text
stringlengths 7
3.69M
|
|---|
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import TestResults from './TestResults';
import * as classroomActions from '../../actions/classroomActions/classroomActions';
const mapStateToProps = ({ classroom }) => {
return {
classroom,
};
};
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators({ ...classroomActions }, dispatch),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(TestResults);
|
$(document).ready(function () {
$("#first").click(function () {
$("#first-desc").fadeIn(4000);
$("#third-desc").hide();
$("#second-desc").hide();
});
});
$(document).ready(function () {
$("#second").click(function () {
$("#second-desc").slideDown(2000);
$("#first-desc").hide();
$("#third-desc").hide();
});
});
$(document).ready(function () {
$("#third").click(function () {
$("#third-desc").slideToggle("slow");
$("#second-desc").hide();
$("#first-desc").hide();
});
});
|
var express = require('express');
var router = express.Router();
const conn = require('../db/db');
const svgCaptcha = require('svg-captcha');
const sms_util = require('../util/sms_util');
const md5 = require('blueimp-md5');
let user = {};
/* 用户相关 */
//一次性图形验证码
router.get('/captcha', (req, res) => {
let captcha = svgCaptcha.create({
color: true,
noise: 2,
ignoreChars: 'Ooli',
size: 4
});
//存储
req.session.captcha = captcha.text.toLocaleLowerCase();
//返回
res.type('svg');
res.send(captcha.data);
});
//获取短信验证码
router.get('/send_code', (req, res) => {
let phone = req.query.phone;
let code = sms_util.randomCode(6);
// sms_util.sendCode(phone, code, function (success) {
// if (success) {
// user.phone = code;
// res.json({ success_code: 200, data: code })
// } else {
// res.json({ err_code: 0, data: '验证码获取失败' })
// }
// })
//成功
user[phone] = code;
res.json({ success_code: 200, data: code })
//失败
/* setTimeout(() => {
res.json({ err_code: 0, data: '验证码获取失败' })
}, 2000); */
});
//手机登录登录
router.post('/login_code', (req, res) => {
const phone = req.body.phone;
const code = req.body.code;
let sql = 'SELECT * FROM user_info WHERE user_phone = ? LIMIT 1';
let data = conn.query(sql, [phone], (error, results, fields) => {
if (error) throw error;
if (results.length) { //已存在
results = JSON.parse(JSON.stringify(results))
req.session.userId = results[0].id;
res.json({
success_code: 200,
data: {
id: req.session.userId,
user_name: results[0]['user_name'],
user_phone: results[0]['user_phone']
}
})
} else { //新用户(用户名是phone)
let addSql = 'INSERT INTO user_info(user_name, user_phone) VALUES (?, ?)';
conn.query(addSql, [phone, phone], (err, results) => {
if (err) throw error;
results = JSON.parse(JSON.stringigy(results));
let sql = 'SELECT * FROM user_info WHERE id = ? LIMIT 1';
conn.query(sql, [results.insertId], (err, results) => {
req.session.usrId = results.insertId;
results = JSON.parse(JSON.stringigy(results));
res.json({
success_code: 200, data: {
id: req.session.usrId,
user_name: results[0]['user_name'],
user_phone: results[0]['user_phone']
}
})
})
})
}
})
});
//有户名密码登录
router.post('/login_pwd', (req, res) => {
const user_name = req.body.name;
const user_pwd = md5(req.body.pwd);
const captcha = req.body.captcha.toLocaleLowerCase();
if (captcha !== req.session.captcha) {
res.json({
err_code: 0,
data: '图形验证码错误'
})
return;
}
delete req.session.captcha;
let sql = 'SELECT * FROM user_info WHERE user_name = ? LIMIT 1';
let data = conn.query(sql, [user_name], (error, results, fields) => {
if (error) throw error;
if (results.length) { //已存在
results = JSON.parse(JSON.stringify(results))
if (results[0].user_pwd !== user_pwd) {
res.json({
err_code: 0,
data: '密码不正确'
})
} else {
req.session.userId = results[0].id;
res.json({
success_code: 200,
data: {
id: req.session.usrId,
user_name: results[0]['user_name'],
user_phone: results[0]['user_phone']
}
})
}
} else { //新用户
let addSql = 'INSERT INTO user_info(`user_name`,`user_pwd`) VALUES(?,?)';
conn.query(addSql, [user_name, user_pwd], (err, results) => {
if (err) throw err;
results = JSON.parse(JSON.stringify(results));
let sql = 'SELECT * FROM user_info WHERE id = ? LIMIT 1';
conn.query(sql, [results.insertId], (err, results) => {
results = JSON.parse(JSON.stringify(results));
if (err) {
res.json({
err_code: 0,
data: '请求失败'
})
} else {
req.session.userId = results[0].id;
res.json({
success_code: 200, data: {
id: results[0].id,
user_name: results[0]['user_name'],
user_phone: results[0]['user_phone']
}
})
}
})
})
}
})
console.log(req.session);
});
//根据用户id获取用户信息
router.get('/user_info', (req, res) => {
let userId = req.session.userId;
let sql = 'SELECT `id`,`user_name`,`user_phone`,`user_sex`,`user_address`,`user_birthday`,`user_sign` FROM user_info WHERE id = ? LIMIT 1';
conn.query(sql, [userId], (err, results) => {
results = JSON.parse(JSON.stringify(results));
if (err) {
res.json({
err_code: 0,
data: '请求失败'
})
} else {
if (results.length) {
res.json({
success_code: 200, data: results[0]
})
} else {
delete req.session.userId;
res.json({
err_code: 1,
data: '请登录'
})
}
}
})
});
//登出
router.get('/logout', (req, res) => {
delete req.session.userId;
res.json({
success_code: 200,
data: '退出成功'
})
});
//修改用户信息
router.post('/change_user_info', (req, res) => {
let id = req.body.user_id;
let user_sex = req.body.user_sex || '';
let user_address = req.body.user_address || '';
let user_birthday = req.body.user_birthday || '';
let user_sign = req.body.user_sign || '';
if (!id) {
res.json({
err_code: 3,
data: '修改用户信息失败'
})
} else {
let sql = 'UPDATE user_info SET user_sex=?, user_address=?, user_birthday=?, user_sign=? WHERE id=' + id;
conn.query(sql, [user_sex, user_address, user_birthday, user_sign], (err, results) => {
if (err) {
res.json({
err_code: 0,
data: '请求失败'
})
} else {
res.json({
success_code: 200, data: '修改信息成功'
})
}
})
}
});
module.exports = router;
|
var itens = [];
function atualizar() {
var table = window.document.getElementById("ta")
var tb = "<tr><td>Nomes</td><td>Email's</td><td>Idades</td><td>Cargos</td></tr>"
for (var i of itens) {
tb = tb + `<tr><td>${i[0]}</td><td>${i[1]}</td><td>${i[2]}</td><td>${i[3]}</td></tr>`;
}
table.innerHTML = tb;
}
function add() {
var nome = window.document.getElementById("nome");
var email = window.document.getElementById("email");
var idade = window.document.getElementById("idade");
var cargo = window.document.getElementById("cargo");
if (nome.value !== "" && email.value !== "" && idade.value !== "" && cargo.value !== "") {
itens.push([nome.value, email.value, idade.value, cargo.value]);
}
nome.value = "";
email.value = "";
idade.value = "";
cargo.value = "";
atualizar();
}
function remove() {
var email = window.document.getElementById("email");
var inr = [];
for (var i of itens) {
if (i[1] === email.value) {
email.value = "";
}
else {
inr.push(i);
}
}
itens = inr;
atualizar();
}
/*
Como ler json:
function carregar(json) {
for(var l of json) {
console.log(`[ ${l["titulo"]} ] ]===> Autor: ${l["autores"]} | Categoria: ${l["categoria"]} | Descrição: ${l["descricao"]}`)
}
}
fetch("http://my-json-server.typicode.com/maujor/livros-json/livros").then(resposta => resposta.json()).then(json => carregar(json))
*/
|
import db from '../src/models';
import sequelizeFixtures from 'sequelize-fixtures';
import { syncDB } from '../src/model-helpers';
// verify that we are not in production
if (process.env.NODE_ENV === 'production') {
console.log("Unable to load database in production (NODE_ENV=='production')");
process.exit(1);
}
const fixtureDir = 'fixtures/';
const fixtures = [
'api-tokens.json',
'customer-roles.json',
'customers.json',
'product-groups.json',
'products.json',
'transactions.json',
'users.js'
].map(file => `./${fixtureDir}${file}`);
syncDB({ force: true })
.then(() => sequelizeFixtures.loadFiles(fixtures, db))
.then(() => {
console.log('Loaded fixtures!');
process.exit(0);
})
.catch(err => {
console.log(err);
process.exit(1);
});
|
const AndhraPradeshDist = [
"Anantapur",
"Chittoor",
"East Godavari",
"Guntur",
"Krishna",
"Kurnool",
"Prakasam",
"Srikakulam",
"Nellore",
"Visakhapatnam",
"Vizianagaram",
"WestGodavari",
"Kadapa",
];
const TelanganaDist = [
"Adilabad",
"Kothagudem",
"Hyderabad",
"Jagtial",
"Jangaon",
"Jayashankar Bhupalpally",
"Jogulamba Gadwal",
"Kamareddy",
"Karimnagar",
"Khammam",
"Kumuram Bheem",
"Mahabubabad",
"Mahabubnagar",
"Mancherial",
"Medak",
"Medchal Malkajgiri",
"Mulugu",
"Nagarkurnool",
"Nalgonda",
"Nirmal",
"Nizamabad",
"Peddapalli",
"Rajanna Sircilla",
"Rangareddy",
"Sangareddy",
"Siddipet",
"Suryapet",
"Vikarabad",
"Wanaparthy",
"Warangal",
"YadadriBhuvanagiri",
];
export const indianStates = {
AndhraPradesh: [...AndhraPradeshDist],
Assam: [],
ArunachalPradesh: [],
Bihar: [],
Goa: [],
Gujarat: [],
JammuKashmir: [],
Jharkhand: [],
WestBengal: [],
Karnataka: [],
Kerala: [],
MadhyaPradesh: [],
Maharashtra: [],
Manipur: [],
Meghalaya: [],
Mizoram: [],
Nagaland: [],
Orissa: [],
Punjab: [],
Rajasthan: [],
Sikkim: [],
TamilNadu: [],
Tripura: [],
Telangana: [...TelanganaDist],
Uttaranchal: [],
UttarPradesh: [],
Haryana: [],
HimachalPradesh: [],
Chhattisgarh: [],
};
|
import {combineReducers} from 'redux';
import { GET_FORMA_PAGO_SUCCESS, SAVE_FORMA_PAGO_SUCCESS, DELETE_FORMA_PAGO_SUCCESS, EDIT_FORMA_PAGO_SUCCESS} from "../../actions/catalogos/formadepagoActions";
function list(state=[], action){
switch(action.type){
case GET_FORMA_PAGO_SUCCESS:
return action.formaP;
case SAVE_FORMA_PAGO_SUCCESS:
return [...state, action.formaP];
case EDIT_FORMA_PAGO_SUCCESS:
let newL = state.filter(a=>{
return a.id!=action.formaP.id
});
return [...newL, action.formaP];
case DELETE_FORMA_PAGO_SUCCESS:
let acualL = state.filter(a=>{
return a.id!=action.formaPId;
});
return acualL;
default:
return state;
}
}
const formadepagoReducer = combineReducers({
list:list,
});
export default formadepagoReducer;
|
const msg = {
id: 'false_554197730230@c.us_DE7B990439AEED793A7B7B3E6F29EA41',
body: '/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEABsbGxscGx4hIR4qLSgtKj04MzM4PV1CR0JHQl2NWGdYWGdYjX2Xe3N7l33gsJycsOD/2c7Z//////////////8BGxsbGxwbHiEhHiotKC0qPTgzMzg9XUJHQkdCXY1YZ1hYZ1iNfZd7c3uXfeCwnJyw4P/Zztn////////////////CABEIAB4APwMBIgACEQEDEQH/xAAtAAADAQEAAAAAAAAAAAAAAAABBAUCAwEBAQEBAAAAAAAAAAAAAAAAAQACA//aAAwDAQACEAMQAAAAXainRfzCM3EVgNNiLs0OPNvAll3vEzbvfl2U0U2//8QAIhAAAgICAQUAAwAAAAAAAAAAAQIAEQMEEhMhMUFRIkJx/9oACAEBAAE/ADsIsTLjb3EyY3B4m6mDYGVytVU3O2IcTMOZ1ZU9R81ZQg+y1ERHY2VNQmjOqUP4mDM62wNGHZ5qFdo7qG7HvOpzYfYM+VWsxdp+mF4C5wLXyjoLFRlb1FxM5EbXf+zBhyqbqbQ8MtCYjZsT9Hr5NXEMqtfkQ66iw0REXvAt3RmXa8KPEZ2Umj2M/8QAGhEBAQADAQEAAAAAAAAAAAAAAQACAxIRIf/aAAgBAgEBPwDpum6ZcpfLqy3I2Lsfrf/EABwRAAICAgMAAAAAAAAAAAAAAAABAhEDEBIxQf/aAAgBAwEBPwCkUikJQ9FFVqONUPh0f//Z',
type: 'image',
t: 1601121190,
notifyName: '',
from: '554197730230@c.us',
to: '554399614929@c.us',
self: 'in',
ack: -1,
invis: false,
isNewMsg: true,
star: false,
recvFresh: true,
caption: 'céi de brigadeiro',
interactiveAnnotations: [],
clientUrl: 'https://mmg.whatsapp.net/d/f/ApWp3RVYboJpFspnoFJR2zxa4AIg5z4gR1lkNG7pdN1Z.enc',
directPath: '/v/t62.7118-24/25074040_2747819088825763_7302467960427566891_n.enc?oh=c1857776543e7be7d04d3a55f77cd57f&oe=5F9A3C6F',
mimetype: 'image/jpeg',
filehash: 'dp/wW9v/+b9aIuPxjYnNLpLO0ytYS7t2HHSfysXJdrE=',
uploadhash: 'XJDkZ2B/lhVymzgqeBfa76xHuU5KLYvHApdZgnkVCac=',
size: 101019,
mediaKey: 'rtUk92mNvX0bzP1lXn2YBYeELSzszzn0xXzWBEC/gBA=',
mediaKeyTimestamp: 1601121189,
isViewOnce: false,
width: 1280,
height: 622,
scanLengths: [9163, 38368, 21015, 32473],
scansSidecar: {},
broadcast: false,
mentionedJidList: [],
isVcardOverMmsDocument: false,
isForwarded: false,
labels: [],
sender: {
id: '554197730230@c.us',
name: 'Henrique',
shortName: 'Henrique',
pushname: 'Henrique',
type: 'in',
isBusiness: false,
isEnterprise: false,
statusMute: false,
labels: [],
formattedName: 'Henrique',
isMe: false,
isMyContact: true,
isPSA: false,
isUser: true,
isWAContact: true,
profilePicThumbObj: {
eurl: 'https://pps.whatsapp.net/v/t61.24694-24/68391512_577539849727400_3416333969002425978_n.jpg?oh=f41cbfd99c13eb753a84654b2a4b0c65&oe=5F7351F2',
id: '554197730230@c.us',
img: 'https://web.whatsapp.com/pp?e=https%3A%2F%2Fpps.whatsapp.net%2Fv%2Ft61.24694-24%2F68391512_577539849727400_3416333969002425978_n.jpg%3Foh%3Df41cbfd99c13eb753a84654b2a4b0c65%26oe%3D5F7351F2&t=s&u=554197730230%40c.us&i=1576538408&n=TqbNxjWDfl6bYIHWpZ0RU6grdTdBNb%2FpEWSXRJpx7qo%3D',
imgFull: 'https://web.whatsapp.com/pp?e=https%3A%2F%2Fpps.whatsapp.net%2Fv%2Ft61.24694-24%2F68391512_577539849727400_3416333969002425978_n.jpg%3Foh%3Df41cbfd99c13eb753a84654b2a4b0c65%26oe%3D5F7351F2&t=l&u=554197730230%40c.us&i=1576538408&n=TqbNxjWDfl6bYIHWpZ0RU6grdTdBNb%2FpEWSXRJpx7qo%3D',
raw: null,
tag: '1576538408'
},
msgs: null
},
timestamp: 1601121190,
content: '/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEABsbGxscGx4hIR4qLSgtKj04MzM4PV1CR0JHQl2NWGdYWGdYjX2Xe3N7l33gsJycsOD/2c7Z//////////////8BGxsbGxwbHiEhHiotKC0qPTgzMzg9XUJHQkdCXY1YZ1hYZ1iNfZd7c3uXfeCwnJyw4P/Zztn////////////////CABEIAB4APwMBIgACEQEDEQH/xAAtAAADAQEAAAAAAAAAAAAAAAABBAUCAwEBAQEBAAAAAAAAAAAAAAAAAQACA//aAAwDAQACEAMQAAAAXainRfzCM3EVgNNiLs0OPNvAll3vEzbvfl2U0U2//8QAIhAAAgICAQUAAwAAAAAAAAAAAQIAEQMEEhMhMUFRIkJx/9oACAEBAAE/ADsIsTLjb3EyY3B4m6mDYGVytVU3O2IcTMOZ1ZU9R81ZQg+y1ERHY2VNQmjOqUP4mDM62wNGHZ5qFdo7qG7HvOpzYfYM+VWsxdp+mF4C5wLXyjoLFRlb1FxM5EbXf+zBhyqbqbQ8MtCYjZsT9Hr5NXEMqtfkQ66iw0REXvAt3RmXa8KPEZ2Umj2M/8QAGhEBAQADAQEAAAAAAAAAAAAAAQACAxIRIf/aAAgBAgEBPwDpum6ZcpfLqy3I2Lsfrf/EABwRAAICAgMAAAAAAAAAAAAAAAABAhEDEBIxQf/aAAgBAwEBPwCkUikJQ9FFVqONUPh0f//Z',
isGroupMsg: false,
isMMS: true,
isMedia: true,
isNotification: false,
isPSA: false,
chat: {
id: '554197730230@c.us',
pendingMsgs: false,
lastReceivedKey: {
fromMe: false,
remote: '554197730230@c.us',
id: 'CA9D2A0B5EDB4E5E462BE666B1479C12',
_serialized: 'false_554197730230@c.us_CA9D2A0B5EDB4E5E462BE666B1479C12'
},
t: 1601121156,
unreadCount: 1,
archive: false,
isReadOnly: false,
muteExpiration: 0,
name: 'Henrique',
notSpam: true,
pin: 0,
msgs: null,
kind: 'chat',
isGroup: false,
contact: {
id: '554197730230@c.us',
name: 'Henrique',
shortName: 'Henrique',
pushname: 'Henrique',
type: 'in',
isBusiness: false,
isEnterprise: false,
statusMute: false,
labels: [],
formattedName: 'Henrique',
isMe: false,
isMyContact: true,
isPSA: false,
isUser: true,
isWAContact: true,
profilePicThumbObj: [Object],
msgs: null
},
groupMetadata: null,
presence: {id: '554197730230@c.us', chatstates: []},
isOnline: true,
lastSeen: null
},
isOnline: true,
lastSeen: null,
chatId: '554197730230@c.us',
quotedMsgObj: null,
mediaData: {
type: 'unknown',
mediaStage: 'INIT',
animationDuration: 0,
animatedAsNewMsg: false,
isViewOnce: false,
_swStreamingSupported: false,
_listeningToSwSupport: false,
isVcardOverMmsDocument: false
}
}
|
StrokeHandler = Class.extend({
drawingAgent: null,
rules: [],
init: function() {
this.setupRules();
this.listen();
},
setupRules: function() {
this.rules = [
new AlphaNumericRule(),
new UnmodifiedRule(),
new ShiftedRule(),
new CtrldRule(),
new SpecialKeyRule()
];
},
listen: function() {
var me = this;
Events.register("INCOMING_KEYSTROKE", this, this.handleStroke);
$(document).keypress(function(e) {
//console.log("code", e.keyCode);
//console.group("KEYPRESS");
//e.stopPropagation();
return me.dispatchStroke(e);
});
$(document).keydown(function(e) {
//console.group("KEYDOWN");
//e.stopPropagation();
return me.dispatchStroke(e);
});
},
dispatchStroke: function(keyEvent) {
//console.log(keyEvent.type, "stroke", keyEvent.keyCode, keyEvent);
var stroke = new Stroke({
keyCode: keyEvent.keyCode,
shifted: keyEvent.shiftKey,
ctrld: keyEvent.ctrlKey,
alted: keyEvent.altKey,
eventType: keyEvent.type,
time: keyEvent.timeStamp
});
Events.trigger("INCOMING_KEYSTROKE", stroke);
Events.trigger("RECORDABLE_KEYSTROKE", stroke);
/*return this.handleStroke(stroke);*/
if (keyEvent.keyCode === 8) {
return false;
}
},
handleStroke: function(stroke) {
this.applyRules(stroke);
console.groupEnd();
},
applyRules: function(stroke) {
for (k=0; k<this.rules.length; k++) {
var r = this.rules[k];
//console.log("checking rule", r.name, "for", stroke.event.type);
if (r.eventType === stroke.eventType) {
var result = r.checkAndResolve(stroke);
if (result !== null) {
Events.trigger("CHARACTER_RESOLVED", result);
//console.log("resolved!");
return;
}
}
}
}
/*
applyRules_: function(stroke) {
for (k=0; k<this.rules.length; k++) {
var r = this.rules[k];
if (r.eventType === stroke.event.type) {
var result = r.checkAndResolve(stroke);
if (result !== null) {
return result;
}
}
}
},
applyRules__: function(stroke) {
for (k=0; k<this.rules.length; k++) {
var r = this.rules[k];
if (r.eventType === stroke.event.type && r.check(stroke)) {
return r.resolve(stroke);
}
}
}*/
});
|
import React from 'react';
import { BoardConfigDialog } from '../containers/BoardConfigDialog';
import { EditStyleDialog } from '../containers/EditStyleDialog';
import { EditTextDialog } from '../containers/EditTextDialog';
import { PieceDialog } from '../containers/PieceDialog';
import { Toolbar } from '../containers/Toolbar';
import staticWrapper from '../enhancers/static';
import BoardAppBar from './BoardAppBar';
import BoardDrawer from './BoardDrawer';
import Canvas from './Canvas';
import styles from '../styles/app.styl';
const App = () => (
<div className={styles.container}>
<BoardAppBar />
<BoardDrawer />
<div className={styles.canvas}>
<Canvas />
</div>
<Toolbar />
<BoardConfigDialog />
<EditStyleDialog />
<EditTextDialog />
<PieceDialog />
</div>
);
export default staticWrapper(App);
|
e = 1;
f = 2;
var h = 1, f;
function m(){
k = 2;
}
|
const fs = require('fs')
const info = require('./os')
const infoText = `
CPUS => ${JSON.stringify(info.osData.cpus)}
SYSTEM => ${JSON.stringify(info.osData.system)}
SERVER => ${JSON.stringify(info.osData.server)}
`;
fs.writeFile('infoText.txt',infoText, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
|
import { GET_CAKES_SUCCESS, GET_CAKES_FAILED, ADD_CAKE_SUCCESS, ADD_CAKE_FAILED } from '../actions'
const startState = {
cakes: [],
getCakesError: false,
addCakeErrors: []
}
const cakes = (state = startState, action) => {
switch (action.type) {
case GET_CAKES_SUCCESS:
return {
...state,
cakes: action.cakes,
getCakesError: false
}
case GET_CAKES_FAILED:
return {
...state,
getCakesError: true
}
case ADD_CAKE_SUCCESS:
return {
...state,
addCakeErrors: []
}
case ADD_CAKE_FAILED:
return {
...state,
addCakeErrors: action.errors
}
default:
return state
}
}
export default cakes
|
// Calculate the total price of one product
function getTotalPrice (oneProduct) {
var unitPrice = oneProduct.querySelector(".unit-cost");
var price = unitPrice.innerHTML;
var quantityItems = oneProduct.querySelector("input");
var quantity = quantityItems.value;
var total = price * quantity;
return total;
}
// Create a click event for the Calculate Prices button + calculate the final price
var success = document.querySelector(".btn-success");
success.onclick = function () {
var allProducts = document.querySelectorAll(".product");
var finalCost = document.querySelectorAll(".final-cost");
var totalPrice = document.querySelector(".total-span");
var sum = 0;
for (i=0;i < allProducts.length; i++){
console.log( getTotalPrice (allProducts[i]) );
finalCost[i].innerHTML = getTotalPrice(allProducts[i]);
sum += getTotalPrice(allProducts[i]);
console.log("The sum is " + sum);
}
totalPrice.innerHTML = sum;
};
// Delete items
var deleteButton = document.querySelectorAll(".btn-delete");
deleteButtonsFunc();
function deleteButtonsFunc() {
deleteButton.forEach( function (element, index) {
element.onclick = function deleteItem(){
console.log("hello delete button onlick");
// confirm with the user that the delete is ok
var isOkay = confirm ("Are you sure you want to delete this item?");
// if the delete is okay, then do this
if (isOkay) {
element.parentNode.parentNode.remove();
}
}
});
}
// Create new item
var createItemButton = document.getElementById('btn-create');
createItemButton.onclick = function createNewItem () {
var element = document.createElement("div");
var personnalizePrice = document.querySelector("#personnalize-cost");
var newPrice = parseInt(personnalizePrice.value);
var personnalizeName = document.querySelector("#personnalize-name");
var newName = personnalizeName.value;
var productList = document.querySelector(".product-list");
element.className = ("product");
element.innerHTML = [
'<div class= "product-name"><span>' + newName + '</span></div>',
'<div class="inline-div"><span>$</span><span class="unit-cost">' + newPrice + '</span></div>',
'<div><div class="quantity inline-div">QTY</div><input type="number" placeholder="0"/></div>',
'<div><span>$</span><span class="final-cost">0.00</span></div>',
'<div><button class="btn btn-delete">Delete</button></div>',
].join("\n");
productList.appendChild(element);
personnalizePrice.value = "";
personnalizeName.value = "";
deleteButton = document.querySelectorAll(".btn-delete");
deleteButtonsFunc();
};
|
/* eslint-disable react/jsx-no-target-blank */
import './style.scss';
const listaDeProjetos = [
{
imagem: 'https://github.com/giovanispaula/PodCastream/blob/main/img/header-parallax.jpg?raw=true',
title: 'PodCastream',
text: 'Compilador de podcasts elaborado para Checkpoint de FrontEnd I',
src: 'https://github.com/giovanispaula/PodCastream'
},
{
imagem: 'https://a-static.mlcdn.com.br/618x463/bloco-de-notas-coloridos-pequeno-tb/yellowimport/1199p/7a505e8854855cf60dea29e67bb40afd.jpeg',
title: 'Notes',
text: 'Projeto de site para criação de notas pessoais, ao estilo Google Keep',
src: 'https://github.com/giovanispaula/CheckpointII-FrontII'
},
{
imagem: 'https://img.freepik.com/vetores-gratis/interior-da-galeria_1284-12766.jpg?size=626&ext=jpg',
title: 'Projeto Fast n Furious',
text: 'Site para adição de imagens, utilizando CSS, JS e HTML',
src: 'https://github.com/giovanispaula/Checkpoint'
}]
const Galeria = ({imagem, title, text, src}) => {
return (
<div className="galeria">
{listaDeProjetos.map((projeto) =>
<card>
<div class="card" id="projects">
<img class="card-img-top" src={projeto.imagem} alt="Imagem do projeto"/>
<div class="card-body">
<h5 class="card-title">{projeto.title}</h5>
<p class="card-text">{projeto.text}</p>
<a href={projeto.src} target="_blank" class="btn btn-primary">GitHub</a>
</div>
</div>
</card>
)
}
</div>
)
}
export default Galeria;
|
define([
'./grouped_timeseries',
'extensions/models/data_source',
'moment-timezone'
],
function (GroupedCollection, DataSource, moment) {
var format = 'YYYY-MM-DD[T]HH:mm:ss';
return GroupedCollection.extend({
queryParams: function () {
var params = {};
var options = this.dataSource.get('query-params');
params.duration = this.duration();
if (options.startAt) {
params.start_at = moment(options.startAt).subtract(this.timeshift(), this.getPeriod()).format(format);
params.duration = this.standardDuration();
}
return params;
},
standardDuration: function () {
var options = this.dataSource.get('query-params');
if (options.duration) {
return options.duration;
} else {
return DataSource.PERIOD_TO_DURATION[this.getPeriod()];
}
},
duration: function () {
return this.timeshift() + this.standardDuration();
},
timeshift: function () {
var seriesList = this.options.axes && this.options.axes.y,
maxTimeshift = _.max(seriesList, function (series) {
return series.timeshift;
});
return (maxTimeshift.timeshift || 0);
},
flatten: function (data) {
data = GroupedCollection.prototype.flatten.apply(this, arguments);
return _.filter(data, function (model) {
return moment(_.last(data)._start_at).diff(model._start_at, this.getPeriod()) < this.standardDuration();
}, this);
},
mergeDataset: function (source, target, axis) {
if (axis.timeshift) {
_.each(source.values, function (model, i) {
model._original_start_at = model._start_at;
model._original_end_at = model._end_at;
var _start_at = moment(model._start_at);
var _end_at = moment(model._start_at);
_start_at.add(axis.timeshift, this.getPeriod()).format(format);
_end_at.add(axis.timeshift, this.getPeriod()).format(format);
if (target.values[i + axis.timeshift]) {
target.values[i + axis.timeshift]['timeshift' + axis.timeshift + ':' + axis.groupId + ':' + this.valueAttr] = model[this.valueAttr];
}
}, this);
} else {
GroupedCollection.prototype.mergeDataset.apply(this, arguments);
}
}
});
});
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//ROUTES
app.use('/', require('./routes/routes'));
app.listen(3000, function() {
console.log('Express server listening');
});
|
const services = require('../../models/services');
const request = require('request');
let VERSION_ARGS={};
for( let key in process.env ) {
if( key.match(/^FIN_.*_(VERSION|HASH|TAG)$/) ) {
VERSION_ARGS[key] = process.env[key];
}
}
module.exports = async (req, res) => {
let arr = [];
for( var key in services.services ) {
let service = services.services[key];
let info = {
id : service.id || key,
urlTemplate : service.urlTemplate,
url : service.url,
description : service.description,
title : service.title,
type : service.type,
supportedTypes : service.supportedTypes
};
if( service.url ) {
try {
let {response} = await requestp({uri: service.url+'/_version'});
if( response.statusCode >= 200 && response.statusCode < 300 ) {
info.version = JSON.parse(response.body);
}
} catch(e) {}
}
arr.push(info);
}
res.json({
versions: VERSION_ARGS,
services : arr
});
}
function requestp(options={}) {
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if( error ) return reject(error);
resolve({response, body});
});
});
}
|
import {createGlobalStyle} from "styled-components"
import tw from "tailwind-styled-components";
/** Body setup */
export const GlobalStyle = createGlobalStyle`
body {
${tw`min-h-screen bg-gray-100 text-sm`}
}
`
/*
styled.div.attrs({
className: "w-full h-screen bg-gray-100 p-2"
})``;
*/
|
const HtmlWebpackPlugin = require("html-webpack-plugin")
const CopyPlugin = require("copy-webpack-plugin")
const TerserPlugin = require("terser-webpack-plugin")
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
module.exports = {
mode: "production",
entry: ["./src/resources/scss/app.scss", "./src/resources/js/app.js"],
output: {
filename: "js/main.js",
path: __dirname + "/dist"
},
module: {
rules: [
{
test: /\.html$/,
use: {
loader: "html-loader",
options: { minimize: true },
},
},
{
test: /\.(png|svg|gif|jpg)$/,
use: {
loader: "html-loader",
options: { minimize: true },
},
},
{
test: /\.(sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader?-url",
"sass-loader",
]
},
{
test: /\.(ttf|eot|svg|gif|webp|png|jpg|woff|woff2)$/,
use: [{
loader: 'file-loader',
}]
},
],
},
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
extractComments: true,
parallel: 4,
}),
new CssMinimizerPlugin({
minimizerOptions: {
preset: [
'default',
{
discardComments: { removeAll: true },
},
],
},
}),
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "./index.html",
}),
new CopyPlugin({
patterns: [
{ from: './src/views/**/*', to: './views' }
],
}),
new MiniCssExtractPlugin({
filename: "css/main.css",
chunkFilename: "css/main.[id].css"
})
],
};
|
import React from "react";
const Landing = props => {
return <h1>Welcome! To get started, click a link in the navbar above.</h1>;
};
export default Landing;
|
import React from "react";
import styles from "./Subscribe.module.css";
const Subscribe = () => {
return (
<form action="#" method="POST" className={styles.subscribe}>
<div>
<h2 className={styles.title}>newsletter</h2>
<input
className={styles.input}
type="email"
name="subscribeEmail"
placeholder="Enter your email to sign up"
required
/>
<button
className={styles.subscribeButton}
type="submit"
onClick={(evt) => evt.preventDefault()}
>
subscribe
</button>
</div>
</form>
);
};
export default Subscribe;
|
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import Bookshelf from '../Components/Bookshelf'
export default function MyReads({ setBooks, books}) {
const [currentlyReading, setCurrentlyReading] = useState([])
const [wantToRead, setWantToRead] = useState([])
const [read, setRead] = useState([])
useEffect(() => {
const sortBooksIntoShelves = () =>{
setCurrentlyReading(
books.filter((b) => {
return b.shelf === 'currentlyReading'
})
)
setWantToRead(
books.filter((b) => {
return b.shelf === 'wantToRead'
})
)
setRead(
books.filter((b) => {
return b.shelf === 'read'
})
)
}
sortBooksIntoShelves()
}, [books]);
return (
<div className="list-books">
<div className="list-books-title">
<h1>MyReads</h1>
</div>
<div className="list-books-content">
<div>
<Bookshelf allBooks={books} setBooks={setBooks} books={currentlyReading} title='Currently Reading' />
<Bookshelf allBooks={books} setBooks={setBooks} books={wantToRead} title='Want To Read' />
<Bookshelf allBooks={books} setBooks={setBooks} books={read} title='Read' />
</div>
</div>
<div className="open-search">
<Link to='/Search'>Add a book</Link>
</div>
</div>
)
}
|
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const passport = require('passport');
const User = require('.././model/User');
const key = require('../config/keys').secret;
module.exports = {
register : async (req, res, next) => {
let {
name,
contact_number,
address,
username,
password,
role
} = req.body;
const foundUser = await User.findOne({ "username": username});
if(foundUser){ return res.status(400).json({ error : 'username is already in use'})};
const foundName = await User.findOne({ "name": name});
if(foundName){ return res.status(400).json({ error : `${name} has already a role`})};
const salt = await bcrypt.genSalt(10);
const passwordHash = await bcrypt.hash(password, salt);
const newUser = new User({
name,
contact_number,
address,
username,
password : passwordHash,
role,
date_updated : Date.now()
});
await newUser.save();
res.status(200).json({
success : true,
message : 'Succesfully Saved',
user : newUser
});
},
logIn : async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });
if(!user) { return res.status(400).json({msg : 'username or password is incorrect', success : false})};
const checkPassword = await bcrypt.compare(password, user.password);
if(!checkPassword) { return res.status(400).json({
msg : 'username or password is incorrect',
success : false
})};
const payload = {
id : user.id,
name : user.name,
username : user.username
}
const token = await jwt.sign({
// iss: 'DavidUy',
sub: payload,
iat: new Date().getTime(),
expiresIn: 604800
}, key);
res.status(200).json({
success : true,
token : `Bearer ${token}`,
user : user,
msg: 'you got your token'
});
}
}
|
'use strict';
const hell = new (require(__dirname + "/helper.js"))({module_name: "ruleset"});
module.exports = function (ruleset) {
/**
* INITIALIZE RULESETS
*
* create default rulesets
*
* @param cb
*/
ruleset.initialize = async function () {
hell.o("start", "initialize", "info");
//create the default rulesets
let default_rulesets = [
{name: "cert", description: "Cert Ruleset"},
{name: "custom", description: "Custom Ruleset"}
];
try {
hell.o("check rulesets", "initialize", "info");
let create_result;
for (const rs of default_rulesets) {
hell.o(["check ruleset", rs.name], "initialize", "info");
create_result = await ruleset.findOrCreate({where: rs}, rs);
if (!create_result) throw new Error("failed to create ruleset " + rs.name);
}
return true;
} catch (err) {
hell.o(err, "initialize", "error");
return false;
}
};
/**
* TOGGLE FULL RULESET
*
* @param name
* @param enabled
* @param options
* @param cb
*/
ruleset.toggleAll = function (ruleset_name, enabled, options, cb) {
hell.o(["start " + ruleset_name, "enabled " + enabled], "toggleAll", "info");
(async function () {
try {
const rule = ruleset.app.models.rule;
hell.o([ruleset_name, "find all rulesets"], "toggleAll", "info");
let rs = await ruleset.find({where: {name: ruleset_name}});
if (!rs) throw new Error(ruleset_name + " could not find ruleset");
let update_input = {enabled: enabled, force_disabled: !enabled, last_modified: new Date()};
let update_result = await rule.updateAll({ruleset: ruleset_name}, update_input);
if (!update_result) throw new Error(ruleset_name + " could not update ruleset ");
hell.o([ruleset_name, update_result], "toggleAll", "info");
hell.o([ruleset_name, "done"], "toggleAll", "info");
cb(null, {message: "ok"});
} catch (err) {
hell.o(err, "toggleAll", "error");
cb({name: "Error", status: 400, message: err.message});
}
})(); // async
};
ruleset.remoteMethod('toggleAll', {
accepts: [
{arg: 'name', type: 'string', required: true},
{arg: 'enabled', type: 'boolean', required: true},
{arg: "options", type: "object", http: "optionsFromRequest"}
],
returns: {type: 'object', root: true},
http: {path: '/toggleAll', verb: 'post', status: 201}
});
/**
* TOGGLE TAG FOR ALL RULES IN A RULESET
*
* @param name
* @param name
* @param enabled
* @param options
* @param cb
*/
ruleset.tagAll = function (ruleset_name, tag_id, enabled, options, cb) {
hell.o([ruleset_name + " start", ruleset_name + " " + " tag: " + tag_id + " enabled: " + enabled], "tagAll", "info");
(async function () {
try {
const rule = ruleset.app.models.rule;
const tag = ruleset.app.models.tag;
hell.o([ruleset_name, "find ruleset"], "tagAll", "info");
let rs = await ruleset.findOne({where: {name: ruleset_name}, include: ["tags"]});
if (!rs) throw new Error(ruleset_name + " could not find ruleset");
hell.o([ruleset_name, "find tag"], "tagAll", "info");
let tag_exists = await tag.findById(tag_id);
if (!tag_exists) throw new Error(ruleset_name + " could not find tag: " + tag_id);
if (enabled) {
hell.o([ruleset_name, "add tag to ruleset"], "tagAll", "info");
let ruleset_tag = await rs.tags.add(tag_exists);
let rules = await rule.find({where: {ruleset: ruleset_name}});
for (let i = 0, l = rules.length; i < l; i++) {
rules[i].tags.add(tag_exists);
}
}
if (!enabled) {
hell.o([ruleset_name, "remove tag from ruleset"], "tagAll", "info");
let ruleset_tag = await rs.tags.remove(tag_exists);
let rules = await rule.find({where: {ruleset: ruleset_name}});
for (let i = 0, l = rules.length; i < l; i++) {
rules[i].tags.remove(tag_exists);
}
}
hell.o([ruleset_name, "done"], "tagAll", "info");
cb(null, {message: "ok"});
} catch (err) {
hell.o(err, "tagAll", "error");
cb({name: "Error", status: 400, message: err.message});
}
})(); // async
};
ruleset.remoteMethod('tagAll', {
accepts: [
{arg: 'name', type: 'string', required: true},
{arg: 'tag', type: 'string', required: true},
{arg: 'enabled', type: 'boolean', required: true},
{arg: "options", type: "object", http: "optionsFromRequest"}
],
returns: {type: 'object', root: true},
http: {path: '/tagAll', verb: 'post', status: 201}
});
};
|
function MsgCenter() {
var msgQueue = [];
var handlers = {};
this.postMsg = function(msgName, msgData, immediately) {
var msg = {
name: msgName,
data: msgData
};
immediately ? msgQueue.unshift(msg) : msgQueue.push(msg);
};
this.regHandler = function(msgName, host, handler) {
if (!handlers[msgName]) {
handlers[msgName] = {};
}
handlers[msgName][host] = handler;
return this;
};
this.unregHandler = function(msgName, host) {
if (handlers[msgName] && handlers[msgName][host]) {
delete handlers[msgName][host];
}
return this;
};
var timer = setInterval(function() {
var msg = msgQueue.shift();
if (msg && handlers[msg.name]) {
for (var i in handlers[msg.name]) {
handlers[msg.name][i](msg.data);
}
}
}, 10);
this.reset = function() {
msgQueue.splice(0);
}
}
var msgCenter = new MsgCenter();
function Game() {
this.level = 'easy';
this.poolWidth = 12;
this.poolHeight = 20;
this.cellSize = 20;
msgCenter.regHandler('game.start', null, function() {
new Pool();
new BlockFactory();
new Gravity();
new Score();
msgCenter.postMsg('score.reset');
msgCenter.postMsg('block.neednew');
}).regHandler('game.over', null, function() {
$('#board').hide();
$('#over').show();
}).regHandler('game.reset', null, function() {
msgCenter.reset();
msgCenter.postMsg('pool.reset');
$('#over').hide();
msgCenter.postMsg('score.reset');
$('#board').show();
msgCenter.postMsg('block.neednew');
});
}
var game = new Game();
$(function() {
msgCenter.postMsg('game.start');
});
|
import React, { Component } from 'react';
class Resume extends Component {
render() {
const divStyle = {
color: "#4f4d4d",
fontWeight: "bold",
};
if(this.props.data){
var skillmessage = this.props.data.skillmessage;
var education = this.props.data.education.map(function(education){
return <div key={education.school}><h3>{education.school}</h3>
<p className="info">{education.degree} <span>•</span><em className="date">{education.graduated}</em></p>
<p>{education.description}</p></div>
})
var work = this.props.data.work.map(function(work){
return <div key={work.company}><h3>{work.company}</h3>
<p className="info">{work.title}<span>•</span> <em className="date">{work.years}</em></p>
<p>{work.description} <br></br> <span style={divStyle}>{work.skills}</span></p>
</div>
})
var languages = this.props.data.skillss.languages;
var frameworks = this.props.data.skillss.frameworks;
var bdds = this.props.data.skillss.bdds;
var cms = this.props.data.skillss.cms;
var deployment = this.props.data.skillss.deployment;
var methods = this.props.data.skillss.methods;
}
return (
<section id="resume">
<div className="row education">
<div className="three columns header-col">
<h1><span>Formation</span></h1>
</div>
<div className="nine columns main-col">
<div className="row item">
<div className="twelve columns">
{education}
</div>
</div>
</div>
</div>
<div className="row work">
<div className="three columns header-col">
<h1><span>Expérience pro</span></h1>
</div>
<div className="nine columns main-col">
<p>Expérience professionnelle en lien direct avec le développement. Vous pouvez consulter mon CV pour avoir un détail des expériences passées.</p>
{work}
</div>
</div>
<div className="row skill">
<div className="three columns header-col">
<h1><span>Skills</span></h1>
</div>
<div className="nine columns main-col">
<p>{skillmessage}
</p>
</div>
<div className="nine columns main-col">
<h3>Langages</h3>
<p className="info">{languages}</p>
<h3>Frameworks</h3>
<p className="info">{frameworks}</p>
<h3>Bases de données</h3>
<p className="info">{bdds}</p>
<h3>CMS</h3>
<p className="info">{cms}</p>
<h3>Déploiement</h3>
<p className="info">{deployment}</p>
<h3>Méthodes</h3>
<p className="info">{methods}</p>
</div>
</div>
</section>
);
}
}
export default Resume;
|
import React, { PropTypes } from 'react'
import Emoji from 'emojione'
var Emojify = React.createClass({
render() {
let { children } = this.props
children = Emoji.toImage(children)
return (
<span dangerouslySetInnerHTML={{__html: children}}/>
)
}
})
export default Emojify
|
'use strict';
var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');
describe('interstellar:app', function () {
before(function (done) {
helpers.run(path.join(__dirname, '../generators/app'))
.withArguments('test-app', '--force')
.inDir(path.join(os.tmpdir(), './temp-test'))
.on('end', done);
});
it('creates files', function () {
assert.file([
"index.html",
"main.es6",
"main.scss",
"README.md",
"head.es6",
"controllers/.gitkeep",
"services/.gitkeep",
"directives/.gitkeep",
"templates/.gitkeep",
"filters/.gitkeep"
]);
});
});
|
// Sample Yelp business URL
// https://www.yelp.com/biz/kings-of-punjab-sunnyvale-2?sort_by=date_desc
var sortBy = encodeURI('sort_by=date_desc');
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
var url = tab.url;
// Replace only on Yelp page of a business
//and only if the URL does not already contain a sort-by parameter
if(url.includes("www.yelp.com/biz") && !(url.includes("sort_by")) ){
var paramStart = (url.indexOf('#') === -1) ? url.length : url.indexOf('#');
var querySymbol = (url.indexOf('?') === -1) ? '?' : '&';
//Construct a new URL by adding the new sort-by parameter
var newUrl = url.substring(0, paramStart) + querySymbol + sortBy +
url.substring(paramStart);
// Now reload the page with the reviews sorted by the provided sort-by parameter
chrome.tabs.update(tab.id, {url: newUrl});
}
}
});
|
$(function() {
// function followHTML(message?) {
// var followedBtn = '<div class="js-messages" message-id="' + message.id + '">'
// return followedBtn;
// }
$('.followBTNHover').hover(function() {
console.log("hover");
$(this).find('a').text("解除");
$(this).css('background-color', 'red');
}, function(){
$(this).find('a').text("フォロー中");
$(this).css('background-color', '#46D89E');
});
$('.followTrigger').on('click', function() {
console.log("clicked")
var parentBox = $(this).closest('.recomendUsers--area')
var userId = $(this).attr("user-id");
var followingId = $(this).attr("following-id");
console.log(followingId);
$.ajax({
type: 'POST',
url: '/relations',
data: {user_id:userId, following_id:followingId}
})
.done(function(data){
console.log(this)
parentBox.remove();
})
.fail(function(){
alert('error');
});
});
$('.followTrigger2').on('click', function() {
console.log("clicked")
var userId = $(this).attr("user-id");
var followingId = $(this).attr("following-id");
console.log(followingId);
$.ajax({
type: 'POST',
url: '/relations',
data: {user_id:userId, following_id:followingId}
})
.done(function(data){
console.log(this)
})
.fail(function(){
alert('error');
});
});
// レコメンドのホバーと色変え
$('.recomendBTNHover').hover(function() {
console.log("recomend!");
$(this).find('a').text("フォロー");
$(this).css('background-color', '#46D89E').css('color', '#ffffff');
}, function(){
$(this).find('a').text("フォロー");
$(this).css('background-color', '#ffffff').css('color', '#21A700');
console.log("white!!");
});
// ここいる?TRTパイセンに相談
// $('.followTrigger').on('click', function() {
// console.log("clicked")
// var parentBox = $(this).closest('.recomendUsers--area')
// var userId = $(this).attr("user-id");
// var followingId = $(this).attr("following-id");
// console.log(followingId);
// $.ajax({
// type: 'POST',
// url: '/relations',
// data: {user_id:userId, following_id:followingId}
// })
// .done(function(data){
// console.log(this)
// parentBox.remove();
// })
// .fail(function(){
// alert('error');
// });
// });
// 人のフォロワーのフォロボタンのホバー挙動をTRTパイセンに相談
// $('.followerFollowBTN').hover(function(){
// console.log('ふぉろーほば');
// $(this).find('a').text('フォロー');
// $(this).css('background-color', '#A3EBCE').css('color', '#ffffff');
// }, function(){
// $(this).find('a').text("フォロー");
// $(this).css('background-color', '#46D89E').css('color', '#ffffff')
// console.log("!!");
// });
});
|
/**
* Increment action
* @return {Object} plain action object
*/
export function increment() {
return {
type: 'INCREMENT'
};
}
/**
* Decrement action
* @return {Object} plain action object
*/
export function decrement() {
return {
type: 'DECREMENT'
};
}
|
import {
GraphQLInt,
GraphQLObjectType,
GraphQLString,
GraphQLNonNull,
GraphQLList
} from 'graphql';
import Resolver from '../../resolver.js'
import addressType from './address.js'
import phoneType from './phone.js'
import historyType from './history.js'
import emailType from './email.js'
let iBorrowerType = new GraphQLObjectType({
name: 'BORROWERINFO',
fields: () => ({
_borrower_id: {type: GraphQLInt },
DATERECORDADDED: { type: GraphQLString },
SCHOOLCODE: { type: GraphQLString },
LASTNAME: { type: GraphQLString },
CITIZENSHIP: { type: GraphQLString },
SCHOOLCERTDATE: { type: GraphQLString },
ACCOUNTID: { type: GraphQLInt },
ALIENIDNUMBER: { type: GraphQLInt },
MIDDLEINITIAL: { type: GraphQLString },
DATELASTCHANGED: { type: GraphQLString },
ENROLLDATE: { type: GraphQLString },
CHANGEDBYUSER: { type: GraphQLString },
SCHOOLBRANCH: { type: GraphQLString },
DRIVERSLICENSE: { type: GraphQLString },
ENROLLEDSTATUS: { type: GraphQLString },
DATEOFBIRTH: { type: GraphQLString },
FIRSTNAME: { type: GraphQLString },
DRIVERSLICENSESTATE: { type: GraphQLString },
GRADSEPDATE: { type: GraphQLString },
ENROLLMENTSOURCE: { type: GraphQLString },
ADDRESSES: {
type: new GraphQLList(addressType),
resolve(obj, args, ast){
return Resolver(obj._borrower_id).Address();
}},
PHONES: {
type: new GraphQLList(phoneType),
resolve(obj, args, ast){
return Resolver(obj._borrower_id).Phone();
}},
EMAILS: {
type: new GraphQLList(emailType),
resolve(obj, args, ast){
return Resolver(obj._borrower_id).Email();
}},
HISTORY: {
type: new GraphQLList(historyType),
args: {
count: {
name: 'count',
type: new GraphQLNonNull(GraphQLInt)
}
},
resolve(obj, args, ast){
return Resolver(obj._borrower_id).History(args.count);
}}
})
});
export default iBorrowerType;
|
import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import {
getAllProducts,
updateProductStateOnLoad,
updateProduct,
} from "../actions/productsActions";
import { Prompt } from "react-router";
import { Formik, Form } from "formik";
import FormikController from "../formikFolder/FormikController";
import { useHistory } from "react-router";
import * as Yup from "yup";
import { Spinner } from "react-bootstrap";
import { useSelector, useDispatch } from "react-redux";
import { Redirect } from "react-router-dom";
import ResultMessage from "../ResultMessage";
function ProductUpdate() {
const dispatch = useDispatch();
const productData = useSelector((state) => state.products);
const [blur, setBlur] = useState(false);
const { id } = useParams();
const [product, setProduct] = useState(null);
const auth = useSelector((state) => state.users);
const history = useHistory();
const dummyVals = {
id: "",
productName: "",
productManufacturer: "",
productQuantity: "",
productPrice: "",
productDescription: "",
views: "",
};
useEffect(() => {
dispatch(updateProductStateOnLoad());
return () => {
dispatch(updateProductStateOnLoad());
};
// eslint-disable-next-line
}, []);
useEffect(() => {
let prod = productData.products.find((product) => product.id === id);
if (prod) {
setProduct(prod);
} else {
dispatch(getAllProducts());
}
// eslint-disable-next-line
}, [productData.products, id]);
const validationSchema = Yup.object({
productName: Yup.string().required("Required"),
productManufacturer: Yup.string().required("Required"),
productPrice: Yup.number()
.typeError("Must be a valid number")
.positive("Price can't be negative")
.required("Required"),
productQuantity: Yup.number()
.typeError("Must be a valid number")
.positive("Quantity can't be negative")
.required("Required"),
productDescription: Yup.string().required("Required"),
});
const OnSubmit = (e) => {
const confirmBox = window.confirm(
"Do you really want to update this item?"
);
if (confirmBox === true) {
console.log(e);
dispatch(updateProduct(e));
setBlur(false);
alert("Successfully Updated");
history.push("/list");
}
};
return auth.loginSuccess ? (
productData.updateLoading ? (
<div
style={{
textAlign: "center",
display: "flex",
flexDirection: "column",
alignItems: "center",
margin: "10%",
}}
>
<Spinner animation='border' style={{ width: "50px", height: "50px" }} />
</div>
) : (
<>
{productData.errors ? (
<ResultMessage color='danger' msg={productData.errors.message} />
) : null}
{product ? (
<>
<Prompt
when={blur}
message='All the Changes will be lost..Are you sure to leave?'
/>
<Formik
initialValues={product || dummyVals}
validationSchema={validationSchema}
onSubmit={OnSubmit}
enableReinitialize='true'
>
{(formik) => {
return (
<Form onBlur={() => setBlur(true)}>
<div>
<div style={{ padding: "20px" }}>
<h3
style={{
textAlign: "center",
margin: "20px",
fontWeight: "bold",
}}
>
Update the Products details here..
</h3>
<hr
style={{
margin: "20px",
}}
></hr>
<div>
<div
style={{
display: "flex",
flexDirection: "column",
marginTop: "40px",
marginLeft: "14%",
}}
>
<FormikController
control='input'
type='text'
label='Product Name'
name='productName'
/>
<FormikController
control='textarea'
type='text'
label='Product Description'
name='productDescription'
/>
<FormikController
control='input'
type='text'
label='Product Manufacturer'
name='productManufacturer'
/>
<FormikController
control='input'
type='text'
label='Product Price'
name='productPrice'
/>
<FormikController
control='input'
type='text'
label='Product Quantity'
name='productQuantity'
/>
<div>
<Link
to='/list'
className='btn btn-dark'
style={{
width: "200px",
fontWeight: "bold",
}}
>
Back to Products List
</Link>
<button
type='submit'
className='btn btn-success'
style={{
width: "200px",
fontWeight: "bold",
marginLeft: "20px",
}}
disabled={!formik.isValid}
>
Update Details
</button>
</div>
</div>
</div>
</div>
<hr></hr>
</div>
</Form>
);
}}
</Formik>
</>
) : (
<h3 className='text-center text-dark my-5'>Checking</h3>
)}
</>
)
) : (
<Redirect to='/login' />
);
}
export default ProductUpdate;
|
// Chapter 2, example 5
// TRY IT OUT: Concatenating Strings
var greetingString = "Hello";
var myName = prompt("Please enter your name", "Bob");
var concatString;
document.write(greetingString + " " + myName + "<br>");
concatString = greetingString + " " + myName;
document.write(concatString);
|
import * as _ from './_';
import * as _Arr from './_Arr';
// https://vocajs.com/
const proto = _.prototypeOf(String);
const protoSlice = proto.slice;
/**
* Adds padding to a string's ends
* @param {string} str
*
* @returns {string}
*/
export const pad = str => ' ' + str + ' ';
/**
* Checks if a string contains a substring
* @param {string} str
* @param {string} substr The substring to check if it exists in the main string
*
* @returns {boolean} Return True or False returned upon checking substring in the main string
*/
export const contains = _.curry2((str, substr) => str.indexOf(substr) !== -1);
/**
* Slice a string for the given indexes
* @param {string} str
* @param {number} from The index from where to start slicing
* @param {number} to The index till where to end slicing
*
* @returns {string}
*/
export const slice = _.curry3((str, from, to) =>
protoSlice.call(str, from, to)
);
/**
* Slice a string from given index to the end
* @param {string} str
* @param {number} from The index from where to start slicing
*
* @returns {string}
*/
export const sliceFrom = _.curry2((str, from) => protoSlice.call(str, from));
/**
* Check if a string starts with a given string
* @param {string} str
* @param {string} substr The substring to check if it comes in starting of the given string
*
* @returns {boolean}
*/
export const startsWith = _.curry2((str, substr) => str.indexOf(substr) === 0);
/**
* Check if a string ends with a given string
* @param {string} str
* @param {string} substring
*
* @returns {boolean}
*/
export const endsWith = _.curry2(
(str, substr) => str.lastIndexOf(substr) === str.length - substr.length
);
/**
* Turns A Sentence To Title Case
* also known as "capital case"
* @param {string} sentence
*
* @returns {string}
*/
export function toTitleCase(sentence) {
const words = _Arr.map(sentence.split(' '), word => {
return `${word.slice(0, 1).toUpperCase()}${word.slice(1).toLowerCase()}`;
});
return _Arr.join(words, ' ');
}
|
import React,{useState} from 'react'
import Dudeme_Logo from "../IMAGES/Dudeme_Logo.png";
import image1 from "../IMAGES/image1.png";
import cart from "../IMAGES/cart.png"; //category-1
import category1 from "../IMAGES/category1.png";
import product1 from "../IMAGES/product1.jpg";
import watch from "../IMAGES/watch.png";
import user from "../IMAGES/user.png";
import brands from "../IMAGES/brands.png";
import menu from "../IMAGES/menu.png";
import './Header.css';
const Products = () => {
const [open,setOpen] = useState(true)
// js for toggle menu
const menuToggle=()=>{
let menuItems=document.getElementById("MenuItems");
open ? menuItems.style.maxHeight="200px" : menuItems.style.maxHeight="0px";
setOpen(!open)
}
return (
<div>
<div className="container">
<div className="navbar">
<div className="logo">
<img src={Dudeme_Logo} alt="logo" width="125px" />
</div>
<nav>
<ul id="MenuItems">
<li><a href="">Home</a></li>
<li><a href="">Products</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact</a></li>
<li><a href="">Account</a></li>
</ul>
</nav>
<img src={cart} alt="cart" width="30px" height="30px" />
<img src={menu} alt="menu-icon" className="menu-icon" onClick={menuToggle} />
</div>
</div>
{/* -------------featured products----------------- */}
<div className="small-container">
<div className="row row-2">
<h2>All Products</h2>
<select>
<option>default shorting</option>
<option>Short by price</option>
<option>Short by popularity</option>
<option>Short by rating</option>
<option>Short by sale</option>
</select>
</div>
<div className="row">
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-half-o"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-half-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-half-o"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-half-o"></i>
</div>
<p>Rs.500/-</p>
</div>
<div className="col-4">
<img src={product1} alt="" />
<h4>Red Printed t shirt</h4>
<div className="rating">
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star"></i>
<i className="fa fa-star-o"></i>
</div>
<p>Rs.500/-</p>
</div>
</div>
<div className="page-btn">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>→</span>
</div>
</div>
{/* -----------------footer--------------------------------- */}
<div className="footer">
<div className="container">
<div className="row">
<div className="footer-col-1">
<h3>Download our app</h3>
<p>download app for android and ios mobile phones</p>
</div>
<div className="footer-col-2">
<img src={Dudeme_Logo} alt="" />
<p>download app for android and ios mobes download app for
android and ios mobile phones</p>
</div>
<div className="footer-col-3">
<h3>Useful Links</h3>
<ul>
<li>Coupons</li>
<li>Blog Post</li>
<li>Return Policy</li>
<li>Join Affilitate</li>
</ul>
</div>
<div className="footer-col-4">
<h3>Follow Us</h3>
<ul>
<li>Facebook</li>
<li>Twitter</li>
<li>Instagram</li>
<li>Youtube</li>
</ul>
</div>
</div>
<hr></hr>
<p className="copyright">Copyright 2021 - Maari bOYZ</p>
</div>
</div>
</div>
)
}
export default Products
|
import React from 'react';
import {Grid, Box, Text, Image, TextInput} from 'grommet';
//import {ImageStamp} from 'grommet-controls';
import Calendar from './assets/calendar.jpg';
import Bell from './assets/bell.jpg';
import Question from './assets/question.jpg';
//import images from './assets'
import './empty.css'
//you can see the images show up in the inspect thing
console.log(Calendar);
console.log(Question);
console.log(Bell);
//images.map(({id, src, title, description}) => <img key={id} src={src} title={title} alt={description} />)
function searchbar(){
//state = {text: ''}
//const[value, setValue] = React.useState('');
//const {text} = this.state;
return(
<div style = {{backgroundColor: '#F9FAFB'}}>
<Grid
rows={['xxsmall']}
columns={['small', 'large', 'small', 'xsmall']}
areas={[
{ name: 'space1', start: [0, 0], end: [0, 0] },
{ name: 'searchbar', start: [1, 0], end: [1, 0] },
{name: 'space2', start: [2, 0], end: [2, 0]},
{name: 'icon', start: [3, 0], end: [3, 0] },
]}
>
<Box gridArea='space1'>
</Box>
<Box gridArea='searchbar' margin = {{'vertical': 'small'}}>
<TextInput size = 'small'
placeholder="Search"
//value={text}
//onChange={event => this.setState({text: event.target.value})}
/>
</Box >
<Box gridArea='space2'>
</Box>
<Box gridArea='icon' direction = 'row' gap = 'large' align = 'center'>
<React.Fragment>
<Box direction = 'row' pad = 'small'>
<Image src = {Question} />
</Box>
<Box direction = 'row' pad = 'small'>
<Image src = {Calendar} />
</Box>
<Box direction = 'row' pad = 'small'>
<Image src = {Bell} />
</Box>
{/* <Image src = {Question} />
<Image src = {Calendar}/>
<Image src = {Bell} /> */}
{/* <Image src = {UserIcon} /> */}
</React.Fragment>
{/* {['start', 'center', 'end'].map(align =>(
<React.Fragment>
<Image src = {Calendar} />
<Image src = {Bell} />
<Image src = {Question} />
</React.Fragment>
))} */}
</Box>
</Grid>
</div>
);
}
export default searchbar;
|
import '@testing-library/jest-dom'
import {render, fireEvent} from '@testing-library/vue'
import VuexTest from './components/Store/VuexTest'
import {store} from './components/Store/store'
// A common testing pattern is to create a custom renderer for a specific test
// file. This way, common operations such as registering a Vuex store can be
// abstracted out while avoiding sharing mutable state.
//
// Tests should be completely isolated from one another.
// Read this for additional context: https://kentcdodds.com/blog/test-isolation-with-react
function renderVuexTestComponent(customStore) {
// Render the component and merge the original store and the custom one
// provided as a parameter. This way, we can alter some behaviors of the
// initial implementation.
return render(VuexTest, {store: {...store, ...customStore}})
}
test('can render with vuex with defaults', async () => {
const {getByTestId, getByText} = renderVuexTestComponent()
await fireEvent.click(getByText('+'))
expect(getByTestId('count-value')).toHaveTextContent('1')
})
test('can render with vuex with custom initial state', async () => {
const {getByTestId, getByText} = renderVuexTestComponent({
state: {count: 3},
})
await fireEvent.click(getByText('-'))
expect(getByTestId('count-value')).toHaveTextContent('2')
})
test('can render with vuex with custom store', async () => {
// This is a silly store that can never be changed.
// eslint-disable-next-line no-shadow
const store = {
state: {count: 1000},
actions: {
increment: () => jest.fn(),
decrement: () => jest.fn(),
},
}
// Notice how here we are not using the helper method, because there's no
// need to do that.
const {getByTestId, getByText} = render(VuexTest, {store})
await fireEvent.click(getByText('+'))
expect(getByTestId('count-value')).toHaveTextContent('1000')
await fireEvent.click(getByText('-'))
expect(getByTestId('count-value')).toHaveTextContent('1000')
})
|
//Revealing module pattern [module is an Object literal, it contains set of related methods]
var repo = function () {
var db = {};
var get = function (id) {
console.log('Getting for db.. pojectId: ' + id);
return {
name: 'A project Id ' + id + ' from db'
};
};
var set = function (project) {
console.log('Saving project in db.. ' + project.name);
}
return {
get: get,
set: set
}
};
module.exports = repo();
|
import React, { createContext, useReducer } from "react";
import { AppReducer } from "./AppReducer";
const initialState = {
usersList: [],
isDataLoaded: false,
snackBarOptions: {
openNotification: false,
notificationType: "success",
notificationMessage: "API is success",
},
};
export const GlobalContext = createContext(initialState);
export const GolbalProvider = ({ children }) => {
const [state, dispatch] = useReducer(AppReducer, initialState);
const fetchUsers = (usersList) => {
dispatch({
type: "FETCH_USERS",
payload: usersList,
});
};
const addUser = (user) => {
dispatch({
type: "ADD_USER",
payload: user,
});
};
const editUser = (payload) => {
dispatch({
type: "EDIT_USER",
payload,
});
};
const removeUser = (id) => {
dispatch({
type: "REMOVE_USER",
payload: id,
});
};
const updateNotificationStatus = (newStatus) => {
dispatch({
type: "UPDATE_NOTIFICATION_STATUS",
payload: newStatus,
});
};
return (
<GlobalContext.Provider
value={{
users: state.usersList,
isDataLoaded: state.isDataLoaded,
snackBarOptions: state.snackBarOptions,
fetchUsers,
addUser,
editUser,
removeUser,
updateNotificationStatus,
}}
>
{children}
</GlobalContext.Provider>
);
};
|
import {applyMiddleware, combineReducers, createStore} from 'redux'
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import reducer from './reducers';
const enhancer = applyMiddleware(thunk, logger());
export default createStore(reducer, enhancer);
|
/**
* @namespace
*/
/**
* Validates form fields within a form.
* @constructor
* @class
* @param {Element} form The form node
*/
kitty.FormValidator = function(form) {
this.form = form;
this.errors = [];
this.validators = [];
};
/**
* Adds a field to be validated against given rules
* @param {String} fieldName The name of the field to validate
* @param {Array[Object]} rules The rules for the validator to check against
* @example
* var formValidator = new kitty.FormValidator(formNode);
* formValidator.addValidator("username", [{
* method: function() {
* // some test here and return true or false
* return true;
* },
* message: "This value for username is unacceptable"
* }])
*/
kitty.FormValidator.prototype.addValidator = function(fieldName, rules) {
var exceptionMessageRules = "Invalid rules. Must provide be an array of rules (at least 1).",
field = this.form.elements[fieldName],
rule,
i;
// if field does not exist
if (!field) {
throw "Invalid form field.";
}
if (!rules) {
throw exceptionMessageRules;
}
if (!rules.length) {
throw exceptionMessageRules;
}
if (rules.length) {
for (i = 0; i < rules.length; i++) {
rule = rules[i];
if (typeof rule.method !== "function" ||
typeof rule.message !== "string") {
throw exceptionMessageRules;
}
}
}
this.validators.push({
fieldName: fieldName,
rules: rules,
field: field
});
};
/**
* Iterates through the list of fields to validate
* @return {Boolean} Returns false if there are errors, otherwise true
* @example
* var formValidator = new kitty.FormValidator(formNode);
* formValidator.validate();
*/
kitty.FormValidator.prototype.validate = function() {
this.errors = [];
var validator = null,
validatorValid = true,
i,
j;
for (i = 0; i < this.validators.length; i++) {
validator = this.validators[i];
for (j = 0; j < validator.rules.length; j++) {
validatorValid = validator.rules[j].method(validator.field,
validator.rules[j].params);
if (!validatorValid) {
this.errors.push({
fieldName: validator.fieldName,
message: validator.rules[j].message
});
break;
}
}
}
return this.errors.length === 0;
};
/**
* Retrieve a list of errors. Typically called after determining that validate
* returned false
* @return {Array[Object]} List of errors in format { fieldName: "",
* message: "" }
*/
kitty.FormValidator.prototype.getErrors = function() {
return this.errors;
};
/**
* Remove a validator from the form validator
* @param {String} fieldName The name of the field to remove from validation
*/
kitty.FormValidator.prototype.removeValidator = function(fieldName) {
var i;
for (i = 0; i < this.validators.length; i++) {
if (this.validators[i].fieldName === fieldName) {
this.validators.splice(i, 1);
break;
}
}
};
/**
* Remove a single rule from a validator
* @param {String} fieldName The name of the field
* @param {Function} ruleFunction The function reference for the rule
*/
kitty.FormValidator.prototype.removeRuleFromValidator = function(fieldName,
ruleFunction) {
var validator = null,
rules,
rule,
i,
j;
for (i = 0; i < this.validators.length; i++) {
validator = this.validators[i];
if (validator.fieldName === fieldName) {
rules = validator.rules;
for (j = 0; j < rules.length; j++) {
rule = rules[j];
if (rule.method === ruleFunction) {
rules.splice(j, 1);
break;
}
}
break;
}
}
};
|
const adminController={
entrarAdmin:(req,res)=>{
res.render("admin")
}
}
module.exports= adminController;
|
const express = require('express');
const service = require('./service');
const pkg = require('./package.json');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
const logger = console;
const app = express();
var http = require('http');
var httpServer = http.createServer(app);
httpServer.listen('8080')
service(app);
// Process application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))
// Process application/json
app.use(bodyParser.json())
const server = app.listen(process.env.PORT || 3000, () => {
logger.info(`${pkg.name} service online\n`);
});
module.exports = server;
|
const mongoose = require('mongoose');
const Joi = require('joi');
Joi.objectId = require('joi-objectid')(Joi);
const now = new Date();
const minDate = new Date(now);
minDate.setFullYear(now.getFullYear() - 50);
const maxDate = new Date();
maxDate.setFullYear(now.getFullYear() + 50);
const todoSchema = new mongoose.Schema({
title: {
type: String,
minlength: 1,
maxlength: 50,
required: true,
},
content: {
type: String,
maxlength: 1000,
required: false,
default: ''
},
due: {
type: Date,
required: false,
default: null
},
priority: {
type: Number,
default: 1
},
done: {
type: Boolean,
required: false,
default: false
},
regDate:{
type: Date,
default: Date.now()
}
});
const Todo = mongoose.model('Todo', todoSchema);
function validate(todo) {
const schema = {
_id: Joi.objectId(),
title: Joi.string().min(1).max(50).required(),
content: Joi.string().max(1000).allow(''),
due: Joi.date().allow(null),
priority: Joi.number().default(1),
done: Joi.boolean().default(false),
regDate: Joi.date().default(Date.now()),
};
return Joi.validate(todo, schema);
}
module.exports = exports = {
Todo,
validateTodo: validate
};
|
let fr = {
"values": {
"buttons:flipper" : "Tourner l'échiquier",
"buttons:first" : "Aller au premier coup",
"buttons:prev" : "Coup précédent",
"buttons:next" : "Coup suivant",
"buttons:play" : "Jouer / arrêter tous les coups",
"buttons:last" : "Aller au dernier coup",
"buttons:deleteVar" : "Effacer la variation",
"buttons:promoteVar" : "Promouvoir la variation",
"buttons:deleteMoves" : "Effacer ce coup et tous les suivants",
"buttons:nags" : "Menu NAGs",
"buttons:pgn" : "Montrer le PGN de la partie",
"buttons:hidePGN" : "Masquer le PGN affiché",
"chess:q": "D",
"chess:k": "R",
"chess:r": "T",
"chess:b": "F",
"chess:n": "C",
"chess:Q": "D",
"chess:K": "R",
"chess:R": "T",
"chess:B": "F",
"chess:N": "C",
"nag:$0": "pas d'annotation",
"nag:$1": "bon coup",
"nag:$1_menu": "Bon coup",
"nag:$2": "mauvais coup",
"nag:$2_menu": "Mauvais coup",
"nag:$3": "coup excellent",
"nag:$3_menu": "Coup excellent",
"nag:$4": "très mauvais coup",
"nag:$4_menu": "Très mauvais coup",
"nag:$5": "coup spéculatif",
"nag:$5_menu": "Coup spéculatif",
"nag:$6": "coup douteux",
"nag:$6_menu": "Coup douteux",
"nag:$7": "coup forcé (tous les autres coups perdent rapidement)",
"nag:$7_menu": "Coup forcé",
"nag:$8": "seul coup (pas d'alternative raisonnable)",
"nag:$8_menu": "Seul coup",
"nag:$9": "le plus mauvais coup",
"nag:$10": "position égale",
"nag:$10_menu": "Position égale",
"nag:$11": "chances égales, position équilibrée",
"nag:$12": "chances égales, position dynamique",
"nag:$13": "position peu claire",
"nag:$13_menu": "Position peu claire",
"nag:$14": "les Blancs ont un avantage minime",
"nag:$14_menu": "Avantage minime blancs",
"nag:$15": "les Noirs ont un avantage minime",
"nag:$15_menu": "Les Noirs ont un avantage minime",
"nag:$16": "les Blancs ont un avantage modéré",
"nag:$17": "les Noirs ont un avantage modéré"
}
}
export default fr
|
db.books.find({},{title:1,isbn:1,pageCount:1,_id:0}).limit(3)
|
let GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
let FacebookStrategy = require('passport-facebook').Strategy;
//load user model
let OtherUsers = require('../../models').OtherUser;
let Users = require('../../models').User;
//load configuration file
const configAuth = require('./auth');
module.exports = (passport) => {
//serialize user for session
passport.serializeUser((user, done) => {
return done(null, user.id);
});
//deserialize user
passport.deserializeUser((id, done) => {
return Users.findById(id).then((user) => {
return done(null, user);
}).catch(error => { return done(error, null); });
});
//Google configuration
passport.use(new GoogleStrategy({
clientID: configAuth.googleAuth.clientID,
clientSecret: configAuth.googleAuth.clientSecret,
callbackURL: configAuth.googleAuth.callbackURL
},
(accessToken, refreshToken, profile, done) => {
// adopt asynchronous method, user won't fire until all data is returned from google
process.nextTick(function() {
let authId = 'google:' + profile.id;
//find user based on their authentication id
return OtherUsers.findOne({ where: { authId: authId } })
.then((user) => {
if (user) return done(null, user);
if (!user) {
//otherwise create user if not found
return OtherUsers.create({
authId: authId,
username: profile.displayName,
email: profile.emails[0].value,
token: accessToken
}).then((newUser) => {
if (newUser) {
return Users.create({
userId: newUser.guid,
username: newUser.username,
email: newUser.email
}).then((createUser) => {
if (createUser) {
return done(null, createUser);
}
});
}
});
}
}).catch(error => { return done(error, null); });
});
}
));
//Facebook configuration
passport.use(new FacebookStrategy({
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
callbackURL: configAuth.facebookAuth.callbackURL,
profileFields: configAuth.facebookAuth.profileFields
},
(accessToken, refreshToken, profile, done) => {
// adopt asynchronous method, user won't fire until all data is returned from google
process.nextTick(function() {
let authId = 'facebook:' + profile.id;
//find user based on their authentication id
return OtherUsers.findOne({ where: { authId: authId } })
.then((user) => {
if (user) return done(null, user);
if (!user) {
//otherwise create user if not found
return OtherUsers.create({
authId: authId,
username: profile.name.givenName + ' ' + profile.name.familyName,
email: profile.emails[0].value,
token: accessToken
}).then((newUser) => {
if (newUser) {
return Users.create({
userId: newUser.guid,
username: newUser.username,
email: newUser.email
}).then((createUser) => {
if (createUser) {
return done(null, createUser);
}
});
}
});
}
}).catch(error => { return done(error, null); });
});
}
));
};
|
import React from 'react';
class List extends React.Component{
render(){
const {value, onClick} = this.props;
return(
<ul>
<li className="list">{this.props.item}<button onClick={()=>onClick(value)} value={value} aria-label="delete" type="button" className="delete">Delete</button></li>
</ul>
)
}
}
export default List;
|
export function checkPlaceHolder(text){
cy.get('.new-todo').should('have.attr','placeholder',text)
}
export function visit(){
cy.visit('/')
}
export function addTodo(text){
cy.get('.new-todo').type(text + '{enter}')
}
export function validateItemsLeft(num){
if(num == 1){
cy.contains(num +' item left').should('have.contain.text', num +' item left')
}
else{
cy.contains(num +' items left').should('have.contain.text', num +' items left')
}
}
export function clearCompleted(){
cy.get('.clear-completed').click()
}
export function completeTodo(position){
cy.get(`.todo-list li:nth-child(${position}) .toggle`).click()
}
export function destroyTodo(position){
cy.get(`.todo-list li:nth-child(${position}) .destroy`).click({force: true})
}
export function checkLabelText(position, text){
cy.get(`.todo-list li:nth-child(${position}) label`).should('have.text', text)
}
export function checked(position){
cy.get(`.todo-list li:nth-child(${position}) .toggle`).should('be.checked')
}
export function textDecoration(position){
cy.get(`.todo-list li:nth-child(${position}) label`).should('have.css', 'text-decoration-line', 'line-through')
}
export function emptyTodoList(){
cy.get('.todo-list').should('not.have.descendants', 'li')
}
|
import Vue from 'vue';
import Router from 'vue-router';
Vue.use(Router);
export default new Router({
mode: 'hash',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'Home',
meta: { title: '首页' },
component: () => import(/* webpackChunkName: "Home" */ '../views/Home.vue'),
redirect: '/homepage',
children: [{
path: '/homepage',
name: 'Homepage',
component: () => import(/* webpackChunkName: "Homepage" */ '../views/homepage'),
},
/* 业务管理 */
{
path: '/business',
name: 'Business',
meta: { title: '业务管理' },
component: () => import(/* webpackChunkName: "Business" */ '../views/business'),
redirect: '/business/phoneAppointment',
children: [{
path: '/business/phoneAppointment',
name: 'BusinessPhoneAppointment',
meta: { title: '电话预约' },
component: () => import(/* webpackChunkName: "BusinessPhoneAppointment" */ '../views/business/phoneAppointment'),
},
{
path: '/business/workManagement',
name: 'BusinessWorkManagement',
component: () => import(/* webpackChunkName: "BusinessWorkManagement" */ '../views/business/workManagement/index'),
redirect: '/business/workManagement/all',
children: [{
path: '/business/workManagement/all',
name: 'BusinessWorkAll',
meta: { title: '全部' },
component: () => import(/* webpackChunkName: "BusinessWorkAll" */ '../views/business/workManagement/numberType/all'),
}, {
path: '/business/workManagement/assign',
name: 'BusinessWorkAssign',
meta: { title: '待指派' },
component: () => import(/* webpackChunkName: "BusinessWorkAssign" */ '../views/business/workManagement/numberType/assign'),
}, {
path: '/business/workManagement/wait',
name: 'BusinessWorkWait',
meta: { title: '待接单' },
component: () => import(/* webpackChunkName: "BusinessWorkWait" */ '../views/business/workManagement/numberType/wait'),
},
{
path: '/business/workManagement/server',
name: 'BusinessWorkServer',
meta: { title: '服务中' },
component: () => import(/* webpackChunkName: "BusinessWorkServer" */ '../views/business/workManagement/numberType/server'),
},
{
path: '/business/workManagement/verify',
name: 'BusinessWorkVerify',
meta: { title: '待审核' },
component: () => import(/* webpackChunkName: "BusinessWorkVerify" */ '../views/business/workManagement/numberType/verify'),
},
{
path: '/business/workManagement/finish',
name: 'BusinessWorkFinish',
meta: { title: '已完成' },
component: () => import(/* webpackChunkName: "BusinessWorkFinish" */ '../views/business/workManagement/numberType/finish'),
},
{
path: '/business/workManagement/termination',
name: 'BusinessWorkTermination',
meta: { title: '已终止' },
component: () => import(/* webpackChunkName: "BusinessWorkTermination" */ '../views/business/workManagement/numberType/termination'),
}],
}, {
path: '/business/workManagement/detail',
name: 'BusinessWorkDetail',
meta: { title: '详情' },
component: () => import(/* webpackChunkName: "BusinessworkDetail" */ '../views/business/workManagement/detail'),
}],
},
/* 人员管理 */
{
path: '/personnel',
name: 'Personnel',
component: () => import(/* webpackChunkName: "Personnel" */ '../views/personnel'),
redirect: '/personnel/service',
children: [{
path: '/personnel/service',
name: 'PersonnelService',
component: () => import(/* webpackChunkName: "PersonnelService" */ '../views/personnel/service'),
},
{
path: '/personnel/service/add',
name: 'PersonnelServiceAdd',
component: () => import(/* webpackChunkName: "PersonnelServiceAdd" */ '../views/personnel/service/add'),
},
],
},
/* 财富管理 */
{
path: '/wealth',
name: 'Wealth',
meta: { title: '财富管理' },
component: () => import(/* webpackChunkName: "Wealth" */ '../views/wealth'),
redirect: '/wealth/masonry',
children: [{
path: '/wealth/masonry',
name: 'wealthMasonry',
meta: { title: '财钻管理' },
component: () => import(/* webpackChunkName: "wealthMasonry" */ '../views/wealth/masonry'),
},
{
path: '/wealth/points',
name: 'wealthPoints',
meta: { title: '贡献分管理' },
component: () => import(/* webpackChunkName: "wealthPoints" */ '../views/wealth/points'),
},
{
path: '/wealth/points/detail/:aaId',
name: 'wealthPointDetail',
meta: { title: '贡献分管理详情' },
component: () => import(/* webpackChunkName: "wealthPointDetail" */ '../views/wealth/points/pointDetail'),
},
{
path: '/wealth/exchange',
name: 'wealthExchange',
meta: { title: '物品兑换管理' },
component: () => import(/* webpackChunkName: "wealthExchange" */ '../views/wealth/exchange'),
},
{
path: '/wealth/goods',
name: 'wealthGoods',
meta: { title: '物品管理' },
component: () => import(/* webpackChunkName: "wealthGoods" */ '../views/wealth/goods'),
},
{
path: '/wealth/addgoods',
name: 'wealthAddGoods',
meta: { title: '新增物品' },
component: () => import(/* webpackChunkName: "wealthAddGoods" */ '../views/wealth/goods/addGoods'),
},
{
path: '/wealth/detailGoods',
name: 'wealthDetailGoods',
meta: { title: '物品管理查看' },
component: () => import(/* webpackChunkName: "wealthDetailGoods" */ '../views/wealth/goods/detailGoods'),
},
{
path: '/wealth/redPacket',
name: 'wealthRedPacket',
meta: { title: '红包管理' },
component: () => import(/* webpackChunkName: "wealthRedPacket" */ '../views/wealth/redPacket'),
}],
}],
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue'),
},
],
});
|
import React, { Component } from 'react';
import Letter from './Letter'
class Letters extends Component {
render() {
const letterStatus = this.props.letterStatus
return (
<div>Available Letters<div>
{Object.keys(letterStatus).map(l => letterStatus[l] ? <Letter className='crossed' letter={l} selectLetter={this.props.selectLetter} /> :
<Letter className='not-crossed' letter={l} selectLetter={this.props.selectLetter}/>) }
</div>
</div>
)
}
}
export default Letters
|
/**
* Created by griga on 11/17/16.
*/
/* https://github.com/indexiatech/redux-immutablejs */
/*
import { createStore } from 'redux';
import { combineReducers } from 'redux-immutablejs';
import Immutable from 'immutable';
import * as reducers from './reducers';
const reducer = combineReducers(reducers);
const state = Immutable.fromJS({});
const store = reducer(state);
export default createStore(reducer, store);
*/
import {createStore, combineReducers, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import {routerReducer} from 'react-router-redux'
import { reducer as formReducer } from 'redux-form'
// Logger with default options
import createLogger from 'redux-logger'
import {config} from '../config/config'
import {handleBodyClasses, dumpLayoutToStorage, layoutReducer} from '../components/layout'
import navigationReducer from '../components/navigation/navigationReducer'
import {userReducer, requestUserInfo} from '../components/user'
import {chatReducer, chatInit} from '../components/chat'
import {eventsReducer} from '../components/calendar'
import outlookReducer from '../routes/outlook/outlookReducer'
import loaderReducer from '../components/Loader/loaderReducer'
import {voiceReducer, VoiceMiddleware} from '../components/voice-control'
import {voiceControlOn} from "../components/voice-control/VoiceActions";
export const rootReducer = combineReducers(
{
routing: routerReducer,
loader: loaderReducer,
layout: layoutReducer,
navigation: navigationReducer,
outlook: outlookReducer,
user: userReducer,
chat: chatReducer,
events: eventsReducer,
voice: voiceReducer,
form: formReducer,
}
);
const logger = createLogger({
//empty options
});
const store = createStore(rootReducer,
applyMiddleware(
//logger, working fine but comment because there is lot of console writing
thunk,
handleBodyClasses,
dumpLayoutToStorage,
VoiceMiddleware
)
);
store.dispatch(requestUserInfo());
store.dispatch(chatInit());
if(config.voice_command_auto){
store.dispatch(voiceControlOn());
}
export default store;
|
export default [
{
tab_name: 'Venue',
venuetabs: [
{
heading: 'Brighton Waterfront Hotel, Brighton, London',
address: '1Hd- 50, 010 Avenue, NY 90001 United States',
t_name: ' Ronaldo König11111' ,
t_phone: '009-215-5595',
t_mail: 'info@example.com',
p_name: ' Ronaldo König',
p_phone: '009-215-5595',
p_mail: 'info@example.com',
}
],
},
{
tab_name: 'Time',
venuetabs: [
{
heading: 'Brighton Waterfront Hotel, Brighton, London',
address: '1Hd- 50, 010 Avenue, NY 90001 United States',
t_name: ' Ronaldo König22222',
t_phone: '009-215-5595',
t_mail: 'info@example.com',
p_name: ' Ronaldo König',
p_phone: '009-215-5595',
p_mail: 'info@example.com',
}
],
},
{
tab_name: 'How to get There',
venuetabs: [
{
heading: 'Brighton Waterfront Hotel, Brighton, London',
address: '1Hd- 50, 010 Avenue, NY 90001 United States',
t_name: ' Ronaldo König3333',
t_phone: '009-215-5595',
t_mail: 'info@example.com',
p_name: ' Ronaldo König',
p_phone: '009-215-5595',
p_mail: 'info@example.com',
}
],
},
]
|
'use strict';
/*
* Auth Controller
* @author Rachel Dotey
* The login and logout controller.
*/
var app = angular.module('editor.controllers', ['ui.bootstrap.showErrors']);
app.controller('ResetPasswordCtrl', ['$rootScope', '$scope', '$stateParams', '$state', 'notifications', 'AuthService',
function($rootScope, $scope, $stateParams, $state, notifications, AuthService) {
$scope.forms = {}; // !Important: Used by form validation
$scope.currentUser = {
email: $stateParams.email || ''
};
$scope.sendResetEmail = function(email) {
if ($scope.forms.resetForm.$valid) {
AuthService.forgotPasswordEmail(email).then(function (results) {
notifications.showSuccess(results);
$state.go('auth.login');
}, function (error) {
notifications.showError(error);
});
} else {
notifications.showError('Please enter a valid email.');
$scope.$broadcast('form-validate');
}
};
}]);
|
import auth from "../services/auth.js";
import viewFinder from "../viewFinder.js";
let view = undefined;
function initialize(domElement) {
view = domElement
}
async function getView(id) {
let ideaRequest = await fetch(`http://localhost:3030/data/ideas/${id}`);
let idea = await ideaRequest.json();
let img = idea.img;
let title = idea.title;
let description = idea.description;
let ideaOwnerId = idea._ownerId;
let imageElement = view.querySelector('.det-img');
let titleElement = view.querySelector('.display-5');
let descriptionElement = view.querySelector('.idea-description');
imageElement.src = img;
titleElement.textContent = title;
descriptionElement.textContent = description;
let deleteButton = view.querySelector('a');
let userId = auth.getUserId();
if (ideaOwnerId != userId) {
deleteButton.setAttribute('hidden', true);
} else {
deleteButton.removeAttribute('hidden');
deleteButton.addEventListener('click', async (e) => {
e.preventDefault();
let deleteRequest = await fetch(`http://localhost:3030/data/ideas/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'X-Authorization': auth.getAccessToken()
}
})
let res = await deleteRequest.json();
console.log(res);
viewFinder.goTo('dashboard');
})
}
return view;
}
let detailsPage = {
initialize,
getView
}
export default detailsPage;
|
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import fetchSeats from './seatsAPI';
const initialState = {
status: 'loading',
ticketQty: 1,
seatNextTo: false,
seats: [],
};
export const fetchSeatsAsync = createAsyncThunk('fetchSeats', async () => {
const response = await fetchSeats();
return response.data;
});
export const seatsReducer = createSlice({
name: 'seatsReducer',
initialState,
reducers: {
changeTickets: (state, { payload }) => {
if (state.seatNextTo) {
const result = payload > 5 ? state : (state.ticketQty = payload);
} else {
state.ticketQty = payload;
}
},
changeSeatNextTo: (state, { payload }) => {
if (state.ticketQty > 5 && !state.seatNextTo) {
state.ticketQty = 5;
}
state.seatNextTo = !state.seatNextTo;
},
highlightSeat: (state, { payload }) => {
state.seats.forEach((seat) => {
if (seat.cords.x === payload.x && seat.cords.y === payload.y) {
if (!seat.marked) {
seat.marked = true;
} else {
seat.marked = !seat.marked;
}
}
});
},
},
extraReducers: {
[fetchSeatsAsync.fulfilled]: (state, action) => {
state.seats = [...action.payload];
state.status = 'idle';
},
[fetchSeatsAsync.pending]: (state, action) => {
state.status = 'loading';
},
},
});
export const { changeTickets, changeSeatNextTo, bookASeat, highlightSeat } =
seatsReducer.actions;
export const selectSeats = (state) => {
const free = state.seatsStore.seats.filter((seat) => !seat.reserved);
const reserved = state.seatsStore.seats.filter((seat) => seat.reserved);
const ticketsQty = +state.seatsStore.ticketQty;
if (state.seatsStore.seatNextTo) {
for (let i = 0; i < free.length; i++) {
if (
free[i + ticketsQty - 1] &&
free[i + ticketsQty - 1].cords.y - free[i].cords.y === ticketsQty - 1
) {
for (let j = 0; j < ticketsQty; j++) {
free[i + j] = { ...free[i + j], avaible: 'true' };
}
}
}
return [...free, ...reserved];
} else {
return state.seatsStore.seats;
}
};
export const ticketsQty = (state) => state.seatsStore.ticketQty;
export const SeatNextTo = (state) => state.seatsStore.seatNextTo;
export const loadingStatus = (state) => state.seatsStore.status;
export default seatsReducer.reducer;
|
function create2DArray(X, Y) {
var arr = [];
for (var i = 0; i < X; i++) {
arr[i] = [];
}
for (var x = 0; x < X; x++) {
for (var y = 0; y < Y; y++) {
arr[x][y] = 0;
}
}
return arr;
}
const Point = require("../common/Point");
const Player = require("./Player");
class Game {
constructor(ID) {
this.ID=ID;
this.mapX = 30;
this.mapY = 30;
this.map = create2DArray(this.mapX, this.mapY);
this.players = [];
this.genRandomMap();
}
genRandomMap() {
for (var x = 0; x < this.mapX; x++) {
for (var y = 0; y < this.mapY; y++) {
this.map[x][y] = Math.floor(Math.random() * 1.3);
}
}
}
join(socket) {
var player = new Player(socket, this);
socket.emit("map", this.map);
socket.emit("you", player.getID());
for (var i = 0; i < this.players.length; i++) {
var a = this.players[i];
this.sendPlayerAToPlayerB(player, a);
}
this.players.push(player);
//send all players to new player
for (var i = 0; i < this.players.length; i++) {
var a = this.players[i];
this.sendPlayerAToPlayerB(a, player);
}
}
leave(socket) {
if (socket.player === null || socket.player === undefined) {
return;
}
removeFromArr(this.players, socket.player);
//send all players that one left
for (var i = 0; i < this.players.length; i++) {
var a = this.players[i];
a.socket.emit("leave", socket.player.getID());
}
socket.player = null;
}
attack(player, input){
switch (input) {
case "W":
{
this.hit(player,0,-1);
break;
}
case "A":
{
this.hit(player,-1,0);
break;
}
case "S":
{
this.hit(player,0,1);
break;
}
case "D":
{
this.hit(player,1,0);
break;
}
}
}
hit(player,cx,cy){
if(!player.canHit()){
return;
}
player.lastHit=Date.now();
for (var i = 0; i < this.players.length; i++) {
var p = this.players[i];
p.socket.emit("attack", player.ID + "." + (player.x+cx) + "." + (player.y+cy));
if(p.x===player.x+cx && p.y===player.y+cy){
this.loseLife(p, 10);
}
}
}
loseLife(player, life){
player.life-=life;
this.updateLife(player);
if(player.life<=0){
var point=this.getSpawnPoint();
player.x=point.x;
player.y=point.y;
player.life=100;
this.updatePlayer(player);
}
}
move(player, input) {
switch (input) {
case "W":
{
this.go(player,0,-1);
break;
}
case "A":
{
this.go(player,-1,0);
break;
}
case "S":
{
this.go(player,0,1);
break;
}
case "D":
{
this.go(player,1,0);
break;
}
}
}
go(player, cx, cy) {
if (!player.canMove()) {
return;
}
if (!this.collide(player.x + cx, player.y + cy)) {
player.x+=cx;
player.y+=cy;
player.lastMove=Date.now();
this.updatePos(player);
}
}
updatePlayer(player){
for (var i = 0; i < this.players.length; i++) {
var p = this.players[i];
this.sendPlayerAToPlayerB(player,p);
}
}
updateLife(player){
for (var i = 0; i < this.players.length; i++) {
var p = this.players[i];
p.socket.emit("life", player.ID + "." + player.life);
}
}
updatePos(player) {
for (var i = 0; i < this.players.length; i++) {
var p = this.players[i];
p.socket.emit("move", player.ID + "." + player.x + "." + player.y);
}
}
collide(x, y) {
if (x < 0 || x >= this.mapX) {
return true;
}
if (y < 0 || y >= this.mapY) {
return true;
}
return this.map[x][y] > 0;
}
sendPlayerAToPlayerB(a, b) {
var sendsocket = b.socket;
var s = a.socket;
var g = a.game;
a.socket = null;
a.game = null;
sendsocket.emit("player", a);
a.socket = s;
a.game = g;
}
getSpawnPoint() {
do {
var x = Math.floor(Math.random() * this.mapX);
var y = Math.floor(Math.random() * this.mapY);
} while (this.map[x][y] === 1);
return new Point(x, y);
}
getAmountPlayer() {
return this.players.length;
}
}
function removeFromArr(arr, elem) {
var position = arr.indexOf(elem);
if (~position)
arr.splice(position, 1);
}
module.exports = Game;
|
(function() {
'use strict';
angular
.module('bq')
.controller('HistoryCtrl', HistoryCtrl);
/* @ngInject */
function HistoryCtrl(common, settings, dataService, $q, $state) {
var vm = this; /*jshint validthis: true */
vm.select = select;
activate();
////////////////
function activate () {
vm.histList = histListInit();
}
function select(item) {
$state.go('app.reader', item.params);
}
function histListInit() {
var hist = settings.history.get();
var histList = [];
var promises = [];
for (var i = 0; i < hist.length; i++) {
var mname = hist[i].moduleId;
if (dataService.bmodules.hasOwnProperty(mname)) {
mname = dataService.bmodules[mname].name;
promises.push(dataService.bmodules[hist[i].moduleId].loadVerse(hist[i].bookId, hist[i].chapterId, 1));
} else {
promises.push('');
}
var bname = hist[i].bookId;
if (common.defaultBooks[bname]) {
bname = common.defaultBooks[bname].short_name;
}
histList.push({
text: mname + ': ' + bname + '. ' + hist[i].chapterId,
params: hist[i]
});
}
$q.all(promises).then(function(versesFull) {
var verses = [];
for (var i = 0; i < versesFull.length; i++) {
verses[i] = versesFull[i].slice(0, 128) + '...';
}
vm.verses = verses;
});
return histList;
}
}
})();
|
import { CHANGE_SEARCH } from '../constants';
import { changeSearch } from '../actions';
describe('Home Actions', () => {
describe('changeSearch', () => {
it('should return the correct type and the passed search', () => {
const fixture = 'Max';
const expectedResult = {
type: CHANGE_SEARCH,
search: fixture
};
expect(changeSearch(fixture)).toEqual(expectedResult);
});
});
});
|
import {
LOGIN_REQUEST,
LOGIN_FAILURE,
LOGIN_SUCCESS,
LOGOUT_SUCCESS,
REGISTER_REQUEST,
REGISTER_SUCCESS,
REGISTER_FAILURE,
} from "./types";
import axios from "../api/axios";
//action for requesting login
const requestLogin = () => {
return {
type: LOGIN_REQUEST,
};
};
//action for recieving login
const receiveLogin = (userShort) => {
return {
type: LOGIN_SUCCESS,
userShort,
};
};
//action for login error
const loginError = (error) => {
return {
type: LOGIN_FAILURE,
error,
};
};
//action for recieving logout
const receiveLogout = () => {
return {
type: LOGOUT_SUCCESS,
};
};
//action for requesting registration
const registerRequest = () => {
return {
type: REGISTER_REQUEST,
};
};
//action for successful registration
const registerSuccess = (user) => {
return {
type: REGISTER_SUCCESS,
user,
};
};
//action for registration error
const registerError = () => {
return {
type: REGISTER_FAILURE,
};
};
//login user dispatch function
export const loginUser = (email, password) => (dispatch) => {
dispatch(requestLogin());
axios
.get("/login", {
params: {
eMail: email,
password,
},
})
.then((response) => {
if( response.data === null){
dispatch(loginError("Incorrect username and/or password"));
} else {
const [firstname, role] = response.data;
dispatch(receiveLogin({ firstname, role }));
}
})
.catch((error) => {
dispatch(loginError("Something went wrong"));
});
};
//logout user dispatch function
export const logoutUser = () => (dispatch) => {
dispatch(receiveLogout());
};
//register user dispatch function
export const registerUser = (
firstname,
lastname,
username,
password,
date,
role
) => (dispatch) => {
dispatch(registerRequest());
axios
.post("/add", {
eMail: username,
fName: firstname,
lName: lastname,
signDate: date,
password,
role,
})
.then(() => {
dispatch(
registerSuccess({ firstname, lastname, username, password, date, role })
);
})
.catch((error) => {
dispatch(registerError());
});
};
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/** @suppress {duplicate} */
var remoting = remoting || {};
/**
* Type definition for the RunApplicationResponse returned by the API.
* @typedef {{
* status: string,
* hostJid: string,
* authorizationCode: string,
* sharedSecret: string,
* host: {
* applicationId: string,
* hostId: string
* }
* }}
*/
remoting.AppHostResponse;
(function() {
'use strict';
/**
* @param {Array<string>} appCapabilities Array of application capabilities.
* @param {remoting.Application} app
* @param {remoting.WindowShape} windowShape
* @param {string} subscriptionToken
*
* @constructor
* @implements {remoting.Activity}
*/
remoting.AppRemotingActivity = function(appCapabilities, app, windowShape,
subscriptionToken) {
/** @private */
this.sessionFactory_ = new remoting.ClientSessionFactory(
document.querySelector('#client-container .client-plugin-container'),
appCapabilities);
/** @private {remoting.ClientSession} */
this.session_ = null;
/** @private {base.Disposables} */
this.connectedDisposables_ = null;
/** @private */
this.app_ = app;
/** @private */
this.windowShape_ = windowShape;
/** @private */
this.subscriptionToken_ = subscriptionToken;
};
remoting.AppRemotingActivity.prototype.dispose = function() {
this.cleanup_();
remoting.LoadingWindow.close();
};
remoting.AppRemotingActivity.prototype.start = function() {
remoting.LoadingWindow.show();
var that = this;
return remoting.identity.getToken().then(function(/** string */ token) {
return that.getAppHostInfo_(token);
}).then(function(/** !remoting.Xhr.Response */ response) {
that.onAppHostResponse_(response);
}).catch(function(/** !remoting.Error */ error) {
that.onConnectionFailed(error);
});
};
remoting.AppRemotingActivity.prototype.stop = function() {
if (this.session_) {
this.session_.disconnect(remoting.Error.none());
}
};
/** @private */
remoting.AppRemotingActivity.prototype.cleanup_ = function() {
base.dispose(this.connectedDisposables_);
this.connectedDisposables_ = null;
base.dispose(this.session_);
this.session_ = null;
};
/**
* @param {string} token
* @return {Promise<!remoting.Xhr.Response>}
* @private
*/
remoting.AppRemotingActivity.prototype.getAppHostInfo_ = function(token) {
var url = remoting.settings.APP_REMOTING_API_BASE_URL + '/applications/' +
this.app_.getApplicationId() + '/run';
// TODO(kelvinp): Passes |this.subscriptionToken_| to the XHR.
return new remoting.AutoRetryXhr({
method: 'POST',
url: url,
oauthToken: token
}).start();
};
/**
* @param {!remoting.Xhr.Response} xhrResponse
* @private
*/
remoting.AppRemotingActivity.prototype.onAppHostResponse_ =
function(xhrResponse) {
if (xhrResponse.status == 200) {
var response = /** @type {remoting.AppHostResponse} */
(base.jsonParseSafe(xhrResponse.getText()));
if (response &&
response.status &&
response.status == 'done' &&
response.hostJid &&
response.authorizationCode &&
response.sharedSecret &&
response.host &&
response.host.hostId) {
var hostJid = response.hostJid;
var host = new remoting.Host(response.host.hostId);
host.jabberId = hostJid;
host.authorizationCode = response.authorizationCode;
host.sharedSecret = response.sharedSecret;
remoting.setMode(remoting.AppMode.CLIENT_CONNECTING);
/**
* @param {string} tokenUrl Token-issue URL received from the host.
* @param {string} hostPublicKey Host public key (DER and Base64
* encoded).
* @param {string} scope OAuth scope to request the token for.
* @param {function(string, string):void} onThirdPartyTokenFetched
* Callback.
*/
var fetchThirdPartyToken = function(
tokenUrl, hostPublicKey, scope, onThirdPartyTokenFetched) {
// Use the authentication tokens returned by the app-remoting server.
onThirdPartyTokenFetched(host['authorizationCode'],
host['sharedSecret']);
};
var credentialsProvider = new remoting.CredentialsProvider(
{fetchThirdPartyToken: fetchThirdPartyToken});
var that = this;
this.sessionFactory_.createSession(this).then(
function(/** remoting.ClientSession */ session) {
that.session_ = session;
session.logHostOfflineErrors(true);
session.getLogger().setLogEntryMode(
remoting.ChromotingEvent.Mode.LGAPP);
session.connect(host, credentialsProvider);
});
} else if (response && response.status == 'pending') {
this.onConnectionFailed(new remoting.Error(
remoting.Error.Tag.SERVICE_UNAVAILABLE));
}
} else {
console.error('Invalid "runApplication" response from server.');
// The orchestrator returns 403 if the user is not whitelisted to run the
// app, which gets translated to a generic error message, so pick something
// a bit more user-friendly.
var error = xhrResponse.status == 403 ?
new remoting.Error(remoting.Error.Tag.APP_NOT_AUTHORIZED) :
remoting.Error.fromHttpStatus(xhrResponse.status);
this.onConnectionFailed(error);
}
};
/**
* @param {remoting.ConnectionInfo} connectionInfo
*/
remoting.AppRemotingActivity.prototype.onConnected = function(connectionInfo) {
var connectedView = new remoting.AppConnectedView(
document.getElementById('client-container'),
this.windowShape_, connectionInfo);
var idleDetector = new remoting.IdleDetector(
document.getElementById('idle-dialog'),
this.windowShape_,
this.app_.getApplicationName(),
this.stop.bind(this));
// Map Cmd to Ctrl on Mac since hosts typically use Ctrl for keyboard
// shortcuts, but we want them to act as natively as possible.
if (remoting.platformIsMac()) {
connectionInfo.plugin().setRemapKeys({
0x0700e3: 0x0700e0,
0x0700e7: 0x0700e4
});
}
// Drop the session after 30s of suspension as we cannot recover from a
// connectivity loss longer than 30s anyways.
this.session_.dropSessionOnSuspend(30 * 1000);
this.connectedDisposables_ =
new base.Disposables(idleDetector, connectedView);
};
/**
* @param {remoting.Error} error
*/
remoting.AppRemotingActivity.prototype.onDisconnected = function(error) {
if (error.isNone()) {
this.app_.quit();
} else {
this.onConnectionDropped_();
}
};
/**
* @param {!remoting.Error} error
*/
remoting.AppRemotingActivity.prototype.onConnectionFailed = function(error) {
remoting.LoadingWindow.close();
this.showErrorMessage_(error);
this.cleanup_();
};
/** @private */
remoting.AppRemotingActivity.prototype.onConnectionDropped_ = function() {
// Don't dispose the session here to keep the plugin alive so that we can show
// the last frame of the remote application window.
base.dispose(this.connectedDisposables_);
this.connectedDisposables_ = null;
if (base.isOnline()) {
this.reconnect_();
return;
}
var rootElement = /** @type {HTMLDialogElement} */ (
document.getElementById('connection-dropped-dialog'));
var dialog =
new remoting.ConnectionDroppedDialog(rootElement, this.windowShape_);
var that = this;
dialog.show().then(function(){
dialog.dispose();
that.reconnect_();
}).catch(function(){
dialog.dispose();
that.app_.quit();
});
};
/** @private */
remoting.AppRemotingActivity.prototype.reconnect_ = function() {
// Hide the windows of the remote application with setDesktopRects([])
// before tearing down the plugin.
this.windowShape_.setDesktopRects([]);
this.cleanup_();
this.start();
};
/**
* @param {!remoting.Error} error The error to be localized and displayed.
* @private
*/
remoting.AppRemotingActivity.prototype.showErrorMessage_ = function(error) {
console.error('Connection failed: ' + error.toString());
remoting.MessageWindow.showErrorMessage(
this.app_.getApplicationName(),
chrome.i18n.getMessage(error.getTag()));
};
})();
|
'use strict'
const webpack = require('webpack')
const webpackMerge = require('webpack-merge')
const commonConfig = require('./webpack.common.js')
const helpers = require('./helpers')
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
const METADATA = {
HOST: process.env.HOST || 'localhost',
PORT: process.env.PORT || 8000,
ENV: process.env.ENV = process.env.NODE_ENV = 'development',
PRODUCTION: false,
DEVELOPMENT: true
}
module.exports = function (env) {
return webpackMerge(commonConfig, {
devtool: 'source-map',
cache: true,
module: {
rules: [
{
test: /\.ts$/,
exclude: [/\.e2e\.ts$/, /\.test\.ts$/],
use: ['ng-annotate-loader', 'awesome-typescript-loader']
},
{
test: [/\.sass$/, /\.scss$/],
loader: ExtractTextWebpackPlugin.extract({
fallbackLoader: 'style-loader',
loader: 'raw-loader!sass-loader'
})
}
]
},
plugins: [
new webpack.LoaderOptionsPlugin({
debug: true
}),
new webpack.DefinePlugin({
ENV: JSON.stringify(METADATA.ENV),
NODE_ENV: JSON.stringify(METADATA.ENV),
PRODUCTION: METADATA.PRODUCTION,
DEVELOPMENT: METADATA.DEVELOPMENT,
'process.env': {
ENV: JSON.stringify(METADATA.ENV),
NODE_ENV: JSON.stringify(METADATA.ENV),
PRODUCTION: METADATA.PRODUCTION,
DEVELOPMENT: METADATA.DEVELOPMENT
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: helpers.reverse([
'polyfills',
'vendor',
'main'
])
})
],
devServer: {
port: METADATA.PORT,
host: METADATA.HOST,
proxy: {
'/api/**': {
target: 'http://localhost:3000',
secure: false
}
},
// HTML5 History API support: no need for # in URLs
// automatically redirect 404 errors to the index.html page
// uses connect-history-api-fallback behind the scenes: https://github.com/bripkens/connect-history-api-fallback
// reference: http://jaketrent.com/post/pushstate-webpack-dev-server/
historyApiFallback: true,
contentBase: helpers.root('src/app') // necessary so that assets are accessible
}
})
}
|
class Player {
constructor() {
// 汎用変数の宣言
let width = window.innerWidth; // ブラウザのクライアント領域の幅
let height = window.innerHeight; // ブラウザのクライアント領域の高さ
//アニメショーン用のパラメーター
this.handLRotation = 0.01;
this.handRRotation = -0.01;
this.footLRotation = -0.01;
this.footRRotation = 0.01;
this.meshFaceRotation = 0.005;
this.bodyFaceRotation = 0.01;
this.meshes = [];
this.groups = [];
this.count = 0;
let MATERIALS = {
m1: {
color: 0xefb886
},
m2: {
color: 0xffcc99
},
m3: {
color: 0xffffff,
side: THREE.DoubleSide
},
m4: {
color: 0x000000,
},
m5: {
color: 0xffffff,
side: THREE.DoubleSide
},
m6: {
color: 0xff2e2e,
}
}
//キャラクターを入れるグループを作成
this.player = new THREE.Group();
//顔用グループ
this.playerFace = new THREE.Group();
this.player.add(this.playerFace);
this.groups.push(this.playerFace);
this.playerFace.rotation.x = Math.PI / 180 * 5;
//顔
let textuer1 = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('images/textuer_l.png')
});
let textuer2 = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('images/textuer_r.png')
});
let textuer3 = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('images/textuer_t.png')
});
let textuer4 = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('images/textuer_u.png')
});
let textuer5 = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('images/textuer_f.png')
});
let textuer6 = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('images/textuer_b.png')
});
let materialFace = new THREE.MultiMaterial([textuer1, textuer2, textuer3, textuer4, textuer5, textuer6])
let geometryFace = new THREE.BoxGeometry(1, 1, 1);
let meshFace = new THREE.Mesh(geometryFace, materialFace);
meshFace.castShadow = true;
this.playerFace.add(meshFace);
this.meshes.push(meshFace);
//口
let geometryMouth = new THREE.BoxGeometry(0.8, 0.1, 0.01);
let materialMouth = new THREE.MeshPhongMaterial(MATERIALS.m6);
let meshMouth = new THREE.Mesh(geometryMouth, materialMouth);
meshMouth.position.z = 0.5;
meshMouth.position.y = meshFace.position.y - 0.35;
this.playerFace.add(meshMouth);
this.meshes.push(meshMouth);
//鼻
let geometryNose = new THREE.BoxGeometry(0.2, 0.2, 0.2);
let materialNose = new THREE.MeshPhongMaterial(MATERIALS.m1);
let meshNose = new THREE.Mesh(geometryNose, materialNose);
meshNose.position.z = 0.5;
meshNose.position.y = meshFace.position.y - 0.15;
this.playerFace.add(meshNose);
this.meshes.push(meshNose);
//耳
let geometryEar = new THREE.BoxGeometry(1.2, 0.3, 0.1);
let materialEar = new THREE.MeshPhongMaterial(MATERIALS.m1);
let meshEar = new THREE.Mesh(geometryEar, materialEar);
meshEar.position.y = -0.1;
meshEar.position.z = 0.1;
this.playerFace.add(meshEar);
this.meshes.push(meshEar);
//目
let lEyeGroup = new THREE.Group();
let rEyeGroup = new THREE.Group();
let geometryGlasses = new THREE.TorusGeometry(0.15, 0.02, 10, 20);
let geometryFrame = new THREE.BoxGeometry(0.2, 0.03, 0.05);
let materialGlasses = new THREE.MeshPhongMaterial(MATERIALS.m4);
let materialEyeBall = new THREE.MeshPhongMaterial(MATERIALS.m4);
let materialEyebrows = new THREE.MeshPhongMaterial(MATERIALS.m4);
let geometryEyebrows = new THREE.BoxGeometry(0.3, 0.05, 0.1);
let geometryEye = new THREE.BoxGeometry(0.3, 0.05, 0.05);
let geometryEyeBall = new THREE.BoxGeometry(0.05, 0.05, 0.05);
let materialEye = new THREE.MeshPhongMaterial(MATERIALS.m5);
let eyeLMesh = new THREE.Mesh(geometryEye, materialEye);
let eyeRMesh = new THREE.Mesh(geometryEye, materialEye);
let eyeBallLMesh = new THREE.Mesh(geometryEyeBall, materialEyeBall);
let eyeBallRMesh = new THREE.Mesh(geometryEyeBall, materialEyeBall);
let eyebrowsLMesh = new THREE.Mesh(geometryEyebrows, materialEyebrows);
let eyebrowsRMesh = new THREE.Mesh(geometryEyebrows, materialEyebrows);
let grassesLMesh = new THREE.Mesh(geometryGlasses, materialGlasses);
let grassesRMesh = new THREE.Mesh(geometryGlasses, materialGlasses);
let grassesFrame = new THREE.Mesh(geometryFrame, materialGlasses);
eyeBallLMesh.position.z = eyeBallRMesh.position.z = 0.02;
eyeBallLMesh.position.y = eyeBallRMesh.position.y = -0.03;
eyeLMesh.position.z = eyeRMesh.position.z = 0.01;
eyeLMesh.position.y = eyeRMesh.position.y = -0.05;
grassesLMesh.position.z = grassesRMesh.position.z = 0.05;
eyebrowsLMesh.position.y = eyebrowsRMesh.position.y = 0.08;
eyebrowsLMesh.position.x = 0.05;
eyebrowsRMesh.position.x = -0.05;
eyebrowsLMesh.position.z = eyebrowsRMesh.position.z = 0.01;
grassesFrame.position.z = 0.55;
grassesFrame.position.y = 0.05;
lEyeGroup.add(eyeLMesh);
lEyeGroup.add(eyeBallLMesh);
lEyeGroup.add(eyebrowsLMesh);
lEyeGroup.add(grassesLMesh);
rEyeGroup.add(eyeRMesh);
rEyeGroup.add(eyeBallRMesh);
rEyeGroup.add(eyebrowsRMesh);
rEyeGroup.add(grassesRMesh);
this.playerFace.add(grassesFrame);
lEyeGroup.position.z = rEyeGroup.position.z = 0.5;
lEyeGroup.position.x = 0.25;
lEyeGroup.position.y = rEyeGroup.position.y = 0.1;
lEyeGroup.rotation.z = Math.PI / 180 * -15;
rEyeGroup.position.x = -0.25;
rEyeGroup.rotation.z = Math.PI / 180 * 15;
this.playerFace.add(lEyeGroup);
this.playerFace.add(rEyeGroup);
//首
this.geometryNeck = new THREE.BoxGeometry(0.2, 0.2, 0.2);
let materialNeck = new THREE.MeshPhongMaterial(MATERIALS.m2);
let meshNeck = new THREE.Mesh(this.geometryNeck, materialNeck);
meshNeck.castShadow = true;
meshNeck.position.y = meshFace.position.y - meshFace.scale.y / 2 - 0.05;
this.meshes.push(meshNeck);
this.playerFace.add(meshNeck);
//体
this.bodyGroup = new THREE.Group();
let geometryBody = new THREE.BoxGeometry(0.5, 0.7, 0.5);
let materialBody = new THREE.MeshPhongMaterial(MATERIALS.m2);
let meshBody = new THREE.Mesh(geometryBody, materialBody);
meshBody.castShadow = true;
meshBody.position.y = meshNeck.position.y - 0.4;
this.meshes.push(meshBody);
this.groups.push(this.bodyGroup);
this.bodyGroup.add(meshBody);
//左手
this.handLGroup = new THREE.Group();
let geometryLhand = new THREE.BoxGeometry(0.8, 0.15, 0.15);
let materialLhand = new THREE.MeshPhongMaterial(MATERIALS.m2);
let meshLhand = new THREE.Mesh(geometryLhand, materialLhand);
meshLhand.castShadow = true;
meshLhand.position.y = meshBody.position.y - 0.05;
meshLhand.position.x = meshBody.position.x + 0.3;
meshLhand.rotation.z = -90 * Math.PI / 180;
this.handLGroup.add(meshLhand);
this.meshes.push(meshLhand);
this.groups.push(this.handLGroup);
this.player.add(this.handLGroup);
//右手
this.handRGroup = new THREE.Group();
let geometryRhand = new THREE.BoxGeometry(0.8, 0.15, 0.15);
let materialRhand = new THREE.MeshPhongMaterial(MATERIALS.m2);
let meshRhand = new THREE.Mesh(geometryRhand, materialRhand);
meshRhand.castShadow = true;
meshRhand.position.y = meshBody.position.y - 0.05;
meshRhand.position.x = meshBody.position.x - 0.3;
meshRhand.rotation.z = 90 * Math.PI / 180;
this.handRGroup.add(meshRhand);
this.meshes.push(meshRhand);
this.groups.push(this.handRGroup);
this.player.add(this.handRGroup);
//左足
this.footLGroup = new THREE.Group();
let geometryLleg = new THREE.BoxGeometry(0.7, 0.15, 0.15);
let materialLleg = new THREE.MeshPhongMaterial(MATERIALS.m2);
let meshLleg = new THREE.Mesh(geometryLleg, materialLleg);
meshLleg.position.y = meshBody.position.y - 0.8;
meshLleg.position.x = meshBody.position.x + 0.2;
meshLleg.rotation.z = -90 * Math.PI / 180;
meshLleg.castShadow = true;
this.footLGroup.add(meshLleg);
this.groups.push(meshLleg);
this.player.add(this.footLGroup);
//右足
this.footRGroup = new THREE.Group();
let geometryRleg = new THREE.BoxGeometry(0.7, 0.15, 0.15);
let materialRleg = new THREE.MeshPhongMaterial(MATERIALS.m2);
let meshRleg = new THREE.Mesh(geometryRleg, materialRleg);
meshRleg.castShadow = true;
meshRleg.position.y = meshBody.position.y - 0.8;
meshRleg.position.x = meshBody.position.x - 0.2;
meshRleg.rotation.z = 90 * Math.PI / 180;
this.footRGroup.add(meshRleg);
this.groups.push(meshRleg);
this.player.add(this.footRGroup);
//パンツ
this.geometryPants = new THREE.Geometry();
let materialPants = new THREE.MeshPhongMaterial(MATERIALS.m3);
this.geometryPants.vertices.push(new THREE.Vector3(0, 0, 0));
this.geometryPants.vertices.push(new THREE.Vector3(0.5, 0, 0));
this.geometryPants.vertices.push(new THREE.Vector3(0.1, -0.2, 0));
this.geometryPants.vertices.push(new THREE.Vector3(0.4, -0.2, 0));
this.geometryPants.vertices.push(new THREE.Vector3(0, 0, -0.5));
this.geometryPants.vertices.push(new THREE.Vector3(0.5, 0, -0.5));
this.geometryPants.vertices.push(new THREE.Vector3(0.1, -0.2, -0.5));
this.geometryPants.vertices.push(new THREE.Vector3(0.4, -0.2, -0.5));
this.geometryPants.faces.push(new THREE.Face3(0, 1, 2));
this.geometryPants.faces.push(new THREE.Face3(3, 2, 1));
this.geometryPants.faces.push(new THREE.Face3(4, 6, 5));
this.geometryPants.faces.push(new THREE.Face3(5, 6, 7));
this.geometryPants.faces.push(new THREE.Face3(0, 2, 6));
this.geometryPants.faces.push(new THREE.Face3(0, 4, 6));
this.geometryPants.faces.push(new THREE.Face3(1, 5, 7));
this.geometryPants.faces.push(new THREE.Face3(1, 3, 7));
this.geometryPants.faces.push(new THREE.Face3(0, 1, 4));
this.geometryPants.faces.push(new THREE.Face3(1, 4, 5));
this.geometryPants.faces.push(new THREE.Face3(2, 3, 6));
this.geometryPants.faces.push(new THREE.Face3(3, 6, 7));
let meshPants = new THREE.Mesh(this.geometryPants, materialPants);
meshPants.position.y = meshBody.position.y - 0.35;
meshPants.position.x = -0.25
meshPants.position.z = 0.25;
meshPants.castShadow = true;
this.geometryPants.computeFaceNormals();
this.meshes.push(meshPants);
this.groups.push(meshPants);
this.bodyGroup.add(meshPants);
this.player.add(this.bodyGroup);
}
create() {
this.render();
return this.player;
}
start() {
this.isMove = true;
}
stop() {
this.isMove = false;
}
//描画
render() {
if (this.isMove === true) {
this.moveHand();
this.moveFoot();
this.faceMove();
this.bodyMove();
this.walk();
}
// animation
requestAnimationFrame(this.render.bind(this));
}
//全体の移動
walk() {
this.player.position.y += 0.005;
}
//顔の移動
faceMove() {
//左手の回転
if (this.playerFace.rotation.z > 0.05) {
this.meshFaceRotation = -0.005;
} else if (this.playerFace.rotation.z < -0.05) {
this.meshFaceRotation = 0.005;
}
this.playerFace.rotation.z += this.meshFaceRotation;
}
//体の移動
bodyMove() {
//左手の回転
if (this.bodyGroup.rotation.y > 0.1) {
this.bodyFaceRotation = -0.01;
} else if (this.bodyGroup.rotation.y < -0.1) {
this.bodyFaceRotation = 0.01;
}
this.bodyGroup.rotation.y += this.bodyFaceRotation;
}
//手の移動
moveHand() {
//左手の回転
if (this.handLGroup.rotation.x > 0.1) {
this.handLRotation = -0.01;
} else if (this.handLGroup.rotation.x < -0.1) {
this.handLRotation = 0.01;
}
this.handLGroup.rotation.x += this.handLRotation;
//右手の回転
if (this.handRGroup.rotation.x > 0.1) {
this.handRRotation = -0.01;
} else if (this.handRGroup.rotation.x < -0.1) {
this.handRRotation = 0.01;
}
this.handRGroup.rotation.x += this.handRRotation;
}
//足の移動
moveFoot() {
//左手の回転
if (this.footLGroup.rotation.x > 0.1) {
this.footLRotation = -0.01;
} else if (this.footLGroup.rotation.x < -0.1) {
this.footLRotation = 0.01;
}
this.footLGroup.rotation.x += this.footLRotation;
//右手の回転
if (this.footRGroup.rotation.x > 0.1) {
this.footRRotation = -0.01;
} else if (this.footRGroup.rotation.x < -0.1) {
this.footRRotation = 0.01;
}
this.footRGroup.rotation.x += this.footRRotation;
}
break () {
this.count += 10;
if (this.count < 90) {
this.player.rotation.x = Math.PI / 180 * this.count;
}
this.player.position.y += (0.5 - this.player.position.y) / 3;
}
}
|
var React = require('react');
var ReactBootstrap = require('react-bootstrap');
var ReactRouterBootstrap = require('react-router-bootstrap');
var Navbar = ReactBootstrap.Navbar;
var Nav = ReactBootstrap.Nav;
var NavItem = ReactBootstrap.NavItem;
var NavItemLink = ReactRouterBootstrap.NavItemLink;
var Grid = ReactBootstrap.Grid;
var Router = require('react-router');
function getApp(ErrorNotification, SessionTimeoutNotification, restrictToRoles, UserStore, UserActions) {
var AdminNavItemLink = restrictToRoles(['procurementAdmin', 'procurementMaster'], NavItemLink);
var OrdererNavItemLink = restrictToRoles(['orderer'], NavItemLink);
return React.createClass({
mixins: [ Router.Navigation ],
getInitialState() {
return UserStore.getState();
},
componentDidMount() {
UserStore.listen(this.onChange);
},
componentWillUnmount() {
UserStore.unlisten(this.onChange);
},
onChange(state) {
if (!state.currentUser) {
this.transitionTo('home');
}
this.setState(state);
},
onLogoutClick() {
UserActions.logoutCurrentUser();
},
render() {
var ordersItem = '';
var titlesLink = '';
var externalOrderLink = '';
var arrivedDeliveriesLink = '';
var myOrdersItem = '';
var costcenterPurchaseOrdersItem = '';
var nameItem = '';
var logoutItem = '';
if (this.state.currentUser) {
ordersItem = (
<AdminNavItemLink to="all_purchase_orders">
Tilaukset
</AdminNavItemLink>
);
titlesLink = (
<AdminNavItemLink to="title_list">
Tuotteet
</AdminNavItemLink>
);
externalOrderLink = (
<AdminNavItemLink to="external_orders">
Ulkoiset tilaukset
</AdminNavItemLink>
);
arrivedDeliveriesLink = (
<AdminNavItemLink to="arrived_deliveries">
Saapuvat tilaukset
</AdminNavItemLink>
);
myOrdersItem = (
<OrdererNavItemLink to="my_purchase_orders">
Omat tilaukset
</OrdererNavItemLink>
);
costcenterPurchaseOrdersItem = (
<NavItemLink to="costcenter_purchase_orders">
Tilaukset kustannuspaikoittain
</NavItemLink>
);
nameItem = (
<NavItem>
{ this.state.currentUser.email }
</NavItem>
);
logoutItem = (
<NavItem onClick={ this.onLogoutClick }>
Kirjaudu ulos
</NavItem>
);
}
return (
<div>
<SessionTimeoutNotification />
<ErrorNotification />
<Navbar brand="HANKI">
<Nav right>
{ ordersItem }
{ titlesLink }
{ externalOrderLink }
{ arrivedDeliveriesLink }
{ costcenterPurchaseOrdersItem }
{ myOrdersItem }
{ nameItem }
{ logoutItem }
</Nav>
</Navbar>
<Grid>
<Router.RouteHandler />
</Grid>
</div>
);
},
});
}
module.exports = getApp;
|
$(document).ready(function() {
$("#content").fadeOut();
$("#content").fadeIn();
function hypo(base, height) {
var hyp = Math.sqrt((base * base) + (height * height));
return hyp
}
function bases(hyp, height) {
var base = Math.sqrt((hyp * hyp) - (height * height));
return base
}
function heights(hyp, base) {
var height = Math.sqrt((hyp * hyp) - (base * base));
return height
}
$("#button").click(function() {
var base = $('#base').val();
var height = $('#height').val();
var hyp = $('#hyp').val();
if (hyp == 0 && base != 0 && height != 0) {
$('#hyp').val(hypo(base, height));
} else if (base == 0 && height != 0 && hyp != 0) {
$('#base').val(bases(hyp, height));
} else if (height == 0 && hyp != 0 && base != 0) {
$('#height').val(heights(hyp, base));
}
});
});
|
import RecoveryPasswordForm from "./RecoveryPasswordForm";
export {RecoveryPasswordForm}
export default RecoveryPasswordForm
|
import { Salad } from "../../class/SaladAPI/Salad"
import store from 'localforage'
// let worker = new PlayingWorker()
// let audioCtx = new (window.AudioContext || window.webkitAudioContext)()
// let audioSrc = audioCtx.createMediaElementSource(playing)
// let analyser = audioCtx.createAnalyser()
// audioSrc.connect(analyser)
// audioSrc.connect(audioCtx.destination)
// analyser.fftSize = 2048
// let bufferLength = analyser.frequencyBinCount
// worker.postMessage({ action: "init", value: Audio })
let initVolume = 8
let maxVolume = 20
const state = {
isPlaying: false,
player: undefined,
playmode: "random",
currentPlaying: undefined,
volume: initVolume,
filter: "",
mute: false,
off: false,
playlist: [],
playingIndex: undefined,
pause: undefined,
mini: false,
progress: 0,
duration: 0.1,
historyCount: 0
}
// getters
const getters = {
}
// actions
const actions = {
insertSong({ commit, state, dispatch }, song) {
commit("addSong", { song: song, front: true })
dispatch("nextSong", true)
},
async nextSong({ commit, state, rootState, dispatch }, next) {
commit("skipSong", next)
if (state.currentPlaying) {
let url = await rootState.salad.getSongUrl(state.currentPlaying)
if (!url) {
dispatch("nextSong")
return
}
state.player.src = url
document.title = state.currentPlaying.name
commit("play")
}
else {
state.player.src = undefined
}
},
// 历史暂时没有和用户绑定,以何形式结合?有待商榷。
async getHistory() {
return await store.getItem("history")
},
saveToHistory({ commit }, song) {
store.getItem("history").then((result) => {
console.log(result)
let history = result || []
let date = new Date()
history = history.concat([{ id: date.getTime(), time: date, song: song }])
if (result) {
store.removeItem("history")
}
store.setItem("history", history).then(
() => {
commit("setHistoryCount", history.length)
}
)
})
// store.setItem("history")
},
initPlayer({ commit, state, dispatch }) {
let player = new Audio()
player.volume = initVolume / maxVolume
player.onended = async () => {
dispatch("saveToHistory", state.currentPlaying)
dispatch("nextSong")
}
player.ontimeupdate = (event) => {
commit('setProgress', event.target.currentTime)
}
player.ondurationchange = (event) => {
commit('setDuration', event.target.duration)
}
player.onpause = (event) => {
state.isPlaying = false
}
player.onplay = (event) => {
state.isPlaying = true
}
const { globalShortcut } = require('electron').remote
globalShortcut.register('MediaNextTrack', () => {
dispatch("nextSong")
})
globalShortcut.register('MediaPlayPause', () => {
state.isPlaying ?
commit("pause") :
commit("play")
})
commit("setPlayer", player)
}
}
// mutations
const mutations = {
setFilter(state, filter) {
state.filter = filter
},
setHistoryCount(state, count) {
state.historyCount = count
},
setPlayer(state, player) {
state.player = player
},
setDuration(state, duration) {
state.duration = duration
},
setProgress(state, progress) {
state.progress = progress
},
skipSong(state, next) {
if (state.playmode == 'order' || next) {
state.currentPlaying = state.playlist.shift() || undefined
return
}
if (state.playmode == "repeat") {
return
}
if (state.playmode == 'random') {
let count = Math.floor(Math.random() * state.playlist.length)
state.currentPlaying = state.playlist.splice(count, 1)[0] || undefined
return
}
},
addSong(state, { song, front }) {
if (song instanceof Array) {
state.playlist = state.playlist.concat(song)
return
}
state.playlist[front ? "unshift" : "push"](song)
},
minify(state) {
let remote = require("electron").remote.getCurrentWindow()
let position = remote.getBounds()
// remote.setSize(state.mini ? 360 : 50, state.mini ? 500 : 360)
if (state.mini) {
document.body.style.transition = "all 0.3s"
document.body.style.opacity = 0
remote.setSkipTaskbar(false)
setTimeout(() => {
remote.setBounds({ x: position.x - 310, y: position.y, width: 360, height: 500 })
remote.setAlwaysOnTop(!state.mini)
setTimeout(() => {
document.body.style.width = 360 + "px"
document.body.style.height = 500 + "px"
document.body.style.opacity = 1
state.mini = !state.mini
}, 300)
}, 250)
}
else {
document.body.style.transition = "all 0.3s"
document.body.style.opacity = 0
document.body.style.width = (state.mini ? 360 : 50) + "px"
document.body.style.height = (state.mini ? 500 : 360) + "px"
remote.setSkipTaskbar(true)
remote.setAlwaysOnTop(!state.mini)
setTimeout(() => {
remote.setBounds({ x: state.mini ? position.x - 310 : position.x + 310, y: position.y, width: state.mini ? 360 : 50, height: state.mini ? 500 : 360 })
document.body.style.opacity = 1
state.mini = !state.mini
}, 300)
}
},
setPlayingInfo(state, info) {
state.playingInfo = info
},
// addSong(state, song, info) {
// state.isPlaying = true
// if (!song.url) {
// //应弹出全局提示
// nextSong()
// }
// // if (state.playing) {
// // state.playing.unload()
// // }
// // state.playing = new Howl({ src: [song.url], loop: true, usingWebAudio: true, volume: state.volume / 20, mute: state.mute })
// state.playing.src = song.url
// state.playing.play()
// state.pause = false
// console.log(state)
// state.playing.onended = nextSong
// mutations.setPlayingInfo(state, info)
// if (info.album && info.album.coverlink) {
// Vibrant.from(info.album.coverlink).getPalette().then((res) => {
// state.playingTheme = res
// })
// }
// },
setVolume(state, volume) {
if (volume > 20) {
return
}
if (volume < 0) {
if (state.mute) {
state.mute = false
state.player.muted = state.mute
}
state.off = true
return
}
state.volume = volume
state.player.volume = state.volume / 20
if (state.mute) {
state.mute = false
state.player.muted = state.mute
}
if (state.off) {
state.off = false
}
return
},
setMute(state, mute) {
state.mute = mute
state.player.muted = state.mute
return
},
seek(state, sec) {
if (state.player) {
state.player.currentTime = sec
}
},
pause(state) {
if (state.player) {
state.player.pause()
state.pause = true
}
},
play(state) {
if (state.player) {
state.player.play()
state.pause = false
}
},
setMode(state, mode) {
state.playmode = mode
},
clearPlaylist(state) {
state.playlist = []
},
deletePlaylist(state, index) {
state.playlist.splice(index, 1)
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
|
const knex = require('knex');
const knexConfig = require('../knexfile');
const db = knex(knexConfig.development);
module.exports = {
getProject,
// getProjectActions,
addProject,
addActions,
};
function getProject(id) {
return db('projects')
.where({ id })
.first()
.then(project => {
if (project) {
return db('actions')
.where({ project_id: id })
.then(actions => {
project = projectClean(project);
actions = actionClean(actions);
project.actions = actions;
return project;
});
} else {
return null;
}
});
}
// function getProject(id) {
// let query = db('projects');
// query.where({ id }).first();
// const promises = [query, this.getProjectActions(id)];
// return Promise.all(promises).then(results => {
// let [ project, actions ] = results;
// project = projectClean(project);
// actions = actionClean(actions);
// project.actions = actions;
// return project;
// })
// }
// function getProjectActions(projectId) {
// return db('actions')
// .where('project_id', projectId)
// }
function addProject(project) {
return db('projects')
.insert(project)
.into('projects');
}
function addActions(action) {
return db('actions')
.insert(action)
.into('actions');
}
//Helper functions
function toBoolean(int) {
return int === 1 ? true : false;
}
function actionClean(actions) {
actions = actions.map(action => {
const { project_id, ...test } = action;
return {
...test,
completed: toBoolean(action.completed),
};
});
return actions;
}
function projectClean(project) {
return {
...project,
completed: toBoolean(project.completed),
};
}
|
/**
* Created by gullumbroso on 09/07/2016.
*/
angular.module('DealersApp')
/**
* The controller that is responsible for checkout's view behaviour.
* @param $scope - the isolated scope of the controller.
* @param $mdDialog - the mdDialog service of the Material Angular library.
*/
.controller('PurchaseDetailsController', ['$scope', '$rootScope', '$routeParams', '$location', '$mdDialog', '$mdMedia', 'ActiveSession', 'Purchase', 'Product', 'Dealer', 'ShippingMethods', 'Translations',
function ($scope, $rootScope, $routeParams, $location, $mdDialog, $mdMedia, ActiveSession, Purchase, Product, Dealer, ShippingMethods, Translations) {
var DOWNLOADED_STATUS = "downloaded";
var DOWNLOADING_STATUS = "downloading";
var FAILED_STATUS = "failed";
var ACTIVE_SESSION_PURCHASE_KEY = "PURCHASE";
$scope.downloadedDelivery = false;
initializeView();
function initializeView() {
$scope.status = DOWNLOADING_STATUS;
$scope.screenIsSmall = $mdMedia('xs');
$scope.purchase = ActiveSession.getTempData(ACTIVE_SESSION_PURCHASE_KEY); // Retrieves the product from the Active Session service.
$scope.isDealer = false; // Whether the user is the dealer of this purchase or not.
if (!$scope.purchase) {
// There is no purchase in the session, download it form the server.
downloadPurchase();
} else {
$scope.status = DOWNLOADED_STATUS;
setPurchaseDetails();
}
}
function downloadPurchase() {
var purchaseID = $routeParams.purchaseID;
Purchase.getPurchase(purchaseID)
.then(function (result) {
$scope.status = DOWNLOADED_STATUS;
$scope.purchase = result.data;
setPurchaseDetails();
}, function (httpError) {
$scope.status = FAILED_STATUS;
$scope.errorMessage = "Couldn't download the purchase object.";
$scope.errorPrompt = "Please try again...";
});
}
function downloadDelivery() {
ShippingMethods.getDelivery($scope.purchase.delivery)
.then(function (response) {
$scope.delivery = response.data;
$scope.delivery = ShippingMethods.convertDeliveryFromServer($scope.delivery);
if ($scope.delivery.delivery_method == ShippingMethods.DEALERS_METHOD) {
$scope.delivery.title = ShippingMethods.DEALERS_SHIPPING_TITLE;
} else if ($scope.delivery.delivery_method == ShippingMethods.PICKUP_METHOD) {
$scope.delivery.title = ShippingMethods.PICKUP_TITLE;
}
$scope.downloadedDelivery = true;
}, function (err) {
console.log("There was an error while downloading the delivery method: " + err.data);
});
}
function setPurchaseDetails() {
$scope.shipping_address = $scope.purchase.shipping_address;
downloadDelivery();
if (!$scope.purchase.buyer.id) {
// purchase.buyer contains the id of the buyer. Need to download his name and photo.
Dealer.getShortDealer($scope.purchase.buyer)
.then(function (result) {
$scope.purchase.buyer = result.data;
}, function (httpError) {
console.log("Couldn't download the buyer's name and photo.");
})
}
var dealerID = $scope.purchase.dealer.id ? $scope.purchase.dealer.id : $scope.purchase.dealer;
$scope.isDealer = dealerID == $rootScope.dealer.id;
var key = $scope.purchase.currency;
$scope.purchase.currency = Product.currencyForKey(key);
if ($scope.purchase.deal.id) {
downloadProduct($scope.purchase.deal.id);
} else {
downloadProduct($scope.purchase.deal);
}
}
function downloadProduct(productID) {
Product.getProduct(productID)
.then(function (result) {
$scope.product = result.data;
$scope.product = Product.mapData($scope.product);
}, function (httpError) {
$scope.status = FAILED_STATUS;
$scope.errorMessage = "Couldn't download the product";
$scope.errorPrompt = "Please try again...";
});
}
/**
* Set the title of the mark button according to the status of the purchase object.
* @param purchase - the purchase object.
* @returns {string} the title of the button.
*/
$scope.markButtonTitle = function (purchase) {
if (!purchase) return "";
if ($scope.isDealer) {
if (purchase.status == Purchase.SENT_STATUS) {
return Translations.purchaseDetails.sent;
} else if (purchase.status == Purchase.RECEIVED_STATUS) {
return Translations.purchaseDetails.received
} else {
return Translations.purchaseDetails.markSent;
}
} else {
if (purchase.status == Purchase.RECEIVED_STATUS) {
return Translations.purchaseDetails.received;
} else {
return Translations.purchaseDetails.markReceived;
}
}
};
/**
* Returns the appropriate representation of the purchase's status.
* @param purchase - the purchase.
* @returns {string} the representation.
*/
$scope.parseForPresentation = function (purchase) {
if (purchase.status == Purchase.PURCHASED_STATUS) {
return Translations.purchaseDetails.purchased;
} else if (purchase.status == Purchase.SENT_STATUS) {
return Translations.purchaseDetails.sent;
} else if (purchase.status == Purchase.RECEIVED_STATUS) {
return Translations.purchaseDetails.received;
}
};
$scope.$on('$destroy', function () {
ActiveSession.removeTempData(ACTIVE_SESSION_PURCHASE_KEY);
});
}]);
|
import React, {Component} from "react";
import "./AddTodo.css";
export class AddTodo extends Component {
state = {
title: ""
};
onChange = (e) => {
this.setState({[e.target.name]: e.target.value})
}
onSubmit = (e) => {
e.preventDefault();
this.props.addTodo({id: Date.now(), title: this.state.title})
this.setState({title: ""})
}
render() {
return (
<form id="add-todo" onSubmit={this.onSubmit}>
<h1>Добавить задачу</h1>
<div className="form-group">
<label htmlFor="title">Название</label>
<input className="form-control" type="text" name="title" value={this.state.title} onChange={this.onChange}/>
</div>
<button className="btn btn-success" type="submit">Добавить</button>
</form>
)
}
}
export default AddTodo
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _dns = require("dns");
/**
* IndexModel类,生成一段异步的数据
* @author 学彤
*/
class IndexModel {
contructor() {}
/**
* 获取具体的API接口数据,返回异步处理结果
* @author 学彤
*/
getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Hello IndexAction");
}, 1000);
});
}
}
exports.default = IndexModel; /**
* 实现Index的数据模型
* @author 学彤
*/
|
sap.ui.define([], function () {
"use strict";
return {
getData: async function () {
return await jQuery.get("/api/v1/data");
},
initializeWebSocket: function(fnHandler) {
const socket = new SockJS('/gs-guide-websocket');
const stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/data', fnHandler);
});
},
}
});
|
const jwt = require('jsonwebtoken');
exports.auth = (req, res, next) => {
var token = req.cookies.jwt;
// console.log("token = "+ token);
// console.log("Ab hoga Authorization");
if(!token){
console.log("Please Login First !!!!");
res.redirect('/');
return ;
}
try{
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, payload) => {
if(err) {
// console.log("Please enter the correct password");
// console.log(err);
res.cookie("jwt", "", {secure: true, httpOnly: true})
res.redirect('/');
return;
}
req.payload = payload;
next();
})
}catch(e){
// console.log("Please enter the correct password");
res.cookie("jwt", "", {secure: true, httpOnly: true})
res.redirect('/');
}
}
|
App.controller('home', function (page) {
// Prevent user from navigating back to signup page
$(page).on('appBeforeBack', function() { return false; });
var $tmpl = $(page).find('ul li.app-button').remove();
var $lists = $(page).find('ul.app-list');
var $spinner = $(page).find('.loading-wrapper');
function fetchLists(username) {
API.auth('GET','/users/'+username+'/todo-lists', '', function (res, status) {
$spinner.hide();
if (status !== 200) {
App.dialog({
title : 'Sign in failed',
text : 'Looks like there was an issue signing in. Try again in a bit.',
cancelButton : 'Close'
});
} else {
res.forEach(function (todo) {
var obs = observable(todo);
App.lists.addList(obs);
});
}
});
};
function bindValue(input, property, observable) {
input.value = observable();
observable.subscribe(function(){ input.value = observable(); });
};
App.lists.subscribe(function (obs) {
var $list = $tmpl.clone(true);
$list.text(obs().name);
obs.subscribe(function (newTodo) {
$list.text(newTodo.name);
});
$list.on('click', function (event) {
App.load('todoList', {observer: obs});
});
$lists.append($list);
});
// Get user's todo lists (order by so can use recents)
kik.getUser(function (user) {
if (user) fetchLists(user.username);
});
// Setup listener for new list
if (kik.utils.platform.os.name === 'android') {
var $newList = $(page).find('.android-add-button');
} else {
var $newList = $(page).find('.ios-add-button');
}
$newList.on('click', function (event) {
App.load('todoList');
});
});
|
/*
* @class NoteView
* @extends Backbone.View
*/
var NoteView = Backbone.View.extend({
tagName: 'article',
className: 'note inactive-note',
template: Handlebars.compile( $('#note-template').html() ),
initialize: function(options) {
this.stacksCollection = options.stacksCollection;
this.listenTo(this.model, 'change', this.render);
this.showUnarchivedNotes = options.showUnarchivedNotes;
this.showArchivedNotes = options.showArchivedNotes;
},
events: {
'click input.delete': 'deleteNote',
'click input.edit': 'editNote',
'click h1.note': 'toggleActive'
},
toggleActive: function(event) {
event.stopPropagation();
event.preventDefault();
var _this = this;
this.model.fetch();
$(this.$el).toggleClass('inactive-note');
if (!this.$el.hasClass('inactive-note')) {
$('.note-body', this.$el).slideDown(200, function(){
_this.makeVisible();
});
} else {
$('.note-body', this.$el).slideUp(200);
}
},
/** Scroll the body so that this note is visible
* @param {Function} optional callback */
makeVisible: function(callback) {
var scroller = $('body');
var padTop = 10;
var scrollTo = this.$el.offset().top - padTop;
var distance = Math.abs(scrollTo - scroller.scrollTop());
scroller.animate({
scrollTop: scrollTo
}, distance, function(){if(callback)callback();});
},
deleteNote: function(event) {
event.stopPropagation();
this.model.setDeleted(true);
this.model.save();
this.remove();
},
editNote: function(event) {
event.stopPropagation();
// invoke edit note view after fetch
if ( this.model.get('_id') ) {
this.model.fetch();
}
console.log('this.stacksCollection: ' + this.stacksCollection);
var editView = new NoteEditView({
'normalView':this,
'isNew':false,
'model':this.model,
'stacksCollection':this.stacksCollection
});
$('body').append(editView.render().$el);
},
render: function() {
var isArchived = this.model.getDeleted();
if ( isArchived && !this.showArchivedNotes ) {
this.remove();
} else if (!isArchived && !this.showUnarchivedNotes) {
this.remove();
} else {
var bodyHTML = jQuery.parseHTML(this.model.getBodyHTML());
var context = {
'name': this.model.getName()
};
this.$el.html(this.template(context));
$('.note-body', this.$el).first().append(bodyHTML);
}
return this;
}
});
|
const http = require("http");
const path = require("path");
const router = require(path.join(__dirname, "router"));
const port = process.env.PORT || 3000;
//create the server here
const server = http.createServer((request, response) => {
//calls router function
router(request, response);
});
//server takes request
server.listen(port, () => console.log(`Listening on http://localhost:${port}`));
|
module.exports.tokenValidation = (req, res, next) => {
let token = JSON.parse(localStorage.getItem('default_auth_token'));
if (!token) {
return req.sendStatus(401);
} else {
next();
}
}
|
import React from "react";
import {HashRouter, Route, Switch} from 'react-router-dom';
import Home from "./mould/home.js";
import About from "./mould/about.js";
import News from "./mould/news.js";
export default class router extends React.Component {
render() {
return (
<HashRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/home" component={Home} />
<Route exact path="/about" component={About} />
<Route exact path="/news" component={News} />
</Switch>
</HashRouter>
);
}
}
|
//grab packages that we need for post model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SheetSchema = new Schema({
username: {
type: String,
required: true
},
timeStamp: {
type: Date,
required: true
},
filepath: String,
type: String
});
//return the model
module.exports = mongoose.model('Sheet', SheetSchema);
|
/* globals binarysearch*/
(function(){
'use strict';
describe('BinarySearch', function(){
it('Should return the position of the number it is looking for, it works only for sorted lists', function(){
var list = [1, 2, 3, 4, 5, 9, 20, 1000];
for(var i = 0; i < list.length; i++){
expect(binarysearch(list, list[i])).toBe(i);
}
});
it('Should return the middle point when using middle function', function(){
expect(binarysearch.middle(1, 4)).toBe(2);
expect(binarysearch.middle(1, 3)).toBe(2);
expect(binarysearch.middle(2, 5)).toBe(3);
});
});
}());
|
import { Link } from 'react-router-dom';
import useFetch from './useFetch';
const Products = () => {
const {data: products, isPending, error} = useFetch('https://inventory-be-app.herokuapp.com/api/v1/products');
return (
<div className="list-main">
<h1>All Products</h1>
{error && <div> {error} </div>}
{isPending && <div>Loading...</div>}
{ products &&
products.map(product => (
<div className="list-preview" key={product._id}>
<Link to={`/products/${product._id}`}>
<h2>{product.name}</h2>
<p>Status: {product.status}</p>
</Link>
</div>
))
}
<Link to="/create-product"><button>Add</button></Link>
</div>
);
}
export default Products;
|
import Enzyme from 'enzyme'
import Adapter from 'enzyme-react-adapter-future'
Enzyme.configure({ adapter: new Adapter() })
|
define(['ngApp'], function (ngApp) {
return ngApp.directive('petForm', function () {
return {
restrict: 'C',
controller: ['$scope', '$element', '$http', '$mdToast', 'dataParserService',
function ($scope, $element, $http, $mdToast, dataParserService) {
}]
};
});
});
|
$(document).ready(function(){
//------ SEQUENCE D'ACCUEIL SUR HOMEPAGE ---------//
TweenMax.to(".title", 3, {opacity:1, top:"0"});
TweenMax.to("#imgDev", 3, {opacity:1, delay:4});
TweenMax.to('#imgMusic', 3, {opacity:1, delay:3});
//------ GESTION DES LIENS HOME PAGE ---------//
$( "#imgDev" )
.mouseover(function() {
TweenMax.to(".devText", 0.75, {opacity:1, scale:1, rotation:360});
});
$( "#imgDev" )
.mouseout(function() {
TweenMax.to(".devText", 1, {opacity:0, scale:0, rotation:0});
});
$( "#imgMusic" )
.mouseover(function() {
TweenMax.to(".musicText", 0.75, {opacity:1, scale:1, rotation:360});
});
$( "#imgMusic" )
.mouseout(function() {
TweenMax.to(".musicText", 1, {opacity:0, scale:0, rotation:0});
});
});
|
import React, { lazy } from 'react'
const Login = lazy(() => import('../Base/Login'))
const LoginPage = () => {
return (
<>
<div className="Container-main">
<Login/>
</div>
</>
)
}
export default LoginPage
|
const fetch = require("node-fetch");
module.exports = class VOID {
constructor(token, client) {
this['token'] = token;
this['client'] = client;
return this;
}
serverCount(message) {
fetch(`https://disbotlist.top/api/bots/stats`, {
method: 'POST',
headers: {
'serverCount': this.client.guilds.cache.size,
'Content-Type': 'application/json',
'Authorization': this.token
},
})
.then(console.log(message || "Server count posted."));
}
async search(id) {
return await fetch(`https://disbotlist.top/api/bots/${id}`, {
method: 'GET'
})
.then(res => res.json()).then(json => json);
}
async hasVoted(id) {
return await fetch(`https://disbotlist.top/api/bots/check/${id}`, {method: 'GET',headers: {
'Content-Type': 'application/json', 'Authorization': this.token
}
}).then(res => res.json()).then(async json => json.voted);
}
}
|
const express = require('express');
const router = express.Router();
module.exports = (db) => {
router.get("/", (req, res) => {
let query = `SELECT *, orders.id AS order_id, CURRENT_TIMESTAMP - date AS time_in_queue, status FROM orders JOIN users ON users.id = user_id WHERE orders.status = 'paid';`
console.log(query);
db.query(query)
.then(data => {
const orders = data.rows;
res.json({ orders });
})
.catch(err => {
res
.status(500)
.json({ error: err.message });
});
});
router.post("/", (req, res) => {
let query = `UPDATE orders SET status = 'closed' WHERE user_id = $1 AND status = 'pending';`;
let query2 = `INSERT INTO orders (user_id) VALUES ($1) RETURNING *;`;
let options = [req.session.user_id];
console.log(req)
if(!req.session.user_id){
return 1;
} else if (req.session.user_id === 1){
console.log("you are the owner")
return res.send("Owners can't order.");
} else {
db.query(query, options)
.then(db.query(query2, options))
.then((data) => {
const addToOrder = data.rows;
res.json({ addToOrder });
})
.catch(err => {
console.log(err.message)
res
.status(500)
.json({ error: err.message });
});
}
});
router.delete("/", (req, res) => {
//let query = `DELETE FROM orders WHERE orders.id = $1;`;
let query = `DELETE FROM orders WHERE orders.id = $1`;
//db.query(query, [req.body.ordersId])
db.query(query, [req.body.ordersId])
.then(data => {
const orders = data.rows;
res.json({ orders });
})
.catch(err => {
res
.status(500)
.json({ error: err.message });
});
});
router.put("/", (req, res) => {
let query = '';
console.log('body:', req.body);
if (req.body.paid === 'false') {
query = `UPDATE orders SET status = 'pending' WHERE user_id = $1 AND status = 'open' RETURNING *;`;
}
if (req.body.paid === 'true') {
query = `UPDATE orders SET status = 'paid' WHERE user_id = $1 AND status = 'pending' RETURNING *;`;
}
if (req.session.user_id && req.session.user_id !== 1){
db.query(query, [req.session.user_id])
.then(data => {
const order = data.rows;
res.json({ order });
})
.catch(err => {
res
.status(500)
.json({ error: err.message });
});
} else {
return res.status(500);
}
}
)
return router;
}
|
const expect = require('chai').expect;
const generateCustomerSalesMap = require('../acme');
describe('generateCustomerSalesMap', ()=>{
it('exists', () => {
expect(generateCustomerSalesMap).to.be.ok;
});
it('converts two arrays to one object', ()=> {
expect(generateCustomerSalesMap([],[])).to.eql({});
});
it('takes two arrays with one data point in common and creates a new object tying both data sets',()=>{
expect(generateCustomerSalesMap([
{customerId: 1, orderId: 1, total: 3},
{customerId: 1, orderId: 1, total: 3},
{customerId: 2, orderId: 1, total: 100},
{customerId: 2, orderId: 1, total: 3}
],[
{id: 1, name: 'moe'},
{id: 2, name: 'larry'}
]
)).to.eql({moe: 6, larry: 103})
})
});
|
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import axios from 'axios'
import Header from './Header'
import Player from './Player'
import RelatedVideos from './RelatedVideos'
const apiKey = 'AIzaSyBB9LBxNmwDosU6hf6-AsPJgoGc4TaTpUw'
const uploadPlaylistId = 'UUIi1h9LoV9fefFTucM8bRtw'
class Home extends Component {
state = {
videosLoaded: false,
latestVideo: {},
latestVideoId: '',
videos: {}
}
componentDidMount() {
axios
.get(
`https://www.googleapis.com/youtube/v3/playlistItems?&order=date&part=snippet&maxResults=5&playlistId=${uploadPlaylistId}&key=${apiKey}`
)
.then(response => {
console.log(response)
this.setState({
latestVideo: response.data.items[0],
latestVideoId: response.data.items[0].snippet.resourceId.videoId,
videos: response.data.items.slice(1, 5),
videosLoaded: true
})
})
}
render() {
let RecentVideos
if (this.state.videosLoaded) {
RecentVideos = <RelatedVideos recent videos={this.state.videos} />
} else {
RecentVideos = ''
}
return (
<div>
<Header />
<main id="content" role="main">
<div className="main-content">
<Player video={this.state.latestVideo} videoId={this.state.latestVideoId} />
{RecentVideos}
<div className="actions">
<Link href="/videos" to="/videos" className="button">
More Videos
</Link>
</div>
</div>
</main>
</div>
)
}
}
export default Home
|
'use strict';
/**
* @ngdoc function
* @name dssiFrontApp.controller:ChecklistItemGroupCreateCtrl
* @description
* # ChecklistItemGroupCreateCtrl
* Controller of the dssiFrontApp
*/
angular.module('dssiFrontApp')
.controller('ChecklistItemGroupCreateCtrl', function ($scope, ChecklistItemGroup, $uibModal, notificationService) {
var vm = this;
// Set scope to modal
$scope = $scope.$parent || $scope;
vm.checklistItemGroup = new ChecklistItemGroup({
name: null,
checklist_id: $scope.$parent.checklist.id || null
});
// Replace method from parent ModalDefaultCtrl
var parentClose = $scope.close;
$scope.ok = ok;
$scope.formSubmit = formSubmit;
////////////
function saveChecklistItemGroup(checklistItemGroup){
checklistItemGroup.$save().then(function(){
notificationService.success('¡Guardado!');
parentClose();
}, function(){
notificationService.error('No ha sido posible atender la solicitud.');
});
}
function ok(){
saveChecklistItemGroup(vm.checklistItemGroup);
}
function formSubmit(){
saveChecklistItemGroup(vm.checklistItemGroup);
}
});
|
var searchData=
[
['myvect',['MyVect',['../class_my_vect.html',1,'']]]
];
|
"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var models_1 = require("../models");
var user_1 = require("./user");
var key = models_1.MODEL_TYPES.Pictures;
exports.pictureFields = {
Picture: {
author: function (picture, _args, ctx) {
return user_1.userQueries.user({}, { id: picture.user_id }, ctx);
}
}
};
exports.pictureQueries = {
/** Gets a single Picture by its id */
picture: function (_root, pic, _a) {
var db = _a.db;
return db
.get(key)
.find(pic)
.value();
}
};
exports.pictureMutations = {
/** Creates a new Picture */
addPicture: function (_root, _a, ctx) {
var input = _a.input;
var db = ctx.db, generateId = ctx.generateId, getMutationResult = ctx.getMutationResult;
var source = input.source, author_id = input.author_id;
if (!user_1.userQueries.user({}, { id: author_id }, ctx)) {
return getMutationResult(false, 'User not found!', {});
}
var newPicture = {
source: source,
id: generateId(key),
user_id: author_id
};
db.get(key)
.push(newPicture)
.write();
return getMutationResult(true, 'Picture succesfully created!', newPicture);
},
/** Updates a Picture */
updatePicture: function (_root, _a, ctx) {
var input = _a.input;
var db = ctx.db, getMutationResult = ctx.getMutationResult;
var id = input.id, data = __rest(input, ["id"]);
var picture = db.get(key).find({ id: id });
if (!picture.value()) {
return getMutationResult(false, 'Picture not found!', {});
}
var updatedPicture = picture.assign(data);
updatedPicture.write();
return getMutationResult(true, 'Picture succesfully updated!', updatedPicture.value());
},
/** Deletes a Picture */
deletePicture: function (_root, _a, ctx) {
var input = _a.input;
var db = ctx.db, getMutationResult = ctx.getMutationResult;
var id = input.id;
var pictures = db.get(key);
if (!pictures.find({ id: id }).value()) {
return getMutationResult(false, 'Picture not found!', {});
}
pictures.remove({ id: id }).write();
return getMutationResult(true, 'Picture succesfully deleted!', {});
}
};
|
var express = require('express');
var router = express.Router();
var fs = require('fs');
var http = require('http');
var https = require('https');
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile('weather.html',{root: 'public'} );
});
router.get('/getcity', function(req, res, next) {
var myRe = new RegExp("^" + req.query.q);
console.log(myRe);
fs.readFile(__dirname + '/cities.dat.txt',function(err,data) {
if(err) throw err;
var cities = data.toString().split("\n");
var jsonresult = [];
for(var i = 0; i < cities.length; i++) {
var result = cities[i].search(myRe);
if(result != -1) {
jsonresult.push({city:cities[i]});
}
}
console.log(jsonresult);
res.status(200).json(jsonresult);
})
console.log("In getCity route");
console.log(req.query);
});
router.get('/googleBooks', function(req, res) {
console.log("IN GOOGLE BOOKS");
var query = req.query.q.toString();
var path = "https://www.googleapis.com/books/v1/volumes?q="+query;
console.log(path);
https.get(path, function(response) {
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
var result = JSON.parse(body);
//console.log(result);
res.status(200).json(result);
});
});
});
// I was working on another API here but I didn't include it on the html page
router.get('/babelfy', function(req, res) {
var key = "b8c8ca24f7aa43658d31d238fd02e163i";
var lang = "EN";
var text = req.query.q.toString();
console.log(text);
var path = "https://babelfy.io/v1/disambiguate?text="+text+"&lang="+lang+"&key="+key;
var optionPath = "/v1/disambiguate?text="+text+"&lang="+lang+"&key="+key;
optionPath.replace(/[\\$'"]/g, "\\$&");
var test = "https://babelfy.io/v1/disambiguate?text=BabelNet is both a multilingual encyclopedic dictionary and a semantic network&lang=EN&key="+key;
var options = {
host: 'babelfly.io',
path: optionPath,
headers: {
'Accept-Encoding': 'gzip'
},
method: 'GET'
};
https.get(test, function(response) {
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
var result = JSON.parse(body);
res.status(200).json(result);
});
});
});
module.exports = router;
|
const express = require('express');
const router = express.Router();
const {nuevo, mostrar, detallesVehiculo, mostrarRecientes, eliminar, mostrarCarrosById, mostrarImg} = require('../controladores/controlador.carros');
router.post('/nuevo', nuevo);
router.get('/mostrar-recientes', mostrarRecientes);
router.get('/mostrar-todo', mostrar);
router.get('/img/:id', mostrarImg);
router.get('/detalles/:id', detallesVehiculo);
router.delete('/:id',eliminar);
router.param('id',mostrarCarrosById);
module.exports = router;
|
import Preloader from "../../Common/Preloader/Preloader"
import ProfileStatusWithHooks from "./ProfileStatusWithHooks"
const ProfileInfo = ({profile, status, updateStatus}) => {
if (!profile) {
return <Preloader />
}
return (
<div>
<img src={profile.photos.large} alt="текст"></img><br></br>
<span>{profile.aboutMe}</span><br></br>
<span>{profile.fullName}</span>
<ProfileStatusWithHooks status={status} updateStatus={updateStatus}/>
</div>
)
}
export default ProfileInfo
|
// NAVBAR ON CLICK
const burger = document.getElementsByClassName("burger");
const navSlider = () => {
const nav = document.querySelector(".desktop");
// TOGGLE NAVBAR
burger.addEventListener("click", () => {
nav.classList.toggle("active");
// BURGER ICON ANIMATE
burger.classList.toggle("animate");
});
};
navSlider();
// CONTACT FORM
const inputs = document.querySelectorAll("input");
const patterns = {
name: /^\w+\s\w+$/,
mail: /^([a-z\d\.-]+)@([a-z\d-]+)\.([a-z]{2,8})(\.[a-z]{2,8})?$/,
phone: /^\d{3}.?\d{3}.?\d{3}$/,
subject: /[\w\s]*/,
};
validate = (field, regex) => {
if (regex.test(field.value)) {
field.className = "valid";
} else {
field.className = "invalid";
}
};
inputs.forEach((input) => {
input.addEventListener("keyup", (e) => {
validate(e.target, patterns[e.target.attributes.name.value]);
});
});
|
module.exports = require('./user.processor.js');
|
#!/usr/bin/env node
'use strict';
const LarryBnd = require('../index');
const BnDCookbook = LarryBnd.cookbook.BnDCookbook;
const cookbook = new BnDCookbook(process.cwd());
(async function (){
await cookbook.initializeProject();
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.