text stringlengths 7 3.69M |
|---|
//队列方法 push() shift() unshift()
//shift()方法,取得第一项并返回值,长度减1
var colors=["red","white","blue"];
console.log(colors.shift()); //red
console.log(colors); //[ 'white', 'blue' ]
//unshift()从前面添加任意项并返回新数组长度
console.log(colors.unshift("red","black")); //4
console.log(colors); //[ 'red', 'black', 'white', 'blue' ] |
import express from "express";
const router = express.Router();
import pool from "../db";
import {
authenticationRequired,
adminAuthenticationRequired
} from "../AuthenticationMiddleware/AuthenticationMiddleware";
// @router PUT api/user/
// @desc Store user information to MySql database
// @ret {cart_id: #}
// @access Private TODO
router.put("/", authenticationRequired, (req, res) => {
const { userId, firstName, lastName } = req.body;
const sql = `INSERT INTO customer(user_id, first_name, last_name) VALUES('${userId}', '${firstName}', '${lastName}')
ON DUPLICATE KEY UPDATE user_id = user_id`;
pool.query(sql, (error, results) => {
if (error) res.send({ error: "Unable to login" });
const sql = `SELECT cart_id FROM cart WHERE user_id = "${userId}"`;
pool.query(sql, (err, results) => {
if (err) res.send({ error: "Unable to retrieve cart id" });
res.json({ cartId: results[0].cart_id });
});
});
});
export default router;
|
import React from 'react';
import PropTypes from 'prop-types';
import classes from './index.module.css';
import {Link} from 'react-router-dom';
export const InvitationSideBar = (props) => (
<div className={classes.invitationCard}>
<div className={classes.title}>
邀请管理
</div>
<div className={classes.content}>
{props.content}
</div>
<Link to="/">
<div className={classes.manageAll}>
管理全部邀请
</div>
</Link>
</div>
);
InvitationSideBar.propTypes = {
content: PropTypes.string.isRequired
};
|
import style from '../style'
export default {
animationDuration: 0,
animationDurationUpdate: 3000,
animationEasingUpdate: 'cubicInOut',
title: {
//text: '运维工单上月与本月对比分析',
textStyle: {
color: style.title.textStyle.color,
fontSize: style.title.textStyle.fontSize
}
},
tooltip: {},
legend: {
orient: 'horizontal',
left: style.legendPos.left,
top: style.legendPos.top,
textStyle: {
color: style.legend.textStyle.color,
fontSize: style.legend.textStyle.fontSize
},
show: true,
data: [{ name: '上月', icon: 'circle' }, { name: '本月', icon: 'circle' }]
},
grid: {
top: style.gridPos.legendTop,
left: style.gridPos.left,
right: style.gridPos.right,
bottom: style.gridPos.bottom,
containLabel: true,
show: false,
borderWidth: 1,
borderColor: style.gridBorderColor
},
xAxis: {
nameTextStyle: {
color: style.fontColor,
opacity: style.opacity,
fontSize: style.fontSize
},
axisLine: { //轴,下面有条是grid线,
show: true,
onZero: false,
lineStyle: {
color: style.axisLineColor,
width: style.axisLine.lineStyle.width,
opacity: style.notSupportOpacity
}
},
axisTick: { //刻度
show: false
},
axisLabel: {
show: true,
margin: 8,
rotate: 0,
textStyle: {
color: style.labelColor,
opacity: style.notSupportOpacity,
fontSize: style.fontSize
}
},
splitLine: {
show: true,
lineStyle: {
color: '#236592',
opacity: style.opacity
}
},
data: ['事件', '问题', '变更', '巡检', '二线流程']
},
yAxis: [{
nameLocation: 'middle',
min: undefined,
max: undefined,
nameTextStyle: {
color: style.fontColor,
opacity: style.opacity,
fontSize: style.fontSize
},
axisLine: {
show: true,
onZero: false,
lineStyle: {
opacity: style.notSupportOpacity,
color: style.axisLineColor,
width: style.axisLine.lineStyle.width
}
},
axisTick: {
show: false
},
axisLabel: {
show: true,
margin: 8,
textStyle: {
color: style.labelColor,
fontSize: style.fontSize,
opacity: style.notSupportOpacity
}
},
splitLine: {
show: true,
lineStyle: {
color: '#236592',
opacity: style.opacity
}
}
},{
nameLocation: 'middle',
nameTextStyle: {
color: style.fontColor,
opacity: style.opacity,
fontSize: style.fontSize
},
axisLine: {
show: true,
onZero: false,
lineStyle: {
opacity: style.notSupportOpacity,
color: style.axisLineColor,
width: style.axisLine.lineStyle.width
}
},
axisTick: {
show: false
},
axisLabel: {
show: false,
margin: 8,
textStyle: {
color: style.labelColor,
fontSize: style.fontSize,
opacity: style.notSupportOpacity
}
},
splitLine: {
show: false,
lineStyle: {
color: '#236592',
opacity: style.opacity
}
}
}],
series: [{
barWidth: 10,
//barGap: '20%',
name: '上月',
type: 'bar',
data: [40, 20, 10, 10, 20]
}, {
barWidth: 10,
//barGap: '20%',
name: '本月',
type: 'bar',
data: [42, 30, 15, 10, 15]
}]
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const THREE = require("three");
function init(obj, objParameters, material, materialParameters, scene) {
const o = new THREE[obj](objParameters);
return o;
}
exports.default = init;
|
import React, { useState } from "react";
import Button from "./components/Button";
import Statistic from "./components/Statistic";
const Statistics = ({ good, bad, neutral }) => {
const sum = good + bad + neutral;
const average = (bad * -1 + good) / 100;
const percentVotes = ((good / sum) * 100).toFixed(4);
if (!good && !bad && !neutral) {
return <div>Please enter some stats</div>;
}
return (
<div>
<table>
<tbody>
<Statistic text="Good" value={good} />
<Statistic text="Neutral" value={neutral} />
<Statistic text="Bad" value={bad} />
<Statistic text="Sum" value={sum} />
<Statistic text="Average Score" value={average} />
<Statistic text="Percent Vote" value={percentVotes + "%"} />
</tbody>
</table>
</div>
);
};
const App = () => {
// save clicks of each button to its own state
const [good, setGood] = useState(0);
const [neutral, setNeutral] = useState(0);
const [bad, setBad] = useState(0);
return (
<div>
<h2>Give Feedback Here</h2>
<Button handleClick={() => setGood(good + 1)} text="Good" />
<Button handleClick={() => setNeutral(neutral + 1)} text="Neutral" />
<Button handleClick={() => setBad(bad + 1)} text="Bad" />
<h2>Statistics</h2>
{/* <p>Good: {good}</p>
<p>Neutral: {neutral}</p>
<p>Bad: {bad}</p> */}
<Statistics good={good} bad={bad} neutral={neutral} />
</div>
);
};
export default App;
|
myApp.controller('RegistrationController',
function($scope, $firebaseAuth, $location, FIREBASE_URL, Authentication) {
var data = new Firebase(FIREBASE_URL);
var auth = $firebaseAuth(data);
$scope.login = function() {
Authentication.login($scope.user)
.then(function(user) {
$location.path('/meetings');
}).catch(function(error) {
$scope.message = error.message;
});
};
$scope.register = function() {
Authentication.register($scope.user)
.then(function(user) {
Authentication.login($scope.user);
$location.path('/meetings');
}).catch(function(error) {
$scope.message = error.message;
});
};
});
|
import React from 'react';
import './footer.styles.css';
import { useTheme, useMediaQuery } from '@material-ui/core';
export default function Footer() {
const theme = useTheme();
const matchesMD = useMediaQuery(theme.breakpoints.down('md'));
const matchesXS = useMediaQuery(theme.breakpoints.down('xs'));
return (
<div>
<div
className="footer"
style={{
marginTop: matchesMD ? '3rem' : matchesXS ? '2rem' : '4rem',
background: '#e0e0e0',
padding: matchesMD ? '0.5em' : '1em',
}}
>
<h4 className="sehertext">
All right reserved by{' '}
<a
href="https://seher-development.vercel.app/"
style={{
textDecoration: 'none',
textTransform: 'none',
}}
target="_blank"
rel="noopener noreferrer"
>
Seher
</a>
</h4>
</div>
</div>
);
}
|
const http = require('http');
//服务器 request请求 输入 浏览器发送过来的页面 response响应 输出,你要发给浏览器的东西
let server = http.createServer(function(request,response){
console.log('有人');
console.log(request.url);
// response.write('aaaaa');
// response.end();
if(request.url == '/1.html'){
response.write('<html><head></head><body><div style="width:200px;height:200px;background:red"></div></body></html>');
response.end();
}else if(request.url == '/1.txt'){
response.write('<html><head></head><body><div style="width:200px;height:200px;background:blue"></div></body></html>');
response.end();
}else{
response.write('404');
response.end();
}
});
//监听,开始等待客户端的连接 端口号 ctrl+c 命令行终止
server.listen(8080);
|
const express = require('express');
const router = express.Router();
//Import controllers
let TaskController = require('../controllers/TaskController');
let StateController = require('../controllers/StateController');
//Request defined
//Task
router.get('/task', TaskController.showTasks);
router.post('/task/:state_id', TaskController.createTask);
router.put('/task/:task_id', TaskController.editTask);
router.put('/task/delete/:task_id', TaskController.deleteTask);
//Task
router.get('/state', StateController.showStates);
router.post('/state', StateController.createState);
router.put('/state/:state_id', StateController.editState);
module.exports = router; |
//Toggle Menu Section
const hambutton = document.querySelector('.ham');
const mainnav = document.querySelector('.navigation')
hambutton.addEventListener('click', () => {mainnav.classList.toggle('responsive')}, false);
// To solve the mid resizing issue with responsive class on
window.onresize = () => {if (window.innerWidth > 760) mainnav.classList.remove('responsive')};
//Date Section
const datefield = document.querySelector("date");
// derive the current date using a date object
const now = new Date();
const fulldate = new Intl.DateTimeFormat("en-UK", { dateStyle: "full" }).format(
now);
document.getElementById("date").innerHTML=fulldate
datefield.innerHTML = `<em>${fulldate}</em>`; |
var initstate={
detailList:[]
}
function reducer(state=initstate,action){
switch(action.type){
case 'NEWSDETAIL':
return {...state,detailList:action.payload};
default:
return state
}
}
export default reducer; |
import React from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as DevicesActions from 'actions/devices'
import ConnectSocket from 'utils/connectSocket'
import styled from 'styled-components'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts'
import moment from 'moment'
class DevicesContainer extends React.Component {
static propTypes = {
device: PropTypes.shape({
devices: PropTypes.arrayOf(PropTypes.object),
selected: PropTypes.shape({
browseName: PropTypes.string,
hasComponent: PropTypes.array,
}),
}).isRequired,
fetchDevices: PropTypes.func.isRequired,
selectDevice: PropTypes.func.isRequired,
selectTag: PropTypes.func.isRequired,
}
constructor(props) {
super(props)
this.state = {
chart: [{ name: moment().format('DD.MM.YY HH:mm:ss'), value: 0 }],
}
this.io = new ConnectSocket()
this.io.socket.on('tagChange', data => {
this.changedTag(data)
})
// this.socket.on('tagChange', (tag) => {
// console.log(tag);
// })
}
componentDidMount() {
this.props.fetchDevices()
}
changedTag(data) {
const currentChart = [...this.state.chart]
currentChart.push({
name: moment().format('DD.MM.YY HH:mm:ss'),
value: data.value,
})
console.log('>>>', currentChart)
if (currentChart.length > 20) {
currentChart.shift()
}
this.setState({
...this.state,
chart: currentChart,
})
}
render() {
return (
<Container>
<Aside>
<AsideTitle>Devices List</AsideTitle>
{this.props.device.devices.filter(d => d.componentsCount > 0).map(device => (
<AsideItem onClick={() => this.props.selectDevice(device)} key={device._id}>
{device.browseName}
</AsideItem>
))}
</Aside>
<Content>
{!!this.props.device.selected.browseName && (
<Tags>
<SelectedTitle>{this.props.device.selected.browseName}</SelectedTitle>
{!!(this.props.device.selected.hasComponent && this.props.device.selected.hasComponent.length) && (
<TagsList>
{this.props.device.selected.hasComponent.map(component => (
<AsideItem key={component.nodeId} onClick={() => this.props.selectTag(component)}>
{component.browseName}
</AsideItem>
))}
</TagsList>
)}
</Tags>
)}
<View>
<LineChart width={800} height={400} data={this.state.chart} margin={{ top: 5, bottom: 5 }}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="value" stroke="#8884d8" />
</LineChart>
</View>
</Content>
</Container>
)
}
}
const mapStateToProps = state => ({
device: state.device,
})
function mapDispatchToProps(dispatch) {
return bindActionCreators(DevicesActions, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(DevicesContainer)
const Container = styled.div`
min-height: 100vh;
display: flex;
flex-flow: row nowrap;
justify-content: space-between;
text-align: left;
`
const Aside = styled.div`
min-width: 300px;
width: 300px;
border-right: 1px #524d4d solid;
`
const AsideItem = styled.div`
position: relative;
border-bottom: 1px #524d4d solid;
text-transform: capitalize;
cursor: pointer;
padding: 15px 10px;
z-index: 2;
&::before {
position: absolute;
content: '';
background: linear-gradient(to right, transparent, #4c4a4a);
height: 100%;
width: 100%;
left: 0;
top: 0;
opacity: 0;
transition: all 0.2s ease;
z-index: 1;
}
&:hover {
&::before {
opacity: 1;
}
}
`
const AsideTitle = styled.h3`
border-bottom: 1px #ccc solid;
padding-bottom: 10px;
margin-bottom: 10px;
`
const Content = styled.div`
width: 100%;
display: flex;
flex-flow: row nowrap;
justify-content: flex-start;
`
const Tags = styled.div`
min-width: 300px;
width: 300px;
height: 100%;
padding-left: 30px;
border-right: 1px #524d4d solid;
`
const SelectedTitle = styled.h3`
border-bottom: 1px #ccc solid;
padding-bottom: 10px;
margin-bottom: 10px;
`
const TagsList = styled.div``
const View = styled.div``
|
/*
function regedit(){
var path = "../templates/default/regedit.html";
path = encodeURI(encodeURI(path));//中文转码
window.showModalDialog(path,"sfdsdf","dialogWidth=570px;dialogHeight=330px;scroll=no;status=no;help=no;");
}
*/
//用户合法性验证
function InputCheck(Regform){
if(Regform.username.value == ""){
alert ( "用户名不能为空!");
Regform.username.focus();
return false;
}
if(Regform.password.value.length<6){
alert("密码不能小于6位");
Regform.password.focus();
return false;
}
if(Regform.password.value == ""){
alert ("密码不能为空!");
Regform.password.focus();
return false;
}
if(Regform.repass.value != Regform.password.value){
alert("密码不一致!");
Regform.repass.focus();
return false;
}
if(Regform.email.value == ""){
alert("邮箱不能为空!");
Regform.email.focus();
return false;
}
if (Regform.img.value == "")
{
alert("请输入验证码!");
Regform.img.focus();
return false;
}
}
//刷新验证码
function showVerify(){
document.getElementById("verify").src ="index.php/User/checkpic?r="
+ (Math.random() * 1000);
}
function alertWin(title, w, h){
var titleheight = "22px"; // 提示窗口标题高度
var bordercolor = "#666699"; // 提示窗口的边框颜色
var titlecolor = "#000000"; // 提示窗口的标题颜色
var titlebgcolor = "#D2E9FF"; // 提示窗口的标题背景色
var bgcolor = "#FFFFFF"; // 提示内容的背景色
var iWidth = document.documentElement.clientWidth;
var iHeight = document.documentElement.clientHeight;
var bgObj = document.createElement("div");
bgObj.style.cssText = "position:absolute;left:0px;top:0px;width:"+iWidth+"px;height:"+Math.max(document.body.clientHeight, iHeight)+"px;filter:Alpha(Opacity=30);opacity:0.3;background-color:#000000;z-index:101;";
document.body.appendChild(bgObj);
var msgObj=document.createElement("div");
msgObj.style.cssText = "position:absolute;font:11px '宋体';top:"+(iHeight-h)/2+"px;left:"+(iWidth-w)/2+"px;width:"+w+"px;height:"+h+"px;border:5px solid #E0E0E0;background-color:"+bgcolor+";padding:1px;line-height:22px;z-index:102;";
document.body.appendChild(msgObj);
var table = document.createElement("table"); //www.divcss5.com divcss5
msgObj.appendChild(table);
table.style.cssText = "margin:0px;border:0px;padding:0px;";
table.cellSpacing = 0;
var tr = table.insertRow(-1);
var titleBar = tr.insertCell(-1);
titleBar.style.cssText = "width:"+iWidth+"px;height:"+titleheight+"px;text-align:left;padding:3px;margin:0px;font:bold 13px '宋体';color:"+titlecolor+";border:0px solid " + bordercolor + ";cursor:move;background-color:" + titlebgcolor;
titleBar.style.paddingLeft = "10px";
titleBar.innerHTML = title;
var moveX = 0;
var moveY = 0;
var moveTop = 0;
var moveLeft = 0;
var moveable = false;
var docMouseMoveEvent = document.onmousemove; //www.divcss5.com divcss5
var docMouseUpEvent = document.onmouseup;
titleBar.onmousedown = function() {
var evt = getEvent();
moveable = true;
moveX = evt.clientX;
moveY = evt.clientY;
moveTop = parseInt(msgObj.style.top);
moveLeft = parseInt(msgObj.style.left);
document.onmousemove = function() {
if (moveable) {
var evt = getEvent();
var x = moveLeft + evt.clientX - moveX; //www.divcss5.com divcss5
var y = moveTop + evt.clientY - moveY;
if ( x > 0 &&( x + w < iWidth) && y > 0 && (y + h < iHeight) ) {
msgObj.style.left = x + "px";
msgObj.style.top = y + "px";
}
}
};
document.onmouseup = function () {
if (moveable) {
document.onmousemove = docMouseMoveEvent; //www.divcss5.com divcss5
document.onmouseup = docMouseUpEvent;
moveable = false;
moveX = 0;
moveY = 0;
moveTop = 0;
moveLeft = 0;
}
};
}
var closeBtn = tr.insertCell(-1);
closeBtn.style.cssText = "cursor:pointer; padding:2px;background-color:" + titlebgcolor;
closeBtn.innerHTML = "<span style='font-size:15pt; color:"+titlecolor+";'>×</span>";
closeBtn.onclick = function(){
document.body.removeChild(bgObj);
document.body.removeChild(msgObj);
}
var msgBox = table.insertRow(-1).insertCell(-1);
msgBox.style.cssText = "font:10pt '宋体';";
msgBox.colSpan = 2;
var loginname = '<form name="Regform" action="index.php/user/register" method="post" onsubmit="return InputCheck(this)" >' +
" <div style='position:absolute;margin-top:8px;margin-left:30px;font-size:12px;'>" +
"<font color=red>*</font>账号:</div><div style='margin-top:5px;margin-left:120px;font-size:12px;'>" +
"<input type = 'text' name='username' style='width:120px;height:15px;font-size:12px;'/>" +
"<span style='color:#AAAAAA'>(必填,3-15字符长度,支持汉字、字母、数字及_)</span><div/>"
var passwords = "<div style = 'margin-top:20px;margin-left:-90px;font-size:12px;'>" +
"<font color=red>*</font>密码:</div><div style='margin-top:-18px;font-size:12px;'>" +
"<input type='password' name='password' style='width:120px;height:15px;font-size:12px;' />" +
"<span style='color:#AAAAAA'>(必填,不得少于6位)</span></div>";
var secondPasswords = "<div style = 'margin-top:20px;margin-left:-90px;font-size:12px;'>" +
"<font color=red>*</font>再次输入密码:</div><div style='margin-top:-18px;font-size:12px;'>" +
"<input type='password' name='repass' style='width:120px;height:15px;font-size:12px;' />" +
"<span style='color:#AAAAAA'>(必填)</span></div>";
var emil = "<div style = 'margin-top:20px;margin-left:-90px;font-size:12px;'>" +
"<font color=red>*</font>电子邮箱:</div><div style='margin-top:-18px;font-size:12px;'>" +
"<input type='text' name='email' style='width:120px;height:15px;font-size:12px;' />" +
"<span style='color:#AAAAAA'>(必填)</span></div>";
//验证码
var character = "<div style = 'margin-top:20px;margin-left:-90px;font-size:12px;'>" +
"<font color=red>*</font>输入右图字符:</div>" +
"<div style='margin-top:-18px;font-size:12px;'>" +
"<input type='text' name='img' style='width:50px;height:15px;font-size:12px;' /></div>" +
"<div style='margin-top:-25px;margin-left:80px;'>" +
"<img id='verify' src='index.php/User/checkpic' style='width:65px;height:30px;'/> 看不清?" +
"<a href='#' onclick='showVerify()' style='text-decoration:none'>换一张</a>" +
"</div>";
var xiyi = "<div style='margin-top:20px;margin-left:-40px;'>" +
"<input class='checkboxs' type='Checkbox' check='true'/> 我已看过并同意" +
"<a href='##' style='text-decoration:none '>《网络服务使用协议》</a>" +
"<a href='##' style='text-decoration:none '>《隐私政策声明》</a></div>";
var submits = "<div style= 'margin-top:10px;margin-left:3px'>" +
"<input type='image' name='submit' src='application/public/image/but_reg.gif' style='width:140px;height:35px;' />" +
"<div></form>";
var welcome = "<div style= 'margin-top:-36px;margin-left:170px'>" +
"<input type='image' name='back' src='application/public/image/but_return.gif' style='width:140px;height:35px;' /><div>";
msgBox.innerHTML =loginname+passwords+secondPasswords+emil+character+xiyi+submits+welcome;
// 获得事件Event对象,用于兼容IE和FireFox
function getEvent() {
return window.event || arguments.callee.caller.arguments[0];
}
}
/* ------------------------------------------------------------------------------------- */
String.prototype.jsonToArray = function ()
{
if (typeof(this) != "object" || this.length < 1) {
return null;
} else {
return eval("(" + this + ")");
}
}
/** 定义工具对象 */
var Util = new Object;
/**
* 获取时段(早晨、上午、中午、下午、晚上)
*
*/
Util.getHours = function()
{
var D = new Date();
var hours = D.getHours();
if (hours > 19 && hours < 5) {
return '晚上';
} else if (hours >= 5 && hours < 11) {
return '上午';
} else if (hours >= 11 && hours < 2) {
return '中午';
} else {
return '下午';
}
alert(D.getHours());
}
/**
* 验证用户登录
*
*/
window.onload = function()
{
addSubmitEvent();
}
function addSubmitEvent()
{
if (typeof jQuery == "undefined") {
return false;
}
/** 重新获取jquery对象 */
var $ = jQuery.noConflict();
var loginForm = document.getElementById("login_form");
if ((loginForm != null))
{
loginForm.onsubmit = function()
{
var username = this["username"].value;
var password = this["password"].value;
//var checkpic = this["checkpic"].value;
if (!username) {
alert("用户名不能为空!");
this["username"].focus();
return false;
}
if (!password) {
alert("密码不能为空!");
this["password"].focus();
return false;
}
$.post("index.php/login/dologin", {"username": username, "password": password}, function(json) {
var data = json.jsonToArray();
if (data.status) {
alert(data.msg);
} else {
var html = "尊敬的用户:";
html += "<b style='color: orange; cursor: pointer' onclick='gotoHome()'>";
html += data.data.username;
html += "</b>";
html += Util.getHours();
html += "好!|";
html += "<b style='cursor: pointer' onclick='logout()'>退出</b>";
$("#login_div").html(html);
}
});
return false;
}
}
}
/**
* 退出
*
*/
function logout()
{
/** 重新获取jquery对象 */
var $ = jQuery.noConflict();
$.get("index.php/login/logout", null, function(json) {
var data = json.jsonToArray();
if (data.status) {
alert(data.msg);
} else {
var html = '<form id="login_form">';
html += '<div class="loginList">';
html += '账号 <input type="text" name="username" value="abc"> ';
html += '<input type="checkbox"/> 自动登录';
html += '</div>';
html += '<div class="loginList">';
html += '密码 <input type="password" name="password" value="abc"> ';
html += '<input id ="login" class="loginButton" type="submit" value="登录" /> ';
html += '<a href="#" style="text-decoration:none" onclick="alertWin(\'注册\',550,310);" onfocus="this.blur()">注册</a>';
html += '</div>';
$("#login_div").html(html);
addSubmitEvent();
}
});
}
/**
* 返回用户中心
*
*/
function gotoHome()
{
location = "/user/home";
}
|
PROPERTY_INFO = {
'Life Cycle Inventory Result': 'A life cycle inventory is a process of quantifying energy and raw material requirements, atmospheric emissions, waterborne emissions, solid wastes, and other releases for the entire life cycle of a product, process, or activity.',
'Production Result': 'An explanation of this property.',
'Release Result': 'Why this result is important: an explanation.',
'Fate and Transport Result': 'Information.',
'Toxicity Result': 'Toxicity is how much bad can be in the good before the good is bad.',
'Scarcity Result': 'Here is some info about this result that is useful in interpreting these numbers.',
}
|
/**
* Copyright 2020 ForgeRock AS. All Rights Reserved
*
* Use of this code requires a commercial software license with ForgeRock AS.
* or with one of its affiliates. All use shall be exclusively subject
* to such license between the licensee and ForgeRock AS.
*/
import BootstrapVue from 'bootstrap-vue';
import { createLocalVue, mount, shallowMount } from '@vue/test-utils';
import BasicInput from './index';
const localVue = createLocalVue();
localVue.use(BootstrapVue);
const defaultMixinProps = {
id: '',
errorMessages: [],
fieldName: '',
helpText: '',
hideLabel: false,
isHtml: false,
label: '',
readonly: false,
};
const defaultProps = {
autofocus: false,
type: 'test',
};
describe('BasicInput', () => {
it('BasicInput component loaded', () => {
const wrapper = shallowMount(BasicInput, {
localVue,
propsData: {
...defaultMixinProps,
...defaultProps,
},
});
expect(wrapper.name()).toBe('BasicInput');
});
it('BasicInput component renders reveal button for password', () => {
const wrapper = mount(BasicInput, {
localVue,
propsData: {
...defaultMixinProps,
...defaultProps,
type: 'password',
},
});
const button = wrapper.find('button');
const input = wrapper.find('input');
expect(button.exists()).toBe(true);
expect(button.attributes('name')).toBe('revealButton');
expect(wrapper.vm.showPassword).toBe(false);
expect(input.attributes('type')).toBe('password');
button.trigger('click');
expect(wrapper.vm.showPassword).toBe(true);
expect(input.attributes('type')).toBe('text');
});
it('BasicInput passes through component slots', () => {
const wrapper = mount(BasicInput, {
localVue,
propsData: {
...defaultMixinProps,
...defaultProps,
},
slots: {
prepend: '<span class="test_prepend">prepend</span>',
append: '<span class="test_append">append</span>',
},
});
expect(wrapper.contains('.test_prepend')).toBe(true);
expect(wrapper.contains('.test_append')).toBe(true);
});
});
|
import { createGlobalStyle } from 'styled-components'
export default createGlobalStyle`
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
}
body {
background: #eee;
}
button,
input {
outline: 0;
}
button {
cursor: pointer;
}
.footer {
font-weight: bold;
text-align: center;
color: var(--dark-blue);
opacity: 0.6;
position: relative;
top: 10px;
}
.footer i {
color: #666666;
font-size: 1.8rem;
opacity: 0.6;
margin-left: 5px;
}
i:hover {
opacity: 1;
}
` |
var projectMediaHeight = new ReactiveVar;
var projectImageDirectory = "img/projects/"
var newLine = " "
var projects = [
{ "title": "AutoSmog",
"media": "edited/autosmog-mockup-plain.jpg",
"blurb": "A digitized, remote smog check solution built off Automatic.<br>\
Engineered iOS application, Parse cloud code, and custom firmware.",
"links": [
{
"text": "Download App",
"link" : "https://itunes.apple.com/us/app/autosmog/id1059905184?mt=8"
},
{
"text": "Learn More",
"link": "https://www.automatic.com/apps/autosmog/"
},
{
"text": "Read Press",
"link": "http://finance.yahoo.com/news/automatic-teams-oregon-deq-consumers-180000885.html"
}
]
},
{ "title": "maruchikim.com",
"media": "edited/website-mockup-macbook.jpg",
"blurb": "A personal website designed and developed from the ground up.<br>\
Custom content management system built with MeteorJS."
},
// {
// "title": "Onee",
// "media": "edited/onee-grey.jpeg",
// "blurb": "Blurbidy Blurb",
// },
{ "title": "Mizu | Hydration Monitor",
"media": "edited/mizu.jpg",
"blurb": "A hydration-monitoring device prototyped for UCSF patients.<br>\
Led a product team to build housing, PCB, firmware, and iOS app.",
"links": [
{
"text": "View Presentation",
"link": "content/mizu.pdf"
}
]
},
{ "title": "Tony | Lightbulb Network",
"media": "edited/tony2.jpg",
"hover": "gif/tony.gif",
"blurb": "A voice-enabled lightbulb to control future smarthome devices.<br>\
Built with EAGLE, RFduino platform, and Google Speech API.",
"links": [
{
"text": "Watch Video",
"link": "https://www.youtube.com/watch?v=ZjZKsAmolr8"
}
]
},
{ "title": "Autonomous Racing Vehicle",
"media": "edited/ee192.jpg",
"hover": "gif/ee192.gif",
"blurb": "A racing robot that follows a curving, self-crossing track at 3+ m/s.<br>\
1st place against 38 other teams at 2014 NATCAR competition.",
"links": [
{
"text": "Watch Video",
"link" : "https://www.youtube.com/watch?v=5SQ9C-32nGY"
},
{
"text": "View Race Results",
"link": "http://www.ece.ucdavis.edu/natcar/results/2014-race-results/"
}
]
},
{ "title": "Apollo | UV Sensing Watch",
"media": "edited/watch.jpg",
"blurb": "An LED watch that keeps track of your daily sun exposure.<br>\
Fabricated functional prototype from ideation in three weeks.",
"links": [
{
"text": "View Gallery",
"link": "content/watch-gallery.pdf"
}
]
},
{ "title": "Two Cents",
"media": "edited/twocents.jpg",
"hover": "gif/twocents.gif",
"blurb": "A microdonation platform for daily $0.02 contributions.<br>\
Won 'Most Popular' award at the CITRIS Mobile App Challenge.",
"links": [
{
"text": "Watch Video",
"link": "https://www.youtube.com/watch?v=wRtLMYtwMhE"
},
{
"text": "Read Press",
"link" : "http://citris-uc.org/meet-citris-mobile-app-challenge-winners/"
}
]
},
{ "title": "Autonomous Trash Can",
"media": "edited/trashcan-2.jpg",
"hover": "gif/trashcan.gif",
"blurb": "An object-tracking robot that attempts to catch thrown projectiles.<br>\
Used ROS, OpenCV, and Kinect to find object-trajectory in 3D space.",
"links": [
{
"text": "Watch Video",
"link": "https://www.youtube.com/watch?v=4CKqBrzsDaA"
},
{
"text": "Read Paper",
"link" : "content/ball-is-life.pdf"
}
]
},
{ "title": "Bartndr | Drink Mixer",
"media": "edited/bartndr.jpg",
"hover": "gif/bartndr.gif",
"blurb": "A location-aware, point-of-sale system driven by iBeacon technology.<br>\
Awarded 'Best Hack - KPCB' and 'Best Use of Parse' at CalHacks.",
"links": [
{
"text": "Watch Video",
"link": "https://www.youtube.com/watch?v=UBuFm0XW2gY"
},
]
},
{ "title": "Orthodontics Wearable",
"media": "edited/orthodontics.jpg",
"blurb": "A medical device for UCSF patients to monitor daily retainer usage.<br>\
Designed battery algorithm to achieve over a year of battery life.",
"links": [
{
"text": "View Presentation",
"link": "content/orthodontics.pdf"
},
]
},
]
Template.projects.helpers({
projects: function() {
return projects;
}
});
Template.projects.rendered = function() {
$(window).resize(function() {
projectMediaHeight.set($(".media").width() / 1.5);
}); projectMediaHeight.set($(".media").width() / 1.5);
Tracker.autorun(function() {
$('<style>.media{height:'+projectMediaHeight.get()+'px;}</style>').appendTo('head');
});
}
Template.projects.events({
'click .media': function(event) {
var target = $(event.target.parentElement.parentElement);
if (target.find("a")[0]) {
var href = $(target.find("a")[0]).attr('href');
window.open(href, "_blank");
}
},
// Took out hover + gif stuff for now because it takes too long to load.
// 'mouseenter .media': function(event) {
// var target = $(event.target.parentElement);
// var projectName = (target.find(".title").text());
//
// for (var i = 0; i < projects.length; i++) {
// if (projects[i].title == projectName) {
// if (projects[i].hover) {
// var projectImage = $(target.find("img")[0]);
// var gifPath = projectImageDirectory+projects[i].hover;
// projectImage.attr("src", gifPath);
//
// // If you want to animate it later try this...
// // projectImage.velocity({opacity: ".75"}, 100, "linear", function() {
// // $(target.find("img")[0]).attr("src", gifPath);
// // }).velocity({opacity: "1"}, 250, "linear");
// }
// }
// }
// },
//
// 'mouseleave .media': function(event) {
// var target = $(event.target.parentElement);
// var projectName = (target.find(".title").text());
//
// for (var i = 0; i < projects.length; i++) {
// if (projects[i].title == projectName) {
// if (projects[i].hover) {
// var projectImage = $(target.find("img")[0]);
// var imagePath = projectImageDirectory+projects[i].media;
// projectImage.attr("src", imagePath);
// }
// }
// }
// }
});
|
import React, { Component } from 'react';
import ProductsScrollLeft from '../Product/ProductsScrollLeft';
class Popular extends Component{
constructor(props){
super(props);
this.state = {
popularClassName: "popular",
popularState: "hide",
caret: "caret-down",
pops: [],
position: 0,
}
this.windowResize = this.windowResizeHandler.bind(this);
this.drop = this.dropHandler.bind(this);
this.getProductByTypeId = this.getProductByTypeIdHandler.bind(this);
this.getProductByGender = this.getProductByGenderHandler.bind(this);
this.windowResize();
this.data = this.props.pop;
}
windowResizeHandler(){
window.addEventListener('resize', ()=>{
try{
if(window.innerWidth<=800){
let popular = document.getElementsByClassName('popular')[0];
let popularHeight = popular.offsetHeight + 100;
this.setState({ popularHeight });
}
}
catch(err){
}
});
}
getProductByTypeIdHandler(type){
let pops = this.data.filter(d => d.type_id[0] == type).slice(0, 4);
this.setState({pops});
}
getProductByGenderHandler(gender){
let pops = this.data.filter(d => d.oriented_id == gender).slice(0, 4);
this.setState({pops});
}
dropHandler(){
if(this.state.popularState == "show"){
let popularState = "hide";
let popularClassName = "popular";
let caret = "caret-down";
this.setState({popularClassName, popularState, caret});
}else{
let popularState = "show";
let popularClassName = "popular popu-show";
let caret = "caret-up";
if(this.state.pops.length==0){
let pops = this.props.pop.filter(d=> d.type_id[0] == 'C').slice(0, 8);
this.setState({popularClassName, popularState, caret, pops});
}
else{
this.setState({popularClassName, popularState, caret});
}
}
}
render = () =>{
return(
<li className={this.props.className + " popular-container"} style={window.innerWidth<=800?{width: `${window.innerWidth-25}px`, minWidth: "unset"}:{}}>
<a onClick={this.drop} className="nav-link">Phổ biến <span className={this.state.caret}/></a>
<div className={this.state.popularClassName}>
<div className="popular-products">
<div className="popular-option">
<ul className="pop-list">
<li onClick={() => {this.getProductByTypeId('C')}} className="pop-item">
<a className="pop-option">Kính cận</a>
</li>
<li onClick={() => {this.getProductByTypeId('V')}} className="pop-item">
<a className="pop-option">Kính viễn</a>
</li>
<li onClick = {() => {this.getProductByGender('m')}} className="pop-item">
<a className="pop-option">Kính nam</a>
</li>
<li onClick = {() => {this.getProductByGender('f')}} className="pop-item">
<a className="pop-option">Kính nữ</a>
</li>
</ul>
</div>
<div className="pop-products-container">
<ProductsScrollLeft data = {this.state.pops}/>
</div>
</div>
</div>
</li>
)
}
}
export default Popular;
|
import React,{Component} from "react";
export default class Signin extends Component{
render(){
return(
<div className="container">
<div className="row">
<div className="col-md-12">
<h1>Sign in successfully!</h1>
<div className="alert alert-success"> <strong>Well done!</strong> You successfully signed in as!
</div>
</div>
</div>
</div>
)
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { useDrag } from 'react-dnd';
import { TWEET_PROPTYPE_SHAPE, DND_TYPE_TWEET } from '../constants';
import { formatDateToTwitterFormat } from '../utils';
function Star({ isButton, buttonProps }) {
return isButton ? (
<button
type="button"
title="Remove from saved tweets"
className="button is-small is-rounded is-pulled-right ml-4"
{...buttonProps}
>
<span className="icon is-small has-text-warning">
<i className="fas fa-star"></i>
</span>
</button>
) : (
<span className="is-pulled-right ml-4">
<span className="icon is-small has-text-warning">
<i className="fas fa-star"></i>
</span>
</span>
);
}
Star.propTypes = {
isButton: PropTypes.bool.isRequired,
buttonProps: PropTypes.shape({
onClick: PropTypes.func,
}),
};
export default function Tweet({
value,
value: { user },
isDraggable,
isSavedTweet,
onRemoveTweet,
}) {
const [{ opacity, cursor }, dragRef] = useDrag({
item: { type: DND_TYPE_TWEET, ...value },
collect: (monitor) => ({
opacity: monitor.isDragging() ? 0.5 : 1,
cursor: monitor.canDrag() ? 'pointer' : 'default',
}),
canDrag: () => isDraggable,
});
return (
<>
{value && (
<div ref={dragRef} style={{ opacity, cursor }} className="box">
<article className="media">
<figure className="media-left">
<p className="image is-64x64">
<img
src={user.profile_image_url_https}
alt={user.screen_name}
/>
</p>
</figure>
<div className="media-content">
<div className="content">
<p>
<strong>{user.name}</strong>{' '}
<small>@{user.screen_name}</small>
{' '}
</p>
<p>{value.text}</p>
</div>
</div>
<div className="media-right">
{!isDraggable && (
<Star
isButton={isSavedTweet}
buttonProps={{
onClick: () =>
onRemoveTweet &&
onRemoveTweet(value.id),
}}
/>
)}
<small>
{formatDateToTwitterFormat(value.created_at)}
</small>
</div>
</article>
</div>
)}
</>
);
}
Tweet.defaultProps = {
isDraggable: true,
isSavedTweet: false,
};
Tweet.propTypes = {
value: TWEET_PROPTYPE_SHAPE.isRequired,
isDraggable: PropTypes.bool,
isSavedTweet: PropTypes.bool,
onRemoveTweet: PropTypes.func,
};
|
/*
* Controller
*************/
// Import module
// const dateformat = require('datformat')
// Import de model
const Presentation = require('../DB/models/Presentation');
const Commentaire = require('../DB/models/Commentaire');
//const articleController = require('./articleController')
//Method get
module.exports = {
get: (req, res) => {
// res.render('commentaire')
Commentaire
.find()
.exec((err, data) => {
if (err) console.log(err);
res.json(data)
})
},
// Method create(post)
create: async(req, res) => {
console.log('Controller create commentaire')
console.log(req.body)
//Declaration const presentation qui attend la reponse id
const presentation = await Presentation.findById(req.params.id)
//Declaration const new comment avec schema en recuperant idpresentation
const comment = new Commentaire({
author: req.session.user.name,
authorID: req.session.userId,
content: req.body.content,
refID: presentation._id
})
//push de idcomment de la presentation
presentation.comment.push(comment._id)
//faire une sauvegarde du new commentaire
comment.save((err) => {
if (err) return handleError(err)
})
//faire une sauvegarde de la presentation
presentation.save((err) => {
if (err) return handleError(err)
})
// on redirige sur la page presentation en chaire de cararactere ($)
res.redirect(`/presentation/${presentation._id}`)
},
// Method delete one
deleteOne: (req, res) => {
// Fonction de suppression de un Articles rechercher par son _id
Commentaire
.deleteOne({
// On va venir chercher parmis tout les _id celui égale à notre req.params (id recupéré dans l'URL)
_id: req.params.id
// ici nous avons un callback err
}, (err) => {
// Si nous avons pas d'erreur alors on redirige
if (err) console.log(err)
// Sinon on renvoit l'err
// res.json({
// succes: req.params.id + ' // à bien été supprimer'
// })
// on redirige sur la page presentation en chaire de cararactere (+ req.params.id))
res.redirect('/presentation/' + req.params.id)
})
},
} |
const viewTabID = {slice:0, isometric:1, render3D:2, text:3};
function Control(canvasName, schematic, program) {
this.targetProgram = program;
this.targetCanvas = document.getElementById(canvasName);
this.targetSchematic = schematic;
this.targetDisplay;
this.mouse = new Mouse();
this.view = new View();
this.button = [];
this.select = "none";
this.currentPalette = 2;
this.currentColour = colourComponents(this.targetSchematic.palette[this.currentPalette].colour);
this.currentTabView = viewTabID.slice;
this.createButtons();
this.createKeyboardEventHandlers();
this.createCanvasEventHandlers();
}
Control.prototype.linkDisplay = function(display) {
this.targetDisplay=display;
this.fitToWindow();
}
Control.prototype.createKeyboardEventHandlers = function () {
var t = this;
document.onkeydown = function (event) {
var keyCode;
if (event === null) {
keyCode = window.event.keyCode;
} else {
keyCode = event.keyCode;
}
if (keyCode>47 && keyCode<58) { //numeric key
var num = keyCode-49;
if (num<0) num=9;
if (num < t.targetSchematic.palette.length) {
t.selectPalette(num);
}
}
switch (keyCode) {
case 85: // u
t.newFile();
break;
case 73: // i
t.loadFile();
break;
case 79: // o
t.saveAsJSON();
break;
case 80: // p
t.saveAsImage();
break;
case 70: // f
t.fullscreen();
break;
case 65:
case 37: // a or left arrow
t.scrollLeft();
break;
case 38:
case 87: // w or up arrow
t.scrollUp();
break;
case 39:
case 68: // d or right arrow
t.scrollRight();
break;
case 40:
case 83: // s or down arrow
t.scrollDown();
break;
case 78: // n
t.increaseSize();
break;
case 77: // m
t.decreaseSize();
break;
case 69: // e
t.shiftViewUp();
break;
case 81: // q
t.shiftViewDown();
break;
case 74: // j
t.fitToWindow();
break;
case 75: // k
t.zoomIn();
break;
case 76: // l
t.zoomOut();
break;
}
};
}
Control.prototype.createCanvasEventHandlers = function () {
var t = this;
this.targetCanvas.onmousemove = function (event) { t.mouseUpdateCoords(event); };
this.targetCanvas.onmousedown = function (event) { t.mousePressed(event); };
this.targetCanvas.onmouseup = function (event) { t.mouseReleased(event); };
this.targetCanvas.onmousewheel = function (event) { t.mouseWheel(event.wheelDelta); return false; };
// special case for Mozilla...
this.targetCanvas.onwheel = function (event) { t.mouseWheel(event); return false; };
this.targetCanvas.oncontextmenu = function (event) { return false; };
this.targetCanvas.onselectstart = function (event) { return false; };
}
function Mouse() {
this.x = 0;
this.y = 0;
this.isOverWorkspace = false;
this.isPressed = false;
this.isReleased = false;
this.buttonPressed = 0;
this.isOverButton = false;
this.selected = 3;
this.newSelected = 0;
this.latticeX = 0;
this.latticeY = 0;
this.latticeZ = 0;
this.oldLatticeX = 0;
this.oldLatticeY = 0;
this.oldLatticeZ = 0;
}
Control.prototype.mouseUpdateCoords = function (event) {
var rect = this.targetCanvas.getBoundingClientRect();
this.mouse.x = event.clientX - rect.left;
this.mouse.y = event.clientY - rect.top;
this.checkHover();
}
Control.prototype.checkHover = function () {
this.mouse.isOverButton = false;
var button;
for (var i = 0; i < this.button.length; i++) {
button = this.button[i];
button.isHovered = false;
button.isClicked = false;
if (this.mouse.x >= button.x && this.mouse.x <= button.x + button.width) {
if (this.mouse.y >= button.y && this.mouse.y <= button.y + button.height) {
if (this.mouse.isReleased) {
this.mouse.newSelected = i;
this[button.function](button.functionArguments);
} else if (this.mouse.isPressed) {
button.isClicked = true;
} else {
button.isHovered = true;
}
this.mouse.isOverButton = true;
this.mouse.isOverWorkspace = false;
}
}
}
if (this.mouse.isOverButton === false && this.currentTabView === viewTabID.slice) {
this.checkLattice();
}
this.targetDisplay.refresh();
}
Control.prototype.checkLattice = function () {
this.mouse.isOverWorkspace = true;
var cellSize = this.view.cellPerPixel/(this.view.pixelPerCell+1);
this.mouse.latticeX = Math.floor((this.mouse.x - this.view.x) * cellSize);
this.mouse.latticeY = this.view.sliceHeight;
this.mouse.latticeZ = Math.floor((this.mouse.y - this.view.y) * cellSize);
if (this.mouse.latticeX < 0) {
this.mouse.isOverWorkspace = false;
this.mouse.latticeX = 0;
}
if (this.mouse.latticeX >= this.targetSchematic.width) {
this.mouse.isOverWorkspace = false;
this.mouse.latticeX = this.targetSchematic.width - 1;
}
if (this.mouse.latticeZ < 0) {
this.mouse.isOverWorkspace = false;
this.mouse.latticeZ = 0;
}
if (this.mouse.latticeZ >= this.targetSchematic.depth) {
this.mouse.isOverWorkspace = false;
this.mouse.latticeZ = this.targetSchematic.depth - 1;
}
}
Control.prototype.setOldHover = function () {
this.mouse.oldLatticeX = this.mouse.latticeX;
this.mouse.oldLatticeY = this.mouse.latticeY;
this.mouse.oldLatticeZ = this.mouse.latticeZ;
}
Control.prototype.mousePressed = function (event) {
this.mouse.buttonPressed = event.which;
this.mouse.isPressed = true;
this.setOldHover();
this.checkHover();
}
Control.prototype.mouseReleased = function (event) {
this.mouse.isReleased = true;
this.mouse.isPressed = false;
this.checkHover();
this.mouse.isReleased = false;
this.checkHover();
if (this.mouse.isOverWorkspace) {
var start = [this.mouse.latticeX,this.mouse.latticeY,this.mouse.latticeZ];
var end = [this.mouse.oldLatticeX,this.mouse.oldLatticeY,this.mouse.oldLatticeZ];
if (this.mouse.buttonPressed === 1) {
this.targetSchematic.setVolume(start, end, this.currentPalette);
} else if (this.mouse.buttonPressed === 3) {
this.targetSchematic.setVolume(start, end, 0);
}
this.targetDisplay.updateRender();
}
this.targetDisplay.refresh();
}
Control.prototype.mouseWheel = function (event) {
var change = -event.deltaY || event.wheelDelta;
if (change < 0) {
//this.zoomOut();
this.shiftViewDown();
} else if (change > 0) {
//this.zoomIn();
this.shiftViewUp();
}
this.checkHover();
}
function View() {
this.offsetX = 0;
this.offsetY = 48;
this.x = this.offsetX;
this.y = this.offsetY;
this.borderTop = 48;
this.borderLeft = 0;
this.borderRight = 232;
this.borderBottom = 48;
this.pixelPerCell = 16;
this.cellPerPixel = 1;
this.sliceHeight = 0;
}
Control.prototype.createButtons = function () {
var c = this.targetCanvas;
var t = this;
this.button = [];
// file modification
this.button.push( new Button(2, 24, 22, 22, 0, "U", "newFile") );
this.button.push( new Button(26, 24, 22, 22, 1, "I", "loadFile") );
this.button.push( new Button(50, 24, 22, 22, 2, "O", "saveAsJSON") );
this.button.push( new Button(74, 24, 22, 22, 5, "P", "saveAsImage") );
// viewport options
this.button.push( new Button(155, 24, 36, 22, null, "", "toggleMainView", viewTabID.slice) );
this.button.push( new Button(195, 24, 56, 22, null, "", "toggleMainView", viewTabID.isometric) );
this.button.push( new Button(255, 24, 55, 22, null, "", "toggleMainView", viewTabID.render3D) );
this.button.push( new Button(315, 24, 42, 22, null, "", "toggleMainView", viewTabID.text) );
// palette
var palette = this.targetSchematic.palette;
var px = this.targetCanvas.width-203;
var py = 497;
var x=0, y=0;
for (var i=0; i<palette.length; i++) {
this.button.push( new Button(px+x*24, py+y*24, 22, 22, null, i+1, "selectPalette", i) );
x++;
if (x>7) {
x=0;
y++;
}
}
// edit palette buttons
this.button.push( new Button(px+x*24, py+y*24, 22, 22, 11, "", "extendPalette") );
this.button.push( new Button(c.width-33, 286, 22, 22, 7, "", "removePalette") );
// rotation buttons
this.button.push( new Button(c.width-214, 240, 22, 22, 8, "", "rotateRender", -1) );
this.button.push( new Button(c.width-23, 240, 22, 22, 9, "", "rotateRender", 1) );
// colour sliders
this.button.push( new Button(px+20, 370, 160, 22, null, "", "changeColour", 0) );
this.button.push( new Button(px+20, 400, 160, 22, null, "", "changeColour", 1) );
this.button.push( new Button(px+20, 430, 160, 22, null, "", "changeColour", 2) );
// viewport controls
this.button.push( new Button(c.width - 21, 1, 20, 20, 10, "F", "fullscreen") );
this.button.push( new Button(c.width - this.view.borderRight, 48, 16, 16, 12, "W", "scrollUp") );
this.button.push( new Button(c.width - this.view.borderRight, c.height - 58, 16, 16, 13, "S", "scrollDown") );
this.button.push( new Button(0, c.height - 42, 16, 16, 14, "A", "scrollLeft") );
this.button.push( new Button(c.width - (16+this.view.borderRight), c.height - 42, 16, 16, 15, "D", "scrollRight") );
// size and scale
this.button.push( new Button(3, c.height - 23, 20, 20, 16, "", "trimEdges") );
this.button.push( new Button(23, c.height - 23, 20, 20, null, "", "increaseSize", [2,0,0]) );
this.button.push( new Button(47, c.height - 23, 20, 20, null, "", "increaseSize", [0,1,0]) );
this.button.push( new Button(71, c.height - 23, 20, 20, null, "", "increaseSize", [0,0,2]) );
this.button.push( new Button(95, c.height - 23, 20, 9, 3, "N", "increaseSize") );
this.button.push( new Button(95, c.height - 12, 20, 9, 4, "M", "decreaseSize") );
this.button.push( new Button(440, c.height - 23, 20, 9, 3, "E", "shiftViewUp") );
this.button.push( new Button(440, c.height - 12, 20, 9, 4, "Q", "shiftViewDown") );
this.button.push( new Button(152, c.height - 23, 20, 20, 17, "", "noEffect") );
this.button.push( new Button(c.width - 70, c.height - 23, 20, 20, 18, "J", "fitToWindow") );
this.button.push( new Button(c.width - 46, c.height - 23, 20, 20, 19, "K", "zoomIn") );
this.button.push( new Button(c.width - 22, c.height - 23, 20, 20, 20, "L", "zoomOut") );
// scrollbar sections
this.button.push( new Button(c.width - this.view.borderRight, 64, 16, 16, null, "W", "scrollUp") );
this.button.push( new Button(c.width - this.view.borderRight, c.height - 74, 16, 16, null, "S", "scrollDown") );
this.button.push( new Button(16, c.height - 42, 16, 16, null, "A", "scrollLeft") );
this.button.push( new Button(c.width - (32+this.view.borderRight), c.height - 42, 16, 16, null, "D", "scrollRight") );
// file tab button
// this.button[27] = new Button(1, 1, 30, 19, null, "fileMenu");
this.button[4].isSelected = true;
this.button[this.currentPalette+8].isSelected = true;
this.mouse.selected = this.currentPalette+4;
}
function Button(x, y, width, height, icon, hotkey, func, funcArgs) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.icon = icon;
this.hotkey = hotkey;
this.function = func
this.functionArguments = funcArgs;
this.isHovered = false;
this.isSelected = false;
this.isClicked = false;
}
Control.prototype.repositionButtons = function () {
this.createButtons();
//this.button[this.mouse.selected].isSelected = true;
}
// file handling
Control.prototype.newFile = function () {
this.targetSchematic.clear();
this.targetDisplay.updateRender();
}
Control.prototype.loadFile = function() {
this.select = "load file";
this.targetProgram.createOpenPrompt();
}
Control.prototype.saveAsJSON = function() {
this.select = "save file";
this.targetProgram.saveJSON();
}
Control.prototype.saveAsImage = function() {
this.select = "save file";
this.targetProgram.saveImage();
}
Control.prototype.toggleMainView = function(newView) {
this.button[this.currentTabView+4].isSelected = false;
this.button[newView+4].isSelected = true;
this.currentTabView = newView;
this.fitToWindow();
}
// rotate isometric render
Control.prototype.rotateRender = function(direc) {
var rotation = this.targetDisplay.render.rotation;
rotation += direc;
if (rotation < 0) rotation = 3;
if (rotation > 3) rotation = 0;
this.targetDisplay.render.rotation = rotation;
this.targetDisplay.minimap.rotation = rotation;
this.targetDisplay.updateRender();
}
// palette editing
Control.prototype.selectPalette = function(id) {
this.currentPalette = id;
this.button[this.mouse.selected].isSelected = false;
this.mouse.selected = id + 8;
this.button[this.mouse.selected].isSelected = true;
this.currentColour = colourComponents(this.targetSchematic.palette[id].colour);
}
Control.prototype.extendPalette = function() {
this.currentPalette = this.targetSchematic.palette.length;
this.targetSchematic.extendPalette();
this.repositionButtons();
this.button[this.mouse.selected].isSelected = false;
this.mouse.selected = this.currentPalette + 4;
this.button[this.mouse.selected].isSelected = true;
this.currentColour = colourComponents(this.targetSchematic.palette[this.currentPalette].colour);
this.targetDisplay.updatePalette();
}
Control.prototype.removePalette = function() {
if (this.currentPalette>0) {
this.targetSchematic.removePaletteEntry(this.currentPalette);
this.currentPalette = 0;
this.repositionButtons();
this.button[this.mouse.selected].isSelected = false;
this.mouse.selected = this.currentPalette + 4;
this.button[this.mouse.selected].isSelected = true;
this.currentColour = colourComponents(this.targetSchematic.palette[this.currentPalette].colour);
this.targetDisplay.updatePalette();
}
}
Control.prototype.changeColour = function(colourID) {
var targetButton = this.button[this.mouse.newSelected];
var step = 255/targetButton.width;
var newValue = Math.floor((this.mouse.x - targetButton.x)*step);
this.currentColour[colourID] = newValue;
var id = this.currentPalette ;
var colour = this.currentColour;
this.targetSchematic.palette[id].colour = toRGBString(colour[0], colour[1], colour[2]);
this.targetDisplay.updatePalette();
}
// move view
Control.prototype.fullscreen = function() {
this.select = "fullscreen";
if (!document.mozFullScreen && !document.webkitFullScreen) {
if (this.targetCanvas.mozRequestFullScreen) {
this.targetCanvas.mozRequestFullScreen();
} else {
this.targetCanvas.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else {
document.webkitCancelFullScreen();
}
}
}
Control.prototype.scrollUp = function() {
this.select = "scroll up";
this.view.y += this.view.pixelPerCell;
}
Control.prototype.scrollDown = function() {
this.select = "scroll down";
this.view.y -= this.view.pixelPerCell;
}
Control.prototype.scrollLeft = function() {
this.select = "scroll left";
this.view.x += this.view.pixelPerCell;
}
Control.prototype.scrollRight = function() {
this.select = "scroll right";
this.view.x -= this.view.pixelPerCell;
}
// change schematic size
Control.prototype.increaseSize = function(axis) {
if (axis) {
this.targetSchematic.changeSize(axis[0],axis[1],axis[2]);
} else {
this.targetSchematic.changeSize(2,2,2);
this.view.sliceHeight++;
}
this.fitToWindow();
this.targetDisplay.minimap.resizeTileSize(200,200);
this.targetDisplay.updateRender();
}
Control.prototype.decreaseSize = function() {
this.targetSchematic.decreaseSize(2,2,2);
if (this.view.sliceHeight >= this.targetSchematic.height) {
this.view.sliceHeight = this.targetSchematic.height -1;
}
this.fitToWindow();
this.targetDisplay.minimap.resizeTileSize(200,200);
this.targetDisplay.updateRender();
}
Control.prototype.trimEdges = function() {
this.targetSchematic.trimEdges();
if (this.view.sliceHeight >= this.targetSchematic.height) this.view.sliceHeight = this.targetSchematic.height-1;
this.fitToWindow();
this.targetDisplay.minimap.resizeTileSize(200,200);
this.targetDisplay.updateRender();
}
Control.prototype.noEffect = function() {
}
// change displayed slice
Control.prototype.shiftViewUp = function() {
this.view.sliceHeight++;
if (this.view.sliceHeight >= this.targetSchematic.height) {
this.view.sliceHeight = this.targetSchematic.height -1;
}
}
Control.prototype.shiftViewDown = function() {
this.view.sliceHeight--;
if (this.view.sliceHeight < 0 ) {
this.view.sliceHeight = 0;
}
}
// change zoom level
Control.prototype.fitToWindow = function() {
var model = this.targetSchematic
this.select = "fit to window";
this.view.pixelPerCell = 128;
this.view.cellPerPixel = 1;
var maxWorkspaceWidth = this.targetCanvas.width - (this.view.borderLeft + this.view.borderRight);
var maxWorkspaceHeight = this.targetCanvas.height - (this.view.borderTop + this.view.borderBottom);
if (this.currentTabView === viewTabID.isometric) {
this.targetDisplay.render.resizeTileSize(maxWorkspaceWidth,maxWorkspaceHeight);//maxWorkspaceWidth, maxWorkspaceHeight);
}
while (this.view.pixelPerCell > maxWorkspaceWidth / model.width && this.view.pixelPerCell > 1) {
this.view.pixelPerCell = this.view.pixelPerCell / 2;
}
while (this.view.pixelPerCell > maxWorkspaceHeight / model.depth && this.view.pixelPerCell > 1) {
this.view.pixelPerCell = this.view.pixelPerCell / 2;
}
this.view.cellPerPixel = 1;
if (this.targetDisplay.topdown.tileSize !== this.view.pixelPerCell+1) {
this.targetDisplay.topdown.tileSize = this.view.pixelPerCell+1;
this.targetDisplay.updateRender();
}
var workspaceWidth = model.width * this.view.pixelPerCell / this.view.cellPerPixel;
var workspaceHeight = model.depth * this.view.pixelPerCell / this.view.cellPerPixel;
if (workspaceWidth < maxWorkspaceWidth) {
this.view.x = this.view.borderLeft + (maxWorkspaceWidth - workspaceWidth) / 2;
}
if (workspaceHeight < maxWorkspaceHeight) {
this.view.y = this.view.borderTop + (maxWorkspaceHeight - workspaceHeight) / 2;
}
this.view.x = Math.floor(this.view.x);
this.view.y = Math.floor(this.view.y);
}
Control.prototype.zoomIn = function () {
this.select = "zoom in";
this.view.cellPerPixel = this.view.cellPerPixel / 2;
if (this.view.cellPerPixel < 1) {
this.view.cellPerPixel = 1;
this.view.pixelPerCell = this.view.pixelPerCell * 2;
}
this.view.x = this.view.x-this.targetCanvas.width/4; //Math.floor(this.view.x * 2 - this.mouse.x);
this.view.y = this.view.y-this.targetCanvas.height/4;//Math.floor(this.view.y * 2 - this.mouse.y);
}
Control.prototype.zoomOut = function () {
this.select = "zoom out";
this.view.pixelPerCell = this.view.pixelPerCell / 2;
if (this.view.pixelPerCell < 1) {
this.view.pixelPerCell = 1;
this.view.cellPerPixel = this.view.cellPerPixel * 2;
}
this.view.x = (this.view.x + this.targetCanvas.width - this.mouse.x) / 2;
this.view.y = (this.view.y + this.targetCanvas.height - this.mouse.y) / 2;
var maxWorkspaceWidth = this.targetCanvas.width - (this.view.borderLeft + this.view.borderRight);
var maxWorkspaceHeight = this.targetCanvas.height - (this.view.borderTop + this.view.borderBottom);
var workspaceWidth = this.targetSchematic.width * this.view.pixelPerCell / this.view.cellPerPixel;
var workspaceHeight = this.targetSchematic.height * this.view.pixelPerCell / this.view.cellPerPixel;
if (workspaceWidth < maxWorkspaceWidth) {
this.view.x = this.view.borderLeft + (maxWorkspaceWidth - workspaceWidth) / 2;
}
if (workspaceHeight < maxWorkspaceHeight) {
this.view.y = this.view.borderTop + (maxWorkspaceHeight - workspaceHeight) / 2;
}
this.view.x = Math.floor(this.view.x);
this.view.y = Math.floor(this.view.y);
}
|
define([
'apps/system2/docsetting/docsetting',
'apps/system2/docsetting/docsetting.service'], function (app) {
app.module.controller("docsetting.controller.file", function ($scope,$state, docsettingService, $uibModal) {
var loadFileLibrarys = function () {
var nodeTypes = {
0: "cloud",
1: "folder",
2: "circle"
}
var convertTreeNode = function (parentNumber,fileNumber, nodes) {
angular.forEach(nodes, function (item) {
item.text = item.Name;
item.type = nodeTypes[item.NodeType];
item.state = { 'opened': true };
item.src = item.Children == undefined || item.Children.length == 0 ? "docsetting.file.field" : "docsetting.file.op";
item.fileNumber = item.NodeType == 1 ? item.Number : fileNumber;
item.ParentFullKey = parentNumber ? parentNumber + ".Node." : "";
pkey = item.ParentFullKey + item.Number;
item.children = convertTreeNode(pkey,item.fileNumber, item.Children);
})
return nodes;
}
docsettingService.file.getList().then(function (result) {
angular.forEach(result, function (item) {
item.children = convertTreeNode("","", item.Children);
item.text = item.Name;
item.type = nodeTypes[item.NodeType]
item.state = { 'opened': true };
item.src = "docsetting.file.op";
})
$scope.documents = result;
});
}
$scope.createFileLibrary = function (node,title) {
if (node == undefined) {
node = $scope.currentFile;
}
var modalInstance = $uibModal.open({
animation: false,
templateUrl: 'apps/system2/docsetting/file/view/file-maintain.html',
size: 'sm',
controller: "docsetting.controller.file.maintain",
resolve: {
maintainInfo: function () {
return {
update: false,
title: title,
fileInfo: {
FondsNumber: node.FondsNumber,
ParentFullKey: node.type == "cloud" ? "" : node.ParentFullKey + node.Number + ".Node."
},
};
}
}
});
modalInstance.result.then(function (info) {
loadFileLibrarys();
}, function () {
//dismissed
});
}
var updateFileLibrary = function (fileInfo, title) {
var modalInstance = $uibModal.open({
animation: false,
templateUrl: 'apps/system2/docsetting/file/view/file-maintain.html',
size: 'sm',
controller: "docsetting.controller.file.maintain",
resolve: {
maintainInfo: function () {
return {
update: true,
title: title,
fileInfo: fileInfo
};
}
}
});
modalInstance.result.then(function (info) {
loadFileLibrarys();
}, function () {
//dismissed
});
}
var delFileLibrary = function (fileInfo) {
bootbox.confirm("删除节点将同时删除该节点下的所有文件,确认删除?", function (result) {
if (result === true) {
docsettingService.file.del(fileInfo.FondsNumber, fileInfo.type == "cloud" ? "" : fileInfo.ParentFullKey + fileInfo.Number).then(function () {
loadFileLibrarys();
});
}
});
}
var generateFileLibrary = function (node) {
docsettingService.file.generate(node.FondsNumber, node.Number).then(function () {
bootbox.alert("文件库生成成功");
})
}
$scope.treeContextmenu = function (node) {
var add = {
"label": "添加文件库",
"icon": "fa fa-folder",
"action": function (obj) {
$scope.createFileLibrary(node.original, "添加文件库");
},
};
var del = {
"label": "删除节点",
"icon": "fa fa-close",
"action": function (obj) {
delFileLibrary(node.original);
},
};
var update = {
"label": "修改节点",
"icon": "fa fa-edit",
"action": function (obj) {
updateFileLibrary(node.original, "修改节点");
},
};
var generate = {
"label": "生成文件库",
"icon": "fa fa-check-circle",
"action": function (obj) {
generateFileLibrary(node.original)
},
}
var addCategory = {
"label": "添加分类",
"icon": "fa fa-circle",
"action": function (obj) {
$scope.createFileLibrary(node.original, "添加分类");
},
}
if (node.type == "cloud") {
return { "add": add, };
} else if (node.type == "folder") {
addCategory.separator_after = true;
return {
"addCategory" : addCategory,
"del": del,
"update": update,
"generate": generate,
};
} else if (node.type == "circle") {
addCategory.separator_after = true;
return {
"addCategory": addCategory,
"del": del,
"update": update,
};
}
}
$scope.changed = function (e, data) {
$scope.setCurrent(data.node.original);
}
$scope.setCurrent = function (info) {
$scope.$safeApply(function () {
$scope.currentFile = info;
})
$state.go(info.src);
}
loadFileLibrarys();
});
app.module.controller("docsetting.controller.file.maintain", function ($scope, docsettingService, $uibModal, $uibModalInstance, maintainInfo) {
$scope.update = maintainInfo.update;
$scope.fileInfo = maintainInfo.fileInfo;
$scope.title = maintainInfo.title;
$scope.save = function () {
if (maintainInfo.update) {
docsettingService.file.update($scope.fileInfo).then(function () {
$uibModalInstance.close($scope.fileInfo);
});
} else {
docsettingService.file.check($scope.fileInfo).then(function (result) {
if (!result) {
docsettingService.file.add($scope.fileInfo).then(function () {
$uibModalInstance.close($scope.fileInfo);
});
} else {
bootbox.alert("文件库名称重复");
}
})
}
};
$scope.close = function () {
$uibModalInstance.dismiss('cancel');
}
});
});
|
// @ts-check
// @ts-ignore
var P = P || {};
/**
* Translations for forkphorus (the player, the website, everything)
*/
P.i18n = (function() {
'use strict';
var i18n = {};
i18n.translations = {
// Messages that start with "player" affect the project player used in the homepage, embed, packages, etc.
// Messages that start with "index" affect the homepage
en: {
'player.controls.turboIndicator': 'Turbo Mode',
'player.controls.fullscreen.title': 'Click to fullscreen player, Shift+click to just maximize.',
'player.controls.flag.title': 'Shift+click to enable turbo mode.',
'player.controls.flag.title.enabled': 'Turbo mode is enabled. Shift+click to disable turbo mode.',
'player.controls.flag.title.disabled': 'Turbo mode is disabled. Shift+click to enable turbo mode.',
'player.controls.muted': 'Muted',
'player.controls.muted.title': 'Your browser isn\'t allowing us to play audio. You may need to interact with the page before audio can be played.',
'studioview.authorAttribution': 'by $author',
'studioview.projectHoverText': '$title by $author',
'report.crash.html': 'An internal error occurred. <a $attrs>Click here</a> to file a bug report.',
'report.crash.instructions': 'Describe what you were doing to cause this error:',
'report.crash.unsupported': 'This project type ($type) is not supported. For more information and workarounds, <a href="https://github.com/forkphorus/forkphorus/wiki/On-Scratch-1-Projects" target="_blank" rel="noopener">visit this help page</a>.',
'report.bug.instructions': 'Describe the issue:',
'index.document.title': 'forkphorus - phosphorus for Scratch 3',
'index.report': 'Report a problem',
'index.embed': 'Embed this project',
'index.package': 'Package this project',
'index.settings': 'Settings',
'index.credits': 'Credits',
'index.code': 'Code',
'index.studio.view': 'View studio on Scratch.',
'index.package.button': 'Package',
'index.package.turbo': 'Turbo mode',
'index.package.fullscreen': 'Full screen',
'index.package.480': '480\u00D7360',
'index.package.custom': 'Other:',
'index.package.divider': '\u00D7',
'index.embed.description': 'Include the forkphorus player in your web site.',
'index.embed.autostart': 'Start automatically',
'index.embed.lightControls': 'Light controls',
'index.embed.hideUI': 'Hide UI',
},
es: {
'player.controls.turboIndicator': 'Modo Turbo',
'player.controls.muted': 'Silenciado',
'studioview.authorAttribution': 'por $author',
'studioview.projectHoverText': '$title por $author',
'index.report': 'Reportar un problema',
'index.settings': 'Configuraciones',
'index.credits': 'Créditos',
'index.code': 'Código',
},
};
i18n.language = navigator.language;
if (i18n.language.indexOf('-') > -1) {
// remove a country code, if it has one.
i18n.language = i18n.language.substring(0, i18n.language.indexOf('-'));
}
if (!i18n.translations[i18n.language]) {
// if this language isn't supported then just default back to english
i18n.language = 'en';
}
/**
* Translate a message ID to the user's language.
* @param {string} messageId The ID of the message. See `i18n.translations`
*/
i18n.translate = function translate(messageId) {
var translations = i18n.translations[i18n.language];
if (translations[messageId]) {
return translations[messageId];
}
// if the user's language does not have a translation, we default to english
if (i18n.translations.en[messageId]) {
return i18n.translations.en[messageId];
}
console.warn('Missing translation:', messageId);
return '## ' + messageId + ' ##';
};
/**
* Translate the children of an element.
* Any children with `data-i18n` set to a message ID will have its textContent replaced.
* @param {HTMLElement} element The element to translate
*/
i18n.translateElement = function translateElement(element) {
var translatable = element.querySelectorAll('[data-i18n]');
for (var i = 0; i < translatable.length; i++) {
var el = translatable[i];
var messageId = el.getAttribute('data-i18n');
var result = i18n.translate(messageId);
// TODO: for some of these innerHTML would actually make sense and make things simpler, but has some obvious issues.
el.textContent = result;
}
};
return i18n;
}());
|
"use strict";
postInit(function(){
var componentObj = new HIPI.framework.Component();
componentObj.defineHtmlElementSelector("newContradictionTabs");
componentObj.defineComponentPropName("domain");
componentObj.defineComponentPropName("dialogPositionChain");
componentObj.defineComponentPropName("contradictionPositionChain");
componentObj.addHtmlGenerator(function(elementIdOfComponentInstanceWrapper, componentPropertiesObj, stateSlicesObj){
if(HIPI.lib.Contradictions.isContradictionLevelSkeptical(componentPropertiesObj.contradictionPositionChain)){
var classExtension = "skeptical";
var dialogMessageTitle = "A New Contradiction Here Will Invalidate the Underlying Dialog";
}
else{
var classExtension = "trusting";
var dialogMessageTitle = "A New Contradiction Here Will Restore the Underlying Dialog to a State of TRUE";
}
var retHtml = "<nav class='tabs-nav'>" +
"<ul>" +
"<li><a class='"+(stateSlicesObj.newContradictionSelectedTab === "suggested-contradictions" ? "active-nav" : "inactive-nav")+"' id='nav-new-contradiction-suggestions"+elementIdOfComponentInstanceWrapper+"' href='#'>Suggested Contradictions</a></li>" +
"<li><a class='"+(stateSlicesObj.newContradictionSelectedTab === "new-contradiction" ? "active-nav" : "inactive-nav")+"' id='nav-new-contradiction-custom"+elementIdOfComponentInstanceWrapper+"' href='#'>Create a New Contradiction</a></li>" +
"</ul>" +
"</nav>" +
"<div class='nav-new-contradiction-bottom-border-"+classExtension+"'></div>" +
"<div class='tabs-nav-container'>";
if(stateSlicesObj.newContradictionSelectedTab === "suggested-contradictions")
retHtml += "<suggestedContradictions domain='"+componentPropertiesObj.domain+"' dialogPositionChain='"+componentPropertiesObj.dialogPositionChain+"' contradictionPositionChain='"+componentPropertiesObj.contradictionPositionChain+"'></suggestedContradictions>";
else if(stateSlicesObj.newContradictionSelectedTab === "new-contradiction")
retHtml += "<newContradiction domain='"+componentPropertiesObj.domain+"' dialogPositionChain='"+componentPropertiesObj.dialogPositionChain+"' contradictionPositionChain='"+componentPropertiesObj.contradictionPositionChain+"'></newContradiction>";
else
throw new Error("Error in addHtmlGenerator for the <newContradictionTabs> component. Cannot determine the selected tab.");
retHtml += "</div>";
retHtml += "<h2 class='respond-to-title'>"+dialogMessageTitle+"</h2><div class='new-message-responding-to-message'>" + HIPI.framework.Utilities.htmlizeStringWithLineBreaks(stateSlicesObj.respondToMessage) + "</div>";
return retHtml;
});
componentObj.addStateExtractor(function(componentPropertiesObj, globalStateObj){
var retStateObj = {};
var subArrayRef = HIPI.lib.General.getDialogOrContradictionReference(globalStateObj, componentPropertiesObj.domain, componentPropertiesObj.dialogPositionChain, componentPropertiesObj.contradictionPositionChain);
if(!subArrayRef.newContradictionSelectedTab)
retStateObj.newContradictionSelectedTab = "suggested-contradictions";
else
retStateObj.newContradictionSelectedTab = subArrayRef.newContradictionSelectedTab;
// So that users know what Dialog Message is being fought over.
retStateObj.respondToMessage = HIPI.lib.Dialogs.getMessageFromDialogPosition(globalStateObj, componentPropertiesObj.domain, componentPropertiesObj.dialogPositionChain);
return retStateObj;
});
componentObj.addDomBindRoutine(function(elementIdOfComponentInstanceWrapper, componentPropertiesObj, stateSlicesObj){
var tabOneElementId = "nav-new-contradiction-suggestions"+elementIdOfComponentInstanceWrapper;
if(document.getElementById(tabOneElementId)){
document.getElementById(tabOneElementId).addEventListener("click", function(e){
e.preventDefault();
HIPI.state.ActionMethods.newContradictionSelectTab(componentPropertiesObj.domain, componentPropertiesObj.dialogPositionChain, componentPropertiesObj.contradictionPositionChain, "suggested-contradictions");
return false;
});
}
var tabTwoElementId = "nav-new-contradiction-custom"+elementIdOfComponentInstanceWrapper;
if(document.getElementById(tabTwoElementId)){
document.getElementById(tabTwoElementId).addEventListener("click", function(e){
e.preventDefault();
HIPI.state.ActionMethods.newContradictionSelectTab(componentPropertiesObj.domain, componentPropertiesObj.dialogPositionChain, componentPropertiesObj.contradictionPositionChain, "new-contradiction");
return false;
});
}
});
componentObj.addReducer(function(stateObj, actionObj){
HIPI.framework.Utilities.ensureTypeObject(stateObj);
HIPI.framework.Utilities.ensureValidActionObject(actionObj);
switch(actionObj.type){
case HIPI.state.ActionNames.NEW_CONTRADICTION_SELECT_TAB :
var subArrayRef = HIPI.lib.General.getDialogOrContradictionReference(stateObj, actionObj.domain, actionObj.dialogPositionChain, actionObj.contradictionPositionChain);
if(["suggested-contradictions", "new-contradiction"].indexOf(actionObj.tabName) === -1)
throw new Error("Error in addReducer for <newContradictionTabs> component. The tabName is invalid: " + actionObj.tabName);
subArrayRef.newContradictionSelectedTab = actionObj.tabName;
console.log("Select New Contradiction Tab:", actionObj.tabName);
break;
}
return stateObj;
});
HIPI.framework.ComponentCollection.addComponent(componentObj);
});
|
import React from 'react';
import {StyleSheet, Text} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import {useNavigation} from '@react-navigation/native';
import normalize from 'react-native-normalize';
export function SkipButton() {
const navigation = useNavigation();
return (
<TouchableOpacity
style={styles.skipButtonContainer}
activeOpacity={0.5}
onPress={() => navigation.replace('SkipScreen')}>
<Text style={styles.skipText}>SKIP</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
skipButtonContainer: {
padding: normalize(10, 'width'),
},
skipText: {
color: '#ffffff',
fontWeight: 'bold',
},
});
|
// @flow
import React, {Component} from 'react';
import {StyleSheet} from 'react-native';
import {
DotIndicator,
BarIndicator,
BallIndicator,
PacmanIndicator,
PulseIndicator,
SkypeIndicator,
WaveIndicator,
} from 'react-native-indicators';
import * as Animatable from 'react-native-animatable';
import {Text, View} from './core';
import {THEME_COLOR} from '../constants/colors';
type Props = {
visible: boolean,
type?: 'dot' | 'bar' | 'ball' | 'pacman' | 'pulse' | 'skype' | 'wave',
text?: string,
};
const defaultLoadingComponent = {
dot: {
Component: DotIndicator,
},
bar: {
Component: BarIndicator,
props: {
count: 5,
},
},
ball: {
Component: BallIndicator,
},
pacman: {
Component: PacmanIndicator,
},
pulse: {
Component: PulseIndicator,
},
skype: {
Component: SkypeIndicator,
},
wave: {
Component: WaveIndicator,
},
};
const DEFAULT_LOADING_INDICATOR_TYPE = 'bar';
export default class LoadingIndicator extends Component<Props, void> {
_loadingIndicator: ?Object;
componentDidMount() {
if (this.props.visible) {
this._loadingIndicator && this._loadingIndicator.fadeIn();
}
}
componentWillReceiveProps(newProps: Props) {
let oldProps = this.props;
if (oldProps.visible !== newProps.visible) {
if (newProps.visible) {
this._loadingIndicator && this._loadingIndicator.fadeIn();
} else {
this._loadingIndicator && this._loadingIndicator.fadeOut();
}
}
}
render() {
let {text: loadingText, type, ...otherProps} = this.props;
let {
Component: LoadingComponent,
...otherDefaultKey
} = defaultLoadingComponent[type || DEFAULT_LOADING_INDICATOR_TYPE];
let defaultProps =
(otherDefaultKey.props && {...otherDefaultKey.props}) || {};
return (
<Animatable.View
ref={(loadingIndicator) => (this._loadingIndicator = loadingIndicator)}
style={[styles.root]}
>
<LoadingComponent
{...defaultProps}
{...otherProps}
color={THEME_COLOR}
/>
{loadingText ? (
<View style={styles.text}>
<Text style={{textAlign: 'center'}}>{loadingText}</Text>
</View>
) : null}
</Animatable.View>
);
}
}
const styles = StyleSheet.create({
root: {
alignItems: 'center',
justifyContent: 'center',
},
text: {
paddingHorizontal: 30,
},
});
|
import { useEffect, useState, useContext } from "react"
import { FirebaseContext } from "../context/firebase"
export default function useContent(target) {
const [content, setContent] = useState([])
const { firebase } = useContext(FirebaseContext)
useEffect(() => {
const unsubscribe = firebase
.firestore()
.collection(target)
.orderBy("fullDate", "desc")
.onSnapshot((snapshot) =>
setContent(snapshot.docs.map((doc) => doc.data()))
)
return () => {
unsubscribe()
}
}, [])
return { [target]: content }
}
|
"use strict";
var models = require('../models');
var bcrypt = require("bcrypt");
exports.login = function (req, res) {
if (req.session.authenticated) return res.redirect('/dashboard');
models.User.findOne({
where: { username: req.body.username }
}).then(function (data) {
if (!data) {
return res.redirect('/');
}
bcrypt.compare(req.body.password, data.dataValues.password, function (err, match) {
if (!match) {
return res.redirect('/');
}
req.session.authenticated = true;
req.session.user = data.dataValues;
return res.redirect('/dashboard');
});
})
}
exports.logout = function (req, res) {
req.session.destroy();
return res.redirect('/');
}
exports.signup = function (req, res) {
if (req.session.authenticated) return res.redirect('/dashboard');
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(req.body.password, salt, function(err, hash) {
models.User.create({
username: req.body.username,
password: hash,
type: req.body.type
})
.then(function (data) {
return exports.login(req, res);
})
.error(function (error) {
if (error) {
console.log(error);
return res.redirect('/');
}
});
});
});
} |
import React from "react";
import TopBar from "./TopBar";
import DevelopmentPlan from "../../containers/DevelopmentPlan";
const DevPlanPage = props => {
return (
<div className="embedded-dev-plan">
<h3 style={{ textAlign: "center" ,fontSize:"18px"}}>
EMPLOYEE PERFORMANCE REVIEW
</h3>
<TopBar {...props} />
<div className="dev-plan-body">
<DevelopmentPlan personId={props.personAssessed.id} />
</div>
</div>
);
};
export default DevPlanPage;
|
const express = require('express');
const knex = require('knex');
const knexConfig = require('./knexfile');
const studentsRouter = require('./students/students-router');
const cohortsRouter = require('./cohorts/cohorts-router');
const db = knex(knexConfig.development);
const server = express();
server.use(express.json());
server.get('/', async (req, res) => {
try {
const cohorts = await db('cohorts');
res.status(200).json(cohorts);
} catch (error) {
res.status(500).json({ error: `${error}` });
};
});
server.use('/students', studentsRouter);
server.use('/cohorts', cohortsRouter);
const port = process.env.PORT || 5000;
server.listen(port, () => console.log(`\n** Running on port ${port} **\n`)); |
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import empformServices from "../../../services/empForm.service";
import Grid from "@material-ui/core/Grid";
import CardContent from "@material-ui/core/CardContent";
import AutorenewIcon from "@material-ui/icons/Autorenew";
import { Form } from "../../../components/patient-ui/Echannelling/useForm";
import {
Button,
Card,
Container,
TextField,
Typography,
} from "@material-ui/core";
import Swal from "sweetalert2";
function Updateform() {
const id = useParams();
const initialEmployee = {
role: "",
firstName: "",
lastName: "",
email: "",
mobile: "",
address: "",
};
const [employee, setEmployee] = useState(initialEmployee);
//get employee details by id
const getEmployee = (id) => {
empformServices
.getOneEmployee(id)
.then((response) => {
setEmployee(response.data);
})
.catch((e) => {
console.log(e);
});
};
useEffect(() => {
getEmployee(id.id);
}, [id.id]);
//update employee function
const UpdateEmployee = (event) => {
event.preventDefault();
//validation for all the input fields
if (employee.role.length === 0) {
alert("Role required");
return null;
}
if (employee.firstName.length === 0) {
alert("First name is required");
return null;
}
if (employee.lastName.length === 0) {
alert("Last name is required");
return null;
}
if (employee.email.includes("@", 0)) {
} else {
alert("email should contain a @ sign");
return null;
}
if (employee.mobile.length === 10) {
} else {
alert("Mobile Number should contain 10 digits");
return null;
}
if (employee.address.length === 0) {
alert("Last name is required");
return null;
}
empformServices
.update(employee._id, employee)
.then((response) => {
console.log(response.employee);
Swal.fire(
"Update Successfull",
"You have successfully updated the employee",
"success"
);
})
.catch((e) => {
console.log(e);
});
};
const handleInputChange = (e) => {
console.log(e);
const { name, value } = e.target;
setEmployee({
...employee,
[name]: value,
});
};
return (
<Container maxWidth="md">
<Form>
<Container>
<div>
<React.Fragment>
<Card>
<CardContent>
<Typography variant="h6" gutterBottom>
Update Employee
</Typography>
<br />
<br />
<br />
<br />
<Grid container spacing={3}>
<Grid item xs={4}>
<p style={styles.label}>Role</p>
</Grid>
<Grid item xs={5}>
<TextField
name="role"
label="Role"
variant="outlined"
required
fullWidth={true}
value={employee.role}
/>
</Grid>
<Grid item xs={4}>
<p style={styles.label}>First Name</p>
</Grid>
<Grid item xs={5}>
<TextField
name="firstName"
label="First Name"
variant="outlined"
required
fullWidth={true}
onChange={handleInputChange}
value={employee.firstName}
/>
</Grid>
<Grid item xs={4}>
<p style={styles.label}>Last Name</p>
</Grid>
<Grid item xs={5}>
<TextField
name="lastName"
label="Last Name"
variant="outlined"
required
fullWidth={true}
onChange={handleInputChange}
value={employee.lastName}
/>
</Grid>
<Grid item xs={4}>
<p style={styles.label}>Email</p>
</Grid>
<Grid item xs={5}>
<TextField
name="email"
label="Email"
variant="outlined"
required
fullWidth={true}
onChange={handleInputChange}
value={employee.email}
/>
</Grid>
<Grid item xs={4}>
<p style={styles.label}>Mobile</p>
</Grid>
<Grid item xs={5}>
<TextField
type="number"
name="mobile"
label="Mobile"
variant="outlined"
required
fullWidth={true}
InputProps={{ inputProps: { min: 10, max: 10 } }}
onChange={handleInputChange}
value={employee.mobile}
/>
</Grid>
<Grid item xs={4}>
<p style={styles.label}>Address</p>
</Grid>
<Grid item xs={5}>
<TextField
name="address"
label="Adress"
variant="outlined"
required
fullWidth={true}
onChange={handleInputChange}
value={employee.address}
/>
</Grid>
<Grid item xs={12}>
<Button
variant="contained"
color="primary"
style={styles.button}
startIcon={<AutorenewIcon />}
onClick={UpdateEmployee}
>
Update
</Button>
</Grid>
</Grid>
</CardContent>
</Card>
</React.Fragment>
</div>
</Container>
</Form>
</Container>
);
}
const styles = {
button: {
margin: 20,
left: 415,
},
label: {
margin: 30,
},
formControl: {
minWidth: 228,
},
};
export default Updateform;
|
const express = require("express");
const router = express.Router();
const EmployeeModel = require("../../models/Employee.model");
const ServiceModel = require("../../models/Service.model");
router.post("/", async (req, res) => {
try {
const employees = await EmployeeModel.find({});
const services = await ServiceModel.find({});
return res.json({ status: true, message: "تم استرجاع البيانات بنجاح", data: { employees, services } });
} catch (e) {
console.log(`Error in /api/home: ${e.message}`, e);
}
});
module.exports = router; |
export const Fonts = {
LatoBold: "Lato-Bold"
} |
import saltPassword from './saltPassword';
export default saltPassword;
export * from './saltPassword';
|
var class_smart_clone3_d =
[
[ "addOriginalToParent", "class_smart_clone3_d.html#a4dd5f471f954cb73c5d437dca8e8e69d", null ],
[ "AddToParent", "class_smart_clone3_d.html#a1e3e1f9e529e5983bfd3995ef3ead96c", null ],
[ "cloneRotationX", "class_smart_clone3_d.html#ae12a75c503e5b7b2f9c0ed20d4b50881", null ],
[ "cloneRotationY", "class_smart_clone3_d.html#a448dd4b8c88f0a6bc6e7ca97d75e0b9d", null ],
[ "cloneRotationZ", "class_smart_clone3_d.html#a910674401d50bdcf427b977412950270", null ],
[ "cloneScaleX", "class_smart_clone3_d.html#a1025089738ae8cb73b6981e24bc4b7d8", null ],
[ "cloneScaleY", "class_smart_clone3_d.html#ad6311a3c2aeb3dc0705d35a0d994eb34", null ],
[ "cloneScaleZ", "class_smart_clone3_d.html#ab221f63993ff0e945fca4788b52d4efa", null ],
[ "cloneTranslationX", "class_smart_clone3_d.html#af402e4cc65e9ea09b85721afefd45883", null ],
[ "cloneTranslationY", "class_smart_clone3_d.html#acedc3050524d00d823294bbb8c9a37bc", null ],
[ "cloneTranslationZ", "class_smart_clone3_d.html#a033a2b648bccf2a83abb8187d833e146", null ],
[ "incrementalRotation", "class_smart_clone3_d.html#a9a67203d8065e6f53bf7c661219065e9", null ],
[ "incrementalScale", "class_smart_clone3_d.html#adec212e4da6ebfe21a6aaf6556477ffc", null ],
[ "numberOfCopiesX", "class_smart_clone3_d.html#a18470eb9580165c4374ca48604d6fb5e", null ],
[ "numberOfCopiesY", "class_smart_clone3_d.html#a4fa0d599eba1d41fbb13a2bac4555879", null ],
[ "numberOfCopiesZ", "class_smart_clone3_d.html#a98255258a2ddaf81997657dfb2f07bf3", null ],
[ "parentName", "class_smart_clone3_d.html#ab9b7fe38fae95d726e25ed6301188ec4", null ],
[ "uniqueCloneNames", "class_smart_clone3_d.html#a4c7f8673f0a130f63798c3161048f94b", null ]
]; |
import homePage from './pages/home-page.js';
import emailApp from './apps/email/pages/email-app.js';
import keepApp from './apps/keep/pages/keep-app.js';
const routes = [
{
path: '/',
component: homePage,
},
{
path: '/email',
component: emailApp,
},
{
path: '/email/:note',
component: emailApp,
},
{
path: '/keep',
component: keepApp,
},
{
path: '/keep/:mail',
component: keepApp,
},
];
export const router = new VueRouter({ routes });
|
var db = require('./../model/contactsDB.js')
exports.index = function(req, res){
res.render('contact/index', {
title: 'Contacts',
contacts:db.getContacts()});
};
exports.create = function(req, res) {
res.render('contact/create', {title: 'New Contact'});
};
exports.createPost = function(req, res) {
db.newContact({
name: req.body.name,
type: req.body.type,
number: req.body.number
});
res.redirect('/contact')
} |
// 1. Cree un programa que tome el valor de un productro y le sume su IVA //
let a=parseFloat(prompt("ingrese valor producto"));
function Precio_final(a,b=0.19) {
let precio_final_producto=(a*b)+a;
return precio_final_producto;
}
let p_final=Precio_final(a); // no se le puede poner la variabvle de iva,pero si podemos anexar valora a par acmbiar valor de iva y no toamr el por defecto //
console.log(p_final);
//----------Alternativa------------// dandeo valor a b de 0.50 de esta manera saltando el valor predeterminado asignado //
// let p_final=Precio_final(a,0.50);
// console.log(p_final);
|
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
*
* (c) Copyright 2009-2014 SAP SE. All rights reserved
*/
sap.ui.define(['./library','./Item'],function(){"use strict";sap.ui.core.Item.extend("sap.ui.core.SeparatorItem",{metadata:{library:"sap.ui.core"}});return sap.ui.core.SeparatorItem},true);
|
/*
* Copyright © 2016 Magestore. All rights reserved.
* See COPYING.txt for license details.
*
*/
define(
[
'jquery',
'ko',
'Magestore_Webpos/js/view/base/grid/renderer/abstract',
],
function ($, ko, renderAbstract) {
"use strict";
return renderAbstract.extend({
render: function (item) {
var posPayments = [
'cashforpos',
'codforpos',
'ccforpos',
'cp1forpos',
'cp2forpos'
];
var code = item.code;
if(item.type === '1'){
code = 'ccforpos';
}else{
if($.inArray(item.code, posPayments) < 0){
code = 'cp1forpos';
}
}
if(item.code === 'mercuryhosted'){
return item.icon_class?item.icon_class:'icon-iconPOS-payment-vantiv';
}
return 'icon-iconPOS-payment-' + code;
}
});
}
); |
load('application');
action('404', function () {
send(404);
}); |
define([
'apps/system3/office/office',
'apps/system3/office/car/car.service'], function (app) {
app.module.controller("office.controller.car", function ($scope, $sce, $state, $stateParams, $uibModal, $timeout, carService) {
// 所有的车辆
$scope.allCars = undefined;
// 申请的车辆
$scope.applyCars = undefined;
$scope.currentStateName = $state.current.name;
$scope.$watch("currentCar", function (newval, oldval) {
if (newval) {
$scope.viewScroll.init();
}
});
// 显示正常可用的车辆
$scope.showNormalCar = function () {
$scope.showAllCar(true)
}
// 显示所有车辆
$scope.showAllCar = function (isNormal) {
$scope.normal = isNormal == true;
if ($scope.allCars == undefined) {
carService.getCarList().then(function (result) {
$scope.allCars = result.Source;
$scope.carList = result.Source;
if ($stateParams.id > 0) {
angular.forEach(result.Source, function (n) {
if (n.ID == $stateParams.id) {
$scope.setcurrentCar(n);
}
});
}
});
} else {
$scope.carList = $scope.allCars;
}
}
// 显示我申请的车辆
$scope.showMyApplyCar = function () {
$scope.normal = false;
if ($scope.applyCars == undefined) {
carService.getUsedCar().then(function (result) {
$scope.applyCars = result;
$scope.carList = result;
if ($stateParams.id > 0) {
angular.forEach($scope.carList, function (n) {
if (n.ID == $stateParams.id) {
$scope.setcurrentCar(n);
}
});
}
});
} else {
$scope.carList = $scope.applyCars;
}
}
$scope.setCurrentCar = function (car) {
$scope.currentCar = car;
$scope.currentCar.HtmlContent = $sce.trustAsHtml($scope.currentCar.Content);
$scope.viewScroll.init();
}
$scope.addCar = function (n) {
$scope.allCars.push(n);
}
$scope.removeCar = function (n) {
$scope.allCars.removeObj(n);
}
$scope.afterApply = function () {
$scope.currentCar.Status = 5;
console.log($scope.currentCar)
}
});
});
|
const express = require('express');
const axios = require('axios');
const Yelp = require('node-yelp-api-v3');
const keys = require('../env/token.js')
const mongoose = require('mongoose');
const Profile = require('../db/models.js')
const router = express.Router();
const yelp = new Yelp({
consumer_key: keys.consumerKey,
consumer_secret: keys.consumerSecret,
})
router.post('/search', (req, res) => {
yelp.searchBusiness({ term: 'tortas', location: 'los angeles' })
.then(results => {
console.log('Recieved Search post!!')
res.status(201).send(results);
})
.catch(err => {
res.send(err);
})
});
router.get('/favorites', (req, res) => {
console.log('Recieved GET for favorites!!');
Profile.find()
.then(results => {
res.status(200).send(results);
})
})
router.post('/favorites', (req, res) => {
console.log(req.body);
//TODO: check if favorite exists in DB before adding
let newProfile = new Profile(req.body)
newProfile.save((err, newProfile) => {
if (err) return console.error(err);
console.log('successfully saved new favorite!')
});
})
module.exports = router;
// {
// search(term: "torta",
// location: "los angeles") {
// total
// business {
// name
// rating
// review_count
// location {
// address1
// city
// state
// country
// }
// }
// }
// }
|
yum.define([
PI.Url.create('UI.RichText', '/richtext.html'),
PI.Url.create('UI.RichText', '/richtext.css'),
PI.Url.create('UI.RichText', '/ckeditor.js'),
PI.Url.create('UI.RichText', '/pt-br.js'),
PI.Url.create('UI.RichText', '/styles.js'),
PI.Url.create('UI.RichText', '/config.js'),
PI.Url.create('UI.RichText', '/skins/office2013/editor.css'),
PI.Url.create('UI.RichText', '/jquery.js')
], function(html){
/**
* @class Ui.RichText
*/
Class('UI.RichText').Extend(Mvc.Component).Body({
instances: function(){
this.view = new Mvc.View(html);
this.id = PI.Util.UUID();
},
viewDidLoad: function(){
var self = this;
this.view.editor.ckeditor();
this.base.viewDidLoad();
},
/**
* Seta o conteudo o rich text
*
* @method set
* @param {string} text
* @return {this}
*/
set: function(text){
CKEDITOR.instances[ this.id ].setData( text );
return this;
},
/**
* Retorna o conteudo em HTML do rich text
*
* @method get
* @return {string}
*/
get: function(){
return CKEDITOR.instances[ this.id ].getData();
}
});
}); |
define('/static/script/lib/array/arrDelete', [], function(require, exports, module) {
function arrDelete()
{
Array.prototype.deletes=function(vArg)
{
var num=this.length;
var _str=" "+vArg+" ";
for (var i=0;i<num;i++)
{
if(" "+this[i]+" "===_str)
{
this.splice(i,1);
}
}
};
}
return arrDelete();
}); |
const parseQstring = require('../lib/parseQstring');
let qs = 'at>=123456<=789,at>123456789,tid==00895485acb,tid>=null,at<233456789,hid~=\A01**1223++300\\03+++,at!=200,hid!=B01122330003,pid==,cid!=00,ppd>,value==138,,mail==abc_1554+da==ddkl@163.com';
// let qs = ',tid==,tid>=,at>15,,tid<=,tid~=5,';
// let qs = 'td==Undefined';
// let qs ='module==,type==,created>=,created<=';
let tt = parseQstring(qs);
console.log(JSON.stringify(tt)); |
import React, {Component} from 'react';
import {StyleSheet, View, ActivityIndicator, FlatList, RefreshControl, Text} from 'react-native';
import { NavigationEvents } from 'react-navigation';
import { FloatingAction } from 'react-native-floating-action';
import {CommonCell, AppPopup} from '../UIKit';
import {addTask, loadTasks} from '../../Networking';
import routes from '../../Constants/routes';
import Icon from 'react-native-vector-icons/Ionicons';
class TasksScreen extends Component {
constructor(props) {
super(props);
this.state = {
tasks: [],
loading: true,
isDialogVisible: false,
duration: '',
};
}
componentDidMount() {
this._loadTasks();
}
_loadTasks = () => {
const {project} = this.props.navigation.state?.params;
loadTasks(project.id, (error, response) => {
if (error) {
this.setState({loading: false});
alert(error);
} else {
this.setState({tasks: response.tasks, isAdmin: response.isAdmin, loading: false});
}
});
};
_addTask = () => {
const {project} = this.props.navigation.state?.params;
const {title, description, duration} = this.state;
if ((!title || !title.trim()) || (!duration || !duration.trim())) {
alert('Заполните название и продолжительность задачи!');
return;
}
const task = {
Title: title,
Description: description,
Duration: parseInt(duration, 10),
StateId: 1,
ProjectId: parseInt(project.id, 10),
CreatedDate: new Date(),
};
addTask({worktask: task}, (error, response) => {
if (error) {
alert(error);
} else {
this._loadTasks();
this.setState((prevState) => {
return {
tasks: [...prevState.tasks, task],
isDialogVisible: false,
title: '',
description: '',
duration: '',
};
});
}
});
};
_renderItem = ({item}) => {
return (
<CommonCell
key={item.id}
{...item}
onPress={() => this.props.navigation.navigate(routes.TaskDetailsStack, {task: item})}
/>
);
};
render() {
const {loading, isDialogVisible} = this.state;
if (loading) {
return (
<View style={styles.loadingIndicator}>
<ActivityIndicator size="large" color="#03bafc" />
</View>
);
}
return (
<View style={{flex: 1}}>
<NavigationEvents
onWillFocus={() => {
this._loadTasks();
}}
/>
<FlatList
style={styles.container}
contentContainerStyle={styles.contentContainer}
data={this.state.tasks}
keyExtractor={(item, index) => index.toString()}
renderItem={this._renderItem}
refreshControl={<RefreshControl refreshing={loading} onRefresh={this._loadTasks} />}
/>
<AppPopup
isDialogVisible={isDialogVisible}
title="Добавить задачу"
hintInput="Никнейм"
firstHintInput="Название"
secondHintInput="Описание"
thirdHintInput="Длительность"
submit={(inputText) => { this._addTask(inputText); }}
closeDialog={() => { this.setState({isDialogVisible: false}); }}
onChangeFirstText={(title) => this.setState({title})}
onChangeSecondText={(description) => this.setState({description})}
onChangeThirdText={(duration) => this.setState({duration})}
duration={this.state.duration}
/>
<FloatingAction
color="#03bafc"
floatingIcon={<Icon name="ios-add" size={35} color="#FFF" />}
onPressMain={() => {
this.setState({isDialogVisible: true});
}}
showBackground={false}
/>
</View>
);
}
}
const styles = StyleSheet.create({
contentContainer: {
marginTop: 10,
},
container: {
flex: 1,
},
navigationBar: {
width: '100%',
},
scene: {
flex: 1,
},
loadingIndicator: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
title: {
marginLeft: 20,
fontSize: 17,
letterSpacing: 0.15,
color: '#FFF',
},
menuIcon: {
},
addIcon: {
paddingHorizontal: 16,
},
flexSpacing: {
flex: 1,
},
});
export default TasksScreen;
|
import styled from 'styled-components';
export const SocialCollection = styled.div`
margin: 0 auto;
width: 88%;
height: 30%;
display: flex;
justify-content: space-around;
position: relative;
`;
|
WMS.module('Suppliers.List', function(List, WMS, Backbone, Marionette, $, _) {
var Views = List.Views;
List.Controller = Marionette.Controller.extend({
prefetchOptions: [
{ request: 'get:supplier:list', name: 'suppliers' }
],
regions: [{
name: "titleRegion",
View: Views.Title,
options: {
title: "Fornitori"
}
}, {
name: 'panelRegion',
viewName: '_panel',
View: List.Views.Panel,
options: {
criterion: "@criterion"
},
events: {
'suppliers:new' : 'newSupplier',
'suppliers:filter' : 'filterSupplier'
}
}, {
name: 'listRegion',
viewName: '_suppliers',
View: List.Views.Suppliers,
options: {
collection: "@suppliers",
criterion: "@criterion"
},
events: {
'supplier:selected' : 'selectSupplier'
}
}],
initialize: function() {
var self = this;
this.listenTo(WMS.vent, "supplier:created", function(supplier) {
self.options.suppliers.add(supplier);
});
this.listenTo(WMS.vent, "supplier:updated", function(supplier) {
var model = self.options.suppliers.find({id: supplier.get('id')});
if (model) {
model.set(supplier.attributes);
}
});
},
listSuppliers: function(criterion) {
this.options.criterion = criterion;
var self = this;
this.start().then(function() {
if (self._layout && !self._layout.isDestroyed) {
self.setupRegions(self._layout);
} else {
self._layout = new Views.FilterLayout();
self._layout.on('show', function() {
self.setupRegions(self._layout);
});
WMS.mainRegion.show(self._layout);
}
});
},
filterSupplier: function(criterion) {
WMS.trigger("suppliers:filter", criterion);
},
newSupplier: function() {
var klass = WMS.Models.Supplier;
if (klass.canCreate()) {
var supplier = new klass()
, view = new Views.New({ model: supplier });
WMS.showModal(view);
} else {
WMS.showError('Operazione non consentita!');
}
},
selectSupplier: function(childView) {
var supplier = childView.model;
if (supplier.canRead()) {
WMS.trigger("suppliers:show", supplier.get("id"));
}
}
});
}); |
const path = require('path');
const fs = require('fs');
const {
addProductInfo,
addVariantForProduct,
addCampaignInfo,
allProductsId,
allCampaignProductsId,
} = require('../Model/admin');
const { clearMarketingCampaignsCache } = require('../Model/v1/marketing');
const { ProductModel } = require('../responseModel/product');
// 新增商品
const addNewProduct = async (req, res) => {
const title = req.body.product_title;
const description = req.body.product_description;
const price = req.body.product_price;
const texture = req.body.product_texture;
const wash = req.body.product_wash;
const place = req.body.product_place;
const note = req.body.product_note;
const story = req.body.product_story;
const mainImageUrl = `https://practicestylish.s3.us-east-2.amazonaws.com/${req.files.product_main_image[0].key}`;
const subfiles = req.files.product_sub_images;
const subImageUrlList = [];
for (let index = 0; index < subfiles.length; index++) {
const eachSubFilePath = `https://practicestylish.s3.us-east-2.amazonaws.com/${subfiles[index].key}`;
subImageUrlList.push(eachSubFilePath);
}
// 因為到時DB存的是TEXT,所以下面把array轉成string
// const subImageUrlListStr = JSON.stringify(subImageUrlList);
// 沒有要上傳活動檔次,而且這邊的設計目前是有問題的
// const hotId = req.body.hot_id;
const category = req.body.product_category;
const keyword = req.body.product_keyword;
const newProductDataModel = new ProductModel(
title,
description,
price,
texture,
wash,
place,
note,
story,
mainImageUrl,
subImageUrlList,
category,
keyword,
);
// 寫入到DB
try {
const addProductsResult = await addProductInfo(newProductDataModel);
if (addProductsResult.length > 0) {
res.send('商品資料上傳成功');
}
} catch (error) {
res.send('請確認新增的商品熱銷活動編號正確以及該活動存在');
}
};
const uploadVariantForProduct = async (req, res) => {
const { product_id: productId } = req.body;
const colorCode = req.body.regular_color_code;
const colorName = req.body.regular_color_name;
const size = req.body.regular_size;
const stock = req.body.regular_stock;
// 寫入規格到DB
try {
const addVariantResult = await addVariantForProduct(productId,
colorCode,
colorName,
size,
stock);
if (addVariantResult.affectedRows > 0) {
res.send('新增規格成功');
}
} catch (error) {
res.send('請確認新增的商品編號是存在的');
}
};
const uploadCampaign = async (req, res) => {
const productId = parseInt(req.body.product_id, 10) || 0;
const picturePath = req.files.campaign_picture[0].path;
const { story } = req.body;
const allProductsIdResult = await allProductsId();
const productIdList = [];
allProductsIdResult.forEach((productIdObj) => {
productIdList.push(productIdObj.id);
});
if (!productIdList.includes(productId)) {
// 雖然不會插入到資料庫中,但還是會因為multer而存到資料夾,所以要刪除
// 因為移到 s3 上面去了,所以下面可以助解掉
// const rootPath = path.join(__dirname, '../');
// const imagePath = path.join(rootPath, `${picturePath}`);
// fs.unlink(imagePath, (err) => {
// if (err) {
// console.log('刪除失敗');
// } else {
// console.log('刪除成功');
// }
// });
res.send('請確認新增的商品編號是存在的');
return;
}
try {
const allCampaignProductsIdList = await allCampaignProductsId();
const campaignProductsIdList = [];
allCampaignProductsIdList.forEach((campaign) => {
campaignProductsIdList.push(campaign.productId);
});
const addCampaingResult = await addCampaignInfo(productId, picturePath, story);
if (addCampaingResult.affectedRows > 0) {
// 因為有新增成功,所以對應的 redis cache要移除
clearMarketingCampaignsCache();
res.send('新增活動成功');
}
} catch (error) {
throw error;
}
};
module.exports = {
addNewProduct,
uploadVariantForProduct,
uploadCampaign,
};
|
import axios from "axios";
const API_URL = "https://api.themoviedb.org/3/";
const API_KEY = "b5fe6f43e3714159d2209d0fe8c3a695";
const header = {
headers: new Headers({
Authorization:
"Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJiNWZlNmY0M2UzNzE0MTU5ZDIyMDlkMGZlOGMzYTY5NSIsInN1YiI6IjU5MGIwOTc5OTI1MTQxNGZhODAxMzE2MyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.ldVdrLz-iWpzmEgMvf_7IwT9pdfh14Pdqr_r2TGuMzg",
"Content-Type": "application/json;charset=utf-8"
})
};
const headers = {
Authorization:
"Bearer AAAAAAAAAAAAAAAAAAAAABWwAwEAAAAAwpR5bj91XGI6HnNczREqg4isd5M%3DEZON7bu5E3dsGhDowTuta7itBPCwS2gpe0r5hHpZyiLJTluu6t",
"Content-Type": "application/json;charset=utf-8"
};
export const searchMovies = search => async dispatch => {
if (search === "") {
// dispatch notification to notify no content
notifyDispatch(`Please provide a search query`, "bg-red-500", dispatch);
return;
}
// dispatch notification to search
notifyDispatch("Loading, Please Wait ...", "bg-teal-500", dispatch);
const url = `${API_URL}search/movie?api_key=${API_KEY}&query=${search}`;
const response = await axios.get(url, header);
dispatch({
type: "SEARCH_MOVIES",
payload: response.data
});
if (response.data.results.length < 1) {
// dispatch notification to notify no content
notifyDispatch(`No Movie with keyword ${search}`, "bg-red-500", dispatch);
} else {
// dispatch notification to notify success
notifyDispatch("Movies Fetched", "bg-green-500", dispatch);
}
};
export const fetchMovies = () => async dispatch => {
// dispatch notification to search
notifyDispatch("Loading, Please Wait ...", "bg-teal-500", dispatch);
// fetch movie
const year = new Date().getFullYear();
const url = `${API_URL}discover/movie?api_key=${API_KEY}?sort_by=popularity.desc&year=${year}`;
await axios.get(url, header).then(
res => {
dispatch({
type: "FETCH_MOVIES",
payload: res.data
});
},
err => {
notifyDispatch(
err.message + ". Please enter a key word to search",
"bg-red-500",
dispatch
);
}
);
};
const notifyDispatch = (message, style, dispatch) => {
const note = { message, style };
dispatch({
type: "NOTIFICATTION_STATUS",
payload: note
});
};
export const fetchTweets = data => async dispatch => {
// dispatch notification to search
notifyDispatch("Loading, Please Wait ...", "bg-teal-500", dispatch);
data.startDate.replace(/-/g, "")
data.startDate = data.startDate.replace('T','');
data.startDate = data.startDate.replace(':','');
data.endDate = data.endDate.replace('T','');
data.endDate = data.endDate.replace(':','');
const dto = {
fromDate: `${data.startDate.replace(/-/g, "")}`,
toDate: `${data.endDate.replace(/-/g, "")}`,
query: `from:${data.username} lang:en`,
maxResults: "100"
};
// fetch tweets
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://api.twitter.com/1.1/tweets/search/fullarchive/Dev.json";
await axios.post(proxyurl + url, dto, { headers }).then(
res => {
dispatch({
type: "FETCH_TWEETS",
payload: res.data
});
notifyDispatch(
"Tweet Fetched.",
"bg-green-500",
dispatch
);
},
err => {
notifyDispatch(
err.message ,
"bg-red-500",
dispatch
);
}
);
// const data = {
// created_at: "Wed Aug 28 22:32:24 +0000 2019",
// id: 1166840987081170944,
// id_str: "1166840987081170944",
// text: "DOCTOR is trending tonight, the VN version sha courtesy @_T_babyy",
// source:
// '<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>',
// user: {
// id: 1032309123025719297,
// name: "Bundayy Olayinka",
// screen_name: "BundayyO",
// location: "Lagos, Nigeria",
// followers_count: 2564,
// friends_count: 2915,
// listed_count: 3,
// favourites_count: 18428,
// statuses_count: 41027,
// profile_image_url:
// "http://pbs.twimg.com/profile_images/1213511879047417859/smzgMKt3_normal.jpg",
// profile_image_url_https:
// "https://pbs.twimg.com/profile_images/1213511879047417859/smzgMKt3_normal.jpg",
// profile_banner_url:
// "https://pbs.twimg.com/profile_banners/1032309123025719297/1570536968"
// },
// quote_count: 0,
// reply_count: 1,
// retweet_count: 0,
// favorite_count: 2,
// entities: {
// hashtags: [],
// urls: [],
// user_mentions: [
// {
// screen_name: "_T_babyy",
// name: "blackkie 🌚",
// id: 1102117924641353728,
// id_str: "1102117924641353728",
// indices: [56, 65]
// }
// ],
// symbols: []
// },
// favorited: false,
// retweeted: false,
// filter_level: "low",
// lang: "en",
// matching_rules: [
// {
// tag: null
// }
// ]
// };
// dispatch({
// type: "FETCH_TWEETS",
// payload: data
// });
};
export const fetchTrends = () => async dispatch => {
// dispatch notification to fetch trends
notifyDispatch("Loading, Please Wait ...", "bg-teal-500", dispatch);
// fetch trends
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://api.twitter.com/1.1/trends/place.json?id=23424908";
await axios.get(proxyurl + url, { headers }).then(
res => {
console.log(res);
dispatch({
type: "FETCH_TRENDS",
payload: res.data
});
notifyDispatch(
"Tweet Fetched.",
"bg-green-500",
dispatch
);
},
err => {
notifyDispatch(
err.message,
"bg-red-500",
dispatch
);
}
);
};
export const notifyPortals = (message, style) => async dispatch => {
notifyDispatch(message, style, dispatch);
};
|
/**
* GET 404 page.
*
* Author: hustcer
* Date: 2012-2-13
*/
// 取得课程值以及对应的中文描述映射信息
var cList = require("../database/course.js").cCoursesList;
var nodeMsg = require("../conf/nodemsg.node.js").nodeMessages;
var getCollection = require("./util.node.js").getCollection;
var sendMail = require("./mail.node.js").sendMail;
exports.man = function(req, res, nlolext){
var col = getCollection(req);
res.render('admin', {
title : '管理员后台',
courseList : cList[col.cCourse.courseType + 'List'],
cCourse : col.cCourse
});
};
/*
* 设置会员为某课程缴费. eg:http://localhost:3000/man/pay/latin/29411?courseVal=13CB
* 注意只有课程状态为 approved 的,即报名通过的用户才可以设置其状态为缴费
*/
exports.pay = function(req, res){
var col = getCollection(req);
console.log("[INFO]----Set paid for user with ID: "+ req.params.id + " courseVal: " + req.query.courseVal)
checkCourseStatus(req, res, 'approved', function(){
col.updateDancerPayStatus(req.params.id, req.query.courseVal, true, function(err, result) {
if (err) throw err;
res.contentType('application/json');
res.send({success:true});
});
});
};
/*
* 设置会员未为某课程缴费. eg:http://localhost:3000/man/unpay/latin/29411?courseVal=13CB
* 注意只有课程状态为 quitApplied、quit 的,即申请过退课的用户才可以退费
*/
exports.unpay = function(req, res){
var col = getCollection(req);
console.log("[INFO]----Set unpaid for user with ID: "+ req.params.id + " courseVal: " + req.query.courseVal)
checkCourseStatus(req, res, 'quitApplied', function(){
col.updateDancerPayStatus(req.params.id, req.query.courseVal, false, function(err, result) {
if (err) throw err;
res.contentType('application/json');
res.send({success:true});
});
});
};
/*
* 设置会员报名成功. eg:http://localhost:3000/man/approve/latin/29411?courseVal=13CB
* 注意只有课程状态为 waiting 的才可以报名审核通过
*/
exports.approve = function(req, res){
var col = getCollection(req);
console.log("[INFO]----Approve course with ID: "+ req.params.id + " courseVal: " + req.query.courseVal)
checkCourseStatus(req, res, 'waiting', function(){
col.updateDancerCourseStatus(req.params.id, req.query.courseVal, 'approved', function(err, result) {
if (err) throw err;
col.findDancerEmailByID(req.params.id, function(err, dancer){
if (err) throw err;
sendMail(dancer.email, '您的报名申请已审核通过', col.cCourse.successMsg + '课程代码:' + req.query.courseVal);
});
res.contentType('application/json');
res.send({success:true});
});
});
};
/*
* 设置会员报名不通过. eg:http://localhost:3000/man/refuse/latin/29411?courseVal=13CB
* 注意只有课程状态为 waiting 的才可以报名审核不通过
*/
exports.refuse = function(req, res){
var col = getCollection(req);
console.log("[INFO]----Refuse course with ID: "+ req.params.id + " courseVal: " + req.query.courseVal)
checkCourseStatus(req, res, 'waiting', function(){
col.updateDancerCourseStatus(req.params.id, req.query.courseVal, 'refused', function(err, result) {
if (err) throw err;
res.contentType('application/json');
res.send({success:true});
});
});
};
/*
* 设置会员退课成功. eg:http://localhost:3000/man/quit/latin/29411?courseVal=13CB
* 注意只有课程状态为 quitApplied 且已经退费,或者未缴费时,发出过退课申请的用户才可以退课成功
*/
exports.quit = function(req, res){
var col = getCollection(req);
console.log("[INFO]----Quit course with dancerID: "+ req.params.id + " courseVal: " + req.query.courseVal)
checkCourseStatus(req, res, 'quitApplied', function(){
checkPayStatus(req, res, false, function(){
col.updateDancerCourseStatus(req.params.id, req.query.courseVal, 'quit', function(err, result) {
if (err) throw err;
col.findDancerEmailByID(req.params.id, function(err, dancer){
if (err) throw err;
sendMail(dancer.email, '您的退课申请已审核通过', col.cCourse.quitMsg + '课程代码:' + req.query.courseVal);
});
res.contentType('application/json');
res.send({success:true});
});
});
});
};
/*
* 设置拒绝会员退课. eg:http://localhost:3000/man/quitRefuse/latin/29411?courseVal=13CB
* 注意只有课程状态为 quitApplied 时,发出过退课申请的用户才可以拒绝退课
*/
exports.quitRefuse = function(req, res){
var col = getCollection(req);
console.log("[INFO]----Refuse quiting with dancerID: "+ req.params.id + " courseVal: " + req.query.courseVal)
checkCourseStatus(req, res, 'quitApplied', function(){
col.updateDancerCourseStatus(req.params.id, req.query.courseVal, 'approved', function(err, result) {
if (err) throw err;
res.contentType('application/json');
res.send({success:true});
});
});
};
/*
* 管理员修改保存会员信息. eg:http://localhost:3000/man/editDancer/latin
*
*/
exports.editDancer = function(req, res){
var col = getCollection(req);
var dancerModel = {
dancerID : req.body.dancerID,
dancerName : req.body.dancerName,
gender : req.body.gender,
email : req.body.email,
wangWang : req.body.wangWang,
extNumber : req.body.extNumber,
alipayID : req.body.alipayID,
vip : req.body.vip,
level : req.body.level,
forever : req.body.forever,
department : req.body.department
};
col.findDancerByID( dancerModel.dancerID, function(err, result) {
if (err) throw err;
// 之所以要把新插入会员和更新会员信息分开处理而不采用upsert模式,
// 一方面是要设置会员创建时间,另一方面是为了明确操作逻辑,避免意外
// 会员存在则更新会员信息
if (!!result) {
col.updateDancerByAdmin(dancerModel.dancerID, dancerModel, function(err) {
if (err) throw err;
// 表单提交成功后返回首页, 没有错误消息就是好消息
res.send();
// res.redirect('back');
// res.send({success:true, msg:'Dancer Information Updated Successfully!'});
});
}
});
};
/*
* 这里的查询条件还要加上对应的课程,否则result.courses.status 未定义
* 检查会员课程状态
* @param req.query.courseVal query字符串中要有course的值
* @param status 期望的状态
* @param callback 满足期望状态后执行的回调
*/
var checkCourseStatus = function(req, res, status, callback){
var col = getCollection(req);
col.findDancerByID(req.params.id, function(err, result){
if (err) throw err;
var satisfied = false;
// 会员不存在或者没有报名任何课程
if (!(!!result && !!result.courses && result.courses.length > 0)){
res.send({success:false, msg:nodeMsg.notExist});
// 如果不return后面for block会继续被执行
return;
}
for (var i = result.courses.length - 1; i >= 0; i--) {
if (result.courses[i].courseVal === req.query.courseVal &&
result.courses[i].status === status) {
satisfied = true;
// console.log("[INFO]----Course Status Satisfied With Status: " + status, ',For Dancer With ID:', req.params.id);
callback();
break;
};
};
if (!satisfied) {
res.send({success:false, msg:nodeMsg.condUnMeet});
};
});
};
/*
* 这里的查询条件还要加上对应的课程,否则result.courses.isPaid 未定义
* 检查会员缴费状态
* @param req.query.courseVal query字符串中要有course的值
* @param isPaid 期望的缴费状态
* @param callback 满足期望状态后执行的回调
*/
var checkPayStatus = function(req, res, isPaid, callback){
var col = getCollection(req);
col.findDancerByID(req.params.id, function(err, result){
if (err) throw err;
var satisfied = false;
// 会员不存在或者没有报名任何课程
if (!(!!result && result.courses && result.courses.length > 0)){
res.send({success:false, msg:nodeMsg.notExist});
// 如果不return后面for block会继续被执行
return;
}
for (var i = result.courses.length - 1; i >= 0; i--) {
if (result.courses[i].courseVal === req.query.courseVal &&
result.courses[i].paid === isPaid) {
satisfied = true;
// console.log("[INFO]----Pay Status Satisfied With Status: " + isPaid, ', For Dancer With ID:', req.params.id);
callback();
break;
};
};
if (!satisfied) {
res.send({success:false, msg:nodeMsg.payUnMeet});
};
});
};
|
var app = angular.module("userApp", ["ngRoute"]);
//Configure routes
app.config(function($routeProvider) {
$routeProvider
.when("/users", {
templateUrl: "templates/user-list.html",
controller: "UsersController",
controllerAs: "usersCtrl"
})
.when("/users/:id/edit", {
templateUrl: "templates/edit-user.html",
controller: "EditUserController",
controllerAs: "editUserCtrl"
})
.otherwise({
redirectTo: "/users"
});
});
app.controller("UsersController", function($http) {
//Step 1: Make HTTP request to Rails API to retrieve list of users (Hint: look up the $http service)
//Step 2: Use Angular's template syntax to display the users
var vm = this;
$http({
method: "GET",
url: "http://localhost:3000/users"
}).success(function(users) {
vm.users = users;
}).error(function() {
alert("Error getting users!");
});
vm.submitUser = function(event) {
event.preventDefault();
$http({
method: "POST",
url: "http://localhost:3000/users",
data: {
user: vm.user
}
}).success(function(newUser) {
vm.users.push(newUser);
vm.user = {};
$("#add-user-modal").modal("hide");
}).error(function() {
alert("Error saving user");
});
}
});
app.controller("EditUserController", function($http, $location, $routeParams) {
var vm = this;
//Pull specific user and insert into edit form
$http({
method: "GET",
url: "http://localhost:3000/users/" + $routeParams.id + "/edit"
}).success(function(user) {
vm.user = user;
}).error(function() {
alert("Error getting specific user");
});
//Capture submit event, prevent default, and update user server-side
vm.submitEdits = function(event) {
event.preventDefault();
$http({
method: "PUT",
url: "http://localhost:3000/users/" + $routeParams.id,
data: {
user: vm.user
}
}).success(function() {
$location.path("/users");
}).error(function() {
alert("Error updating user");
});
}
});
|
import '@/sula/umi';
import '@/sula/render-plugin';
|
// Read cookie when page loads
window.addEventListener('load', function() {
read_cookie();
});
// Set the number and phrase.
function read_cookie(){
let rval = CookieUtil.get("cookie_count");
rval = parseInt(rval)
if (rval) {
document.getElementById("count").innerHTML = rval;
set_phrase(rval-1);
set_cookie(rval+1);
}
else {
document.getElementById("count").innerHTML = 1;
set_cookie(2);
set_phrase(0);
}
}
// Increase the visit count and then refresh page
function increase_count() {
let rval = parseInt(document.getElementById("count").innerHTML);
set_cookie(rval+1);
window.location.reload();
}
// Set the cookie in the browser
function set_cookie(number){
CookieUtil.set("cookie_count", number);
}
// Delete the cookie in the browser
function delete_cookie(){
CookieUtil.unset("cookie_count");
window.location.reload();
}
// Set phrase depending on the visit number.
function set_phrase(number){
let myArray = ['Welcome to my page!', 'I see you came back!', 'Oh, it\'s you again!', 'You must be curious!', 'This is your 5th time!', 'This is your 6th time!', 'This is you 7th time!', 'This is your 8th time!', 'This is your 9th time!', 'This is your 10th time!'];
number = number%10;
document.getElementById("phrase").innerHTML = myArray[number];
} |
import React from 'react';
import { Link } from 'react-router-dom';
import Panel from 'component/panel/index.jsx';
import TableList from 'component/table-list/index.jsx';
import FileUploader from 'component/file-uploader/index.jsx';
import BaseUtil from 'util/base-util.jsx';
import Competition from 'service/competition-service.jsx';
const _baseUtil = new BaseUtil();
const _competition = new Competition();
class CompetitionFileScore extends React.Component{
constructor(props){
super(props);
this.state = {
id: this.props.match.params.id || '',
status: this.props.match.params.status || '',
list: [],
scoreJson: {}
}
}
componentDidMount(){
this.loadData();
}
loadData(){
_competition.getFileList(this.state.id)
.then(res=>{
this.setState({
total: res.totalCount,
list: res.list || []
});
},errMsg=>{
this.setState({
list: []
});
_baseUtil.errorTips(errMsg);
});
}
onValueChange(e){
let name = e.target.name,
value = e.target.value;
this.setState({
[name]: value
});
}
onScoreChange(e, fileId){
let name = e.target.name,
value = e.target.value;
if(isNaN(value)){
_baseUtil.errorTips('请输入数字');
return;
}
let scoreJson = this.state.scoreJson;
scoreJson[fileId] = value;
this.setState({
scoreJson: scoreJson
});
}
onScore(fileId){
let score = this.state.scoreJson[fileId];
if(!score || score === ""){
_baseUtil.errorTips('请输入评分');
return;
}
if(score > 100){
_baseUtil.errorTips('满分为100分');
return;
}
_competition.giveFileScore(fileId, score)
.then(res=>{
_baseUtil.successTips(res);
this.loadData();
},errMsg=>{
_baseUtil.errorTips(errMsg);
});
}
getFilename(fileUrl){
fileUrl = fileUrl.split('/');
let len = fileUrl.length;
return fileUrl[len-1];
}
render(){
let stageList = ['前期宣传', '报名', '预赛', '周赛', '月赛', '中间赛', '复赛', '决赛', '结束'];
let tableHeads = ['文件名(点击下载)', '分数(满分为100分)', '操作'];
let listBody = this.state.list.map((file,index)=>{
return (
<tr key={index}>
<td>
<a href={`http://static.chuangyh.com/${file.url}`}>
{this.getFilename(file.url)}
</a>
</td>
<td>{file.score === '' ? '未评分' : file.score}</td>
<td>
<div className="col-md-3">
<input type="text" name="score" placeholder="请输入分数" className="input-smh"
onChange={(e)=>{this.onScoreChange(e, file.file_id)}}/>
</div>
<a onClick={(e) => {this.onScore(file.file_id)}} className="btn btn-xs btn-primary mr-5">确定</a>
</td>
</tr>
);
});
return (
<Panel title="竞赛打分">
<div className="col-md-12">
<div className="panel panel-info">
<div className="panel-heading">
<h3 className="panel-title">{`当前阶段 - ${stageList[this.state.status]}`}</h3>
</div>
</div>
</div>
<TableList tableHeads={tableHeads}>
{listBody}
</TableList>
</Panel>
);
}
}
export default CompetitionFileScore;
|
// Gulp 4 Common JS
// Author: Funnydino. funnydino1@gmail.com
// Шрифты должны быть в виде: *FontFamily-FontWeightFontStyle.ttf*
const {
src,
dest,
parallel,
series,
watch
} = require('gulp');
const fs = require('fs');
const del = require('del');
const browserSync = require('browser-sync').create();
const notify = require('gulp-notify');
const sass = require('gulp-sass')(require('sass'));
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const cleanCSS = require('gulp-clean-css');
const fileInclude = require('gulp-file-include');
const htmlMin = require('gulp-htmlmin');
const image = require('gulp-image');
const rename = require('gulp-rename');
const rev = require('gulp-rev');
const revdel = require('gulp-rev-delete-original');
const revRewrite = require('gulp-rev-rewrite');
const svgSprite = require('gulp-svg-sprite');
const ttf2woff2 = require('gulp-ttf2woff2');
const uglify = require('gulp-uglify-es').default;
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
// Production version:
// Fonts:
const fonts = () => {
return src('./src/fonts/**.ttf')
.pipe(ttf2woff2())
.pipe(dest('./app/fonts/'))
};
const fontWeightCalc = (str) => {
let weight;
switch (true) {
case /thin/.test(str) || /hairline/.test(str):
weight = 100;
break;
case /extralight/.test(str) || /ultralight/.test(str):
weight = 200;
break;
case /light/.test(str):
weight = 300;
break;
case /normal/.test(str) || /regular/.test(str):
weight = 400;
break;
case /medium/.test(str):
weight = 500;
break;
case /semibold/.test(str) || /demibold/.test(str):
weight = 600;
break;
case /bold/.test(str):
weight = 700;
break;
case /extrabold/.test(str) || /ultrabold/.test(str):
weight = 800;
break;
case /black/.test(str) || /heavy/.test(str):
weight = 900;
break;
case /extrablack/.test(str) || /ultrablack/.test(str):
weight = 950;
break;
default:
weight = 400;
}
return weight;
};
const fontStyleCalc = (str) => {
return str.includes('italic') ? 'italic' : 'normal';
};
const cb = () => {};
const srcFonts = './src/scss/_fonts.scss';
const appFonts = './app/fonts/';
const fontsStyle = (done) => {
let file_content = fs.readFileSync(srcFonts);
fs.writeFile(srcFonts, '', cb);
fs.readdir(appFonts, function (err, items) {
if (items) {
let c_fontname;
for (var i = 0; i < items.length; i++) {
let fontname = items[i].split('.');
let fontfamily = fontname[0].split('-');
let fontInfo = fontfamily[1].toLowerCase();
fontweight = fontWeightCalc(fontInfo);
fontstyle = fontStyleCalc(fontInfo);
fontname = fontname[0];
fontfamily = fontfamily[0];
if (c_fontname != fontname) {
fs.appendFile(srcFonts, '@include font-face("' + fontfamily + '", "' + fontname + '", ' + fontweight + ', "' + fontstyle + '");\r\n', cb);
}
c_fontname = fontname;
};
};
});
done();
};
// Styles:
const styles = () => {
return src('./src/scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'expanded'
}).on('error', notify.onError()))
.pipe(rename({
suffix: '.min',
}))
.pipe(autoprefixer({
cascade: false,
}))
.pipe(cleanCSS({
level: 2,
}))
.pipe(sourcemaps.write('.'))
.pipe(dest('./app/css/'))
.pipe(browserSync.stream())
};
// HTML (только собирает .html-файл):
const html = () => {
return src(['./src/*.html'])
.pipe(fileInclude({
prefix: '@',
basepath: '@file',
}))
.pipe(dest('./app'))
.pipe(browserSync.stream())
};
// Images:
const images = () => {
return src(['./src/img/**/*.jpg', './src/img/**/*.jpeg', './src/img/**/*.png', './src/img/**.svg'])
.pipe(dest('./app/img'))
};
// SVG Sprite:
const svgSprites = () => {
return src('./src/img/svg/**.svg')
.pipe(svgSprite({
mode: {
stack: {
sprite: '../sprite.svg'
}
}
}))
.pipe(dest('./app/img'))
};
// Scripts:
const scripts = () => {
return src('./src/js/main.js')
.pipe(webpackStream({
output: {
filename: 'main.js',
},
module: {
rules: [{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', {
targets: "defaults"
}]
]
}
}
}]
}
}))
.on('error', (err) => {
console.error('WEBPACK ERROR', err);
this.emit('end'); // Don't stop the rest of the task
})
.pipe(sourcemaps.init())
.pipe(rename({
suffix: '.min',
}))
.pipe(sourcemaps.write('.'))
.pipe(dest('./app/js'))
.pipe(browserSync.stream())
};
// Перенос файлов из папки 'resources' в папку 'app':
const resources = () => {
return src('./src/resources/**')
.pipe(dest('./app'))
};
// Удаление папки 'app':
const clean = () => {
return del(['./app/*'])
};
// BrowserSync (Наблюдение (слежение) за файлами):
const watchFiles = () => {
browserSync.init({
server: {
baseDir: './app',
},
});
watch('./src/scss/**/*.scss', styles);
watch('./src/*.html', html);
watch('./src/html/*.html', html);
watch('./src/img/**/*.jpg', images);
watch('./src/img/**/*.jpeg', images);
watch('./src/img/**/*.png', images);
watch('./src/img/**.svg', images);
watch('./src/img/svg/**.svg', svgSprites);
watch('./src/resources/**', resources);
watch('./src/fonts/**.ttf', fonts);
watch('./src/fonts/**.ttf', fontsStyle);
watch('./src/js/**/*.js', scripts)
};
exports.clean = clean;
exports.fonts = fonts;
exports.styles = styles;
exports.html = html;
exports.images = images;
exports.svgSprites = svgSprites;
exports.resources = resources;
exports.watchFiles = watchFiles;
exports.default = series(clean, parallel(html, scripts, fonts, images, svgSprites, resources), fontsStyle, styles, watchFiles);
// Build version:
// HTML (собирает .html-файл и минифицирует его):
const htmlBuild = () => {
return src(['./src/*.html'])
.pipe(fileInclude({
prefix: '@',
basepath: '@file',
}))
.pipe(htmlMin({
collapseWhitespace: true,
}))
.pipe(dest('./app'))
};
// Styles:
const stylesBuild = () => {
return src('./src/scss/**/*.scss')
.pipe(sass({
outputStyle: 'expanded'
}).on('error', notify.onError()))
.pipe(rename({
suffix: '.min',
}))
.pipe(autoprefixer({
cascade: false,
}))
.pipe(cleanCSS({
level: 2,
}))
.pipe(dest('./app/css/'))
};
// Scripts:
const scriptsBuild = () => {
return src('./src/js/main.js')
.pipe(webpackStream({
output: {
filename: 'main.js',
},
module: {
rules: [{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', {
targets: "defaults"
}]
]
}
}
}]
}
}))
.on('error', (err) => {
console.error('WEBPACK ERROR', err);
this.emit('end'); // Don't stop the rest of the task
})
.pipe(uglify({
toplevel: true,
}).on('error', notify.onError()))
.pipe(rename({
suffix: '.min',
}))
.pipe(dest('./app/js'))
};
// Images:
const imagesBuild = () => {
return src(['./src/img/**/*.jpg', './src/img/**/*.jpeg', './src/img/**/*.png', './src/img/**.svg'])
.pipe(image())
.pipe(dest('./app/img'))
};
exports.build = series(clean, parallel(htmlBuild, scriptsBuild, fonts, imagesBuild, svgSprites, resources), fontsStyle, stylesBuild);
// Cache:
const cache = () => {
return src('./app/**/*.{css,js,svg,png,jpg,jpeg,woff2}', {
base: 'app'
})
.pipe(rev())
.pipe(revdel())
.pipe(dest('app'))
.pipe(rev.manifest('rev.json'))
.pipe(dest('app'));
};
const rewrite = () => {
const manifest = fs.readFileSync('./app/rev.json');
return src('./app/**/*.html')
.pipe(revRewrite({
manifest
}))
.pipe(dest('app'))
};
exports.cache = series(cache, rewrite); |
var express = require('express')
var router = express.Router()
var http = require('http')
var db = require('../db.js')
router.get('/', (req, res, next) => {
res.render('parser', {title: 'parse'})
})
router.get('/ccs', (req, res) => {
// TODO use loadOptions function
http.get('http://www.assist.org/web-assist/welcome.html', (aRes) => {
var html
html = ''
aRes.setEncoding('utf8')
aRes.on('data', (chunk) => {
html += chunk
})
aRes.on('end', () => {
var list
list = html.split('</option>').slice(1, -1).map((line) => {
return dataFromLine(line)
})
res.json({opts: list})
})
}).on('error', (e) => {
console.log(e)
})
})
router.get(/^\/years.*/, (req, res) => {
var split, cc
split = req.url.split('/')
if (split.length !== 3 || split[2] === '') {
res.status(400).end()
return
}
cc = req.url.split('/')[2]
pullOpts('http://www.assist.org/web-assist/' + cc, 'helptextAY\')">', (data) => {
if (data.status !== 200) {
res.status(data.status).end()
} else {
res.json({opts: data.json})
}
})
})
router.get(/^\/unis.*/, (req, res) => {
var split, assistUrl
split = req.url.split('/')
if (split.length !== 3 || split[2] === '') {
res.status(400).end()
return
}
assistUrl = split[2]
console.log(assistUrl)
pullOpts('http://www.assist.org/web-assist/' + assistUrl, 'campus<', (data) => {
if (data.status !== 200) {
res.status(data.status).end()
} else {
res.json({opts: data.json})
}
})
})
router.get(/^\/majors.*/, (req, res) => {
var split, assistUrl
split = req.url.split('/')
if (split.length !== 3 || split[2] === '') {
res.status(400).end()
return
}
assistUrl = split[2]
pullOpts('http://www.assist.org/web-assist/' + assistUrl, 'Select a major', (data) => {
if (data.status !== 200) {
res.status(data.status).end()
} else {
var ret
ret = {}
ret.opts = data.json
ret.submitUrl = parseMajorForm(data.html)
res.json(ret)
}
})
})
router.get(/^\/plan.*/, (req, res) => {
var split, assistUrl
split = req.url.split('/')
if (split.length !== 3 || split[2] === '') {
res.status(400).end()
return
}
assistUrl = split[2]
getPlan(assistUrl, (planUrl) => {
res.end(planUrl)
})
})
router.get(/^\/data.*/, (req, res) => {
var split, cc, year, uni, major
split = req.url.split('/')
if (split.length !== 6 || split[5] === '') {
res.status(400).end()
return
}
cc = split[2]
year = split[3]
uni = split[4]
major = split[5]
db.getPlan(cc, year, uni, major, (stat, data) => {
if (stat !== 200) {
res.status(stat).json(data)
return
}
findCourseUnitsForPlan(cc, year, data, (units) => {
res.json({
'courses': data,
'units': units
})
})
})
})
router.post(/^\/data.*/, (req, res) => {
var split, cc, year, uni, major
split = req.url.split('/')
if (split.length !== 6 || split[5] === '') {
res.status(400).end()
return
}
cc = split[2]
year = split[3]
uni = split[4]
major = split[5]
db.insertOrUpdatePlan(cc, year, uni, major, req.body, () => {
res.send('success')
})
})
router.get(/^\/guess.*/, (req, res) => {
var split, assistUrl
split = req.url.split('/')
if (split.length !== 3 || split[2] === '') {
res.status(400).end()
return
}
assistUrl = split[2]
getPlan(assistUrl, (planUrl) => {
http.get(planUrl, (aRes) => {
if (aRes.statusCode !== 200) {
res.status(aRes.statusCode).end()
return
}
var html
html = ''
aRes.setEncoding('utf8')
aRes.on('data', (chunk) => {
html += chunk
})
aRes.on('end', () => {
res.json({
'plan': parsePlan(html),
'units': getUnits(html)
})
})
})
})
})
function dataFromLine (line) {
return {
link: line.substring(line.search('value="') + 7, line.search('">')),
name: line.substring(line.search('">') + 2)
}
}
function getPlan (url, cb) {
var fullUrl = 'http://www.assist.org/web-assist/' + url
http.get(fullUrl, (res) => {
if (res.statusCode !== 200) {
cb('invalid url')
return
}
var html
html = ''
res.setEncoding('utf8')
res.on('data', (chunk) => {
html += chunk
})
res.on('end', () => {
var planUrl
planUrl = html.split('<iframe')[1].split('src="')[1].split('"')[0]
cb(planUrl)
})
}).on('error', (e) => {
console.log(e)
})
}
function pullOpts (url, sep, callback) {
// returns json with status, json (list of options), html
// TODO refactor code so one function returns html, another parses,
// would be much cleaner
http.get(url, (res) => {
if (res.statusCode !== 200) {
callback({
status: res.statusCode
})
} else {
var html
html = ''
res.setEncoding('utf8')
res.on('data', (chunk) => {
html += chunk
})
res.on('end', () => {
var list, block, lines, valSubstr, endValLoc, link, uni
if (html.indexOf(sep) === -1) {
callback({status: 404})
return
}
block = html.split(sep)[1].split('</select>')[0]
lines = block.split('</option>').slice(0, -1)
list = lines.map((line) => {
valSubstr = line.substring(line.search('value="') + 7)
endValLoc = valSubstr.search('"')
link = valSubstr.substring(0, endValLoc).replace('&', '&')
uni = valSubstr.substring(valSubstr.search('>') + 1)
return {
link: link,
name: uni
}
})
callback({
status: 200,
json: list,
html: html
})
})
}
}).on('error', (e) => {
console.log(e)
})
}
function parseMajorForm (html) {
var page, qstr
html = html.split('<form name="major"')[1].split('</select>')[0]
page = html.substring(html.indexOf('action="') + 8)
page = page.substring(0, page.indexOf('">'))
// for the inputs before the major select box, get their name and value
qstr = ''
html.split('<select')[0].split('\n').forEach((line) => {
if (line.indexOf('<input') !== -1) {
var name, val
name = line.split('name="')[1].split('"')[0]
val = line.split('value="')[1].split('"')[0]
qstr += name + '=' + val + '&'
}
})
qstr = qstr.substring(0, qstr.length - 1)
return page + '?' + qstr
}
function parsePlan (data) {
// TODO put code into functions to make easier to read.
var sep = /--------------------------------------------------------------------------------|AND/
var reOr = />\s*OR\s*<.*\|/
var blocks = data.split(sep)
var courses = {
'required': [],
'choices': [],
'choosenum': [],
'missing': []
}
blocks.forEach((block) => {
if (reOr.exec(block)) {
var grps, opts, allMiss
grps = block.split(reOr)
opts = []
grps.forEach((grp) => {
opts.push(getCourses(grp))
})
allMiss = true
opts.forEach((opt) => {
opt.forEach((crs) => {
if (crs.split(' ')[0] !== 'missing') {
allMiss = false
}
})
})
if (allMiss) {
var str = ''
opts.forEach((opt, i) => {
if (i !== 0) {
str += ' or '
}
str += opt.map((crs) => {
return crs.substr(crs.search(' ') + 1)
}).join(' and ')
})
courses.missing.push(str)
} else {
var newOpts
newOpts = []
opts.forEach((opt) => {
var valid
valid = true
opt.forEach((crs) => {
if (crs.includes('missing')) {
valid = false
}
})
if (valid) {
newOpts.push(opt)
}
})
if (newOpts.length === 1) {
newOpts[0].forEach((crs) => {
courses.required.push(crs)
})
} else {
courses.choices.push(opts)
}
}
} else {
getCourses(block).forEach((crs) => {
if (crs.split(' ')[0] === 'missing') {
var crsName
crsName = crs.split(' ').slice(1).join(' ')
if (courses.missing.indexOf(crsName) === -1) {
courses.missing.push(crsName)
}
} else if (courses.required.indexOf(crs) === -1) {
courses.required.push(crs)
}
})
}
})
return courses
}
function getCourses (str) {
var courses, prevAnd, prevMissing
prevAnd = null
prevMissing = false
courses = []
str.split('\n').forEach((line) => {
var ccCourse = /\([0-9]+(\.[0-9]+)?\)$/.exec(line) // (0-9) found at end of line
var uniCourse = /\([0-9]+(\.[0-9]+)?\)\|/.exec(line) // (0-9)| found in line
// if there's a uni course and no cc course and either there was no &
// sign on the past uni course, or there was and that course was missing
if (uniCourse && !ccCourse && (!prevAnd || (prevAnd && prevMissing))) {
courses.push('missing ' + line.split(' ').slice(0, 2).join(' '))
prevMissing = true
}
if (ccCourse) {
courses.push(
line.slice(line.search(/\|/) + 1) // line after |
.split(' ').slice(0, 2).join(' ') // take first two words
)
prevMissing = false
}
if (uniCourse) {
prevAnd = />\s*\&\s*<.*\|/.exec(line)
}
})
return courses
}
function getUnits (str) {
var units
units = {}
str.split('\n').forEach((line) => {
// regex finds parens with nums, optional floating point number
var unitCnt = /\([0-9]+(\.[0-9]+)?\)$/.exec(line)
if (unitCnt) {
// the count is the string result, with cut off open and close parentheses
unitCnt = parseFloat(unitCnt[0].substr(1, unitCnt[0].length - 2))
var course = line.split('|')[1]
if (course) {
var andFound = course.search(/<b/i)
if (andFound !== -1) {
course = course.substr(0, andFound)
} else {
course = course.substr(0, course.search(/\ \ /))
}
units[course] = unitCnt
}
}
})
return units
}
function findCourseUnitsForPlan (cc, year, coursePlan, cb) {
var units = {}
var courses = new Set()
// add the required courses to the list
coursePlan.required.forEach((crs) => {
courses.add(crs)
})
// add the courses in the choices blocks
coursePlan.choices.forEach((choice) => {
choice.forEach((grp) => {
grp.forEach((crs) => {
courses.add(crs)
})
})
})
// add the courses in the chooseNum blocks
coursePlan.choosenum.forEach((grp) => {
grp.choices.forEach((crs) => {
courses.add(crs)
})
})
courses.forEach((crs) => {
db.getUnits(cc, year, crs, (err, unitCnt) => {
// don't throw an error if a course's units are undefined
if (err) {
console.log('ERROR', err)
units[crs] = 'MISSING'
} else {
units[crs] = unitCnt
}
if (Object.keys(units).length === courses.size) {
cb(units)
}
})
})
}
module.exports = router
|
enyo.depends(
"Palette.js",
"Palette.css",
"Json.js",
"Serializer.js",
"Inspector.css",
"Inspector.js",
"ComponentView.js",
"ComponentView.css",
"InspectorConfig.js",
"Designer.js",
"designer.css",
"RPCCommunicator.js"
);
|
const Sequelize = require('sequelize');
require('dotenv').config();
const seq = new Sequelize('data_warehouse', process.env.U, process.env.P,
{
dialect:'mariadb',
host:'127.0.0.1'
});
seq.authenticate().then(()=>{
console.log('Conectado a la base de datos');
}).catch(err=>{
console.error(err);
});
module.exports = seq; |
/**
* Namespace for all constants in the application.
* @namespace Constants
*/
var Constants = {
} |
import { Component } from 'react'
import RoomService from '../../../services/room.service'
import { Container, Row, Col, Carousel } from 'react-bootstrap'
import { Link } from 'react-router-dom'
import Spinner from "../../shared/Spinner/Spinner"
import UserNavigation from '../../shared/UserNavigation/UserNavigation'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faUserFriends, faReceipt, faHouseUser } from '@fortawesome/free-solid-svg-icons'
import '../../shared/UserNavigation/UserNavigation.css'
import './RoomDatails.css'
class RoomDetails extends Component {
constructor(props) {
super(props)
this.state = {
rooms: undefined
}
this.RoomService = new RoomService()
}
/* loadDetailsRoom() {
} */
componentDidMount() {
const { room_id } = this.props.match.params
this.RoomService
.roomDetails(room_id)
.then(response => this.setState({ rooms: response.data }))
.catch(err => this.props.showMessage(err.response.data.message))
}
render() {
return (
<>
{!this.state.rooms
?
<Spinner />
:
<div className='bg-blue'>
<UserNavigation color link="/habitaciones" text='Volver' />
<Container fluid className=''>
<Row className="room-row-datails">
<Col md={6}>
<div className='carousel-card'>
<Carousel fade>
{this.state.rooms.image.map(elm =>
<Carousel.Item key={elm}>
<img className="d-block w-100" src={elm} alt={elm} />
</Carousel.Item>
)}
</Carousel>
</div>
</Col>
<Col md={4}>
<div className='room-datails-card'>
<h1>{this.state.rooms.name}</h1>
<p>{this.state.rooms.description}</p>
<div className='room-details-icons'>
<div className='datails-box'>
<FontAwesomeIcon icon={faHouseUser} className='icon-font' />
<p>{this.state.rooms.type}</p>
</div>
<div className='datails-box'>
<FontAwesomeIcon icon={faUserFriends} className='icon-font' />
<p>{this.state.rooms.capacity}</p>
</div>
<div className='datails-box'>
<FontAwesomeIcon icon={faReceipt} className='icon-font' />
<p>{this.state.rooms.price} €</p>
</div>
</div>
{!this.props.hasRoom ? <Link to="/habitaciones/disponibles" className="btn btn-roomd">RESERVAR</Link> : null}
</div>
</Col>
</Row>
</Container>
</div>
}
</>
)
}
}
export default RoomDetails |
var mariadb = require("mariadb");
const pool = mariadb.createPool({
host: global.gConfig.db_host,
user: global.gConfig.db_user,
password: global.gConfig.db_password,
database: global.gConfig.db_database
});
module.exports = {
pool
};
|
const mongoose = require('mongoose');
const { Schema } = mongoose;
const DoorSchema = new Schema({
thingId : String,
dimension : String,
dimensionBackground : String
});
const Door = mongoose.model('Door', DoorSchema);
module.exports = Door;
|
const path = require('path')
const webpack = require('webpack')
const argv = require('yargs').argv
const pkg = require('./package.json')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const VueLoaderPlugin = require('vue-loader/lib/plugin')
// const CopyPlugin = require('copy-webpack-plugin')
const mode = argv.mode || 'production'
const qappenv = argv.qappenv || 'prod'
const isDist = argv.dist
const isDemo = argv.demo
const iscocos = argv.cocos
// const filename = mode === 'production' ? 'index.js' : 'index.dev.js';
const ip = require('ip').address()
// 处理 entyr,在 package.json 里面所有的 demo 都覆盖了 qa 参数,以区分是否 demo
const entry = {
index: './src/index.js',
}
if (qappenv === 'qa') {
entry.demo = './demo/index.js'
}
if (iscocos) {
entry.index = './cocosDemo/index.js'
}
// plugins
const plugins = [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(mode),
QAPP_ENV: JSON.stringify(qappenv),
},
BRIDGE_VERSION: JSON.stringify(pkg.version),
}),
new VueLoaderPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
]
if (!isDist) {
plugins.push(new webpack.HotModuleReplacementPlugin())
plugins.push(new BundleAnalyzerPlugin())
}
function getPublicPath () {
// webpack dev server
let result = '/docs/demo/qa/'
if (isDist) {
// http://qapp-bridge-testing.qttfe.com/
if (mode !== 'prodution') {
return ''
}
// http://static-oss.qutoutiao.net
result = `static-oss.qutoutiao.net/${pkg.location}/${pkg.version}/`
}
return result
}
function getPathByEnv () {
let subPath = ''
let finalPath = ''
switch (qappenv) {
case 'qa':
subPath = 'qa'
break
case 'pre':
subPath = 'pre'
break
}
finalPath = path.resolve(__dirname, `dist/${subPath}`)
if (isDemo) {
finalPath = path.resolve(__dirname, 'docs/demo/qa')
}
if (iscocos) {
finalPath = path.resolve(__dirname, 'dist/cocosDemo')
}
return finalPath
}
const config = {
devtool: mode === 'production' ? 'none' : 'source-map',
mode,
entry: entry,
output: {
library: 'qruntimeBridgeCore',
libraryTarget: 'umd',
libraryExport: 'default',
path: getPathByEnv(),
filename: '[name].js',
globalObject: 'this',
publicPath: getPublicPath(),
chunkFilename: '[name].chunk.js',
crossOriginLoading: 'anonymous',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
plugins: [
['import', { libraryName: 'antd-mobile', style: 'css' }], // `style: true` 会加载 less 文件
],
},
},
exclude: /node_modules/,
},
{
test: /\.vue$/,
loader: 'vue-loader',
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
esModule: false,
},
},
],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
plugins,
}
if (mode !== 'production') {
config.devServer = {
contentBase: __dirname, // boolean | string | array, static file location
compress: true, // enable gzip compression
hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin
https: false, // true for self-signed, object for cert authority
noInfo: false, // only errors & warns on hot reload
host: ip || '0.0.0.0',
port: 4000,
open: true,
openPage: 'docs/demo/index.html',
}
}
module.exports = config
|
"use strict";
exports.__esModule = true;
exports.DomInject = void 0;
function DomInject(seletor) {
return function (target, key) {
var elemento;
var getter = function () {
if (!elemento) {
console.log("buscando " + seletor + " para injetar em " + key);
elemento = $(seletor);
}
return elemento;
};
Object.defineProperty(target, key, {
get: getter
});
};
}
exports.DomInject = DomInject;
|
import React from "react"
import BaseLayout from "../components/Layouts/BaseLayout"
import HeadlineSection from "../components/Home/HeadlineSection"
import BelowHeaderHeadlineSection from "../components/Home/BelowHeaderHeadlineSection"
import TestimonialSection from "../components/Home/TesimonialSection"
import LocationScheduleCards from "../components/Shared/LocationScheduleCards"
import BenefitsOneTwoSection from "../components/Home/BenefitsOneTwoSeciton"
import BenefitsThreeFourSection from "../components/Home/BenefitsThreeFourSection"
import BenefitsFiveSixSection from "../components/Home/BenefitsFiveSixSection"
import MembersInActionSectionTop from "../components/Home/MembersInActionSectionTop"
import MembersInActionSectionBottom from "../components/Home/MembersInActionSectionBottom"
import TransformationSection from "../components/Home/TransformationSection"
import CallToActionSection from "../components/Home/CallToActionSection"
import { siteConfig } from "../utils/siteConfig"
import SEO from "../components/seo"
const IndexPage = () => {
return (
<BaseLayout>
<SEO
title={siteConfig.home.title}
description={siteConfig.home.description}
url={siteConfig.home.url}
keywords={siteConfig.home.keywords}
lang={siteConfig.home.lang}
/>
<HeadlineSection />
<BelowHeaderHeadlineSection />
<LocationScheduleCards />
<BenefitsOneTwoSection />
<MembersInActionSectionTop />
<TestimonialSection />
<BenefitsThreeFourSection />
<TransformationSection />
<BenefitsFiveSixSection />
<MembersInActionSectionBottom />
<CallToActionSection />
</BaseLayout>
)
}
export default IndexPage
|
// const { PureComponent } = require('react');
const { memo } = require('react');
const React = require('react');
// Class Type
// PureComponent: state, props 값 변경 시에만 새로 렌더링함 -> 성능 향상
// class Try extends PureComponent {
// // shouldComponentUpdate: state, props 값 변경 시에만 새로 렌더링함 -> 성능 향상
// // shouldComponentUpdate(nextProps, nextState, nextContext) {
// // }
// constructor(props) {
// super(props);
// // 다른 동작
// const filtered = this.props.filter(() => {
// });
// this.state = {
// result: filtered,
// try: this.props.try
// }
// }
// render() {
// const { tryInfo } = this.props;
// return (
// <li>
// <div>{tryInfo.try}</div>
// <div>{tryInfo.result}</div>
// </li>
// );
// }
// }
// Function Type
// memo: state, props 값 변경 시에만 새로 렌더링함 -> 성능 향상
const Try = memo(({ tryInfo }) => {
return (
<li>
<div>{tryInfo.try}</div>
<div>{tryInfo.result}</div>
</li>
)
});
module.exports = Try; |
// src/js/actions/index.js
import { ADD_ARTICLE, DEL_ARTICLE, SHOW_NOTIFICATION, DATA_REQUESTED } from "../constants/action-types";
export function addArticle(payload) {
debugger;
return { type: ADD_ARTICLE, payload }
};
export function deleteArticle(payload) {
debugger;
return { type: DEL_ARTICLE, payload }
};
export function showNotification(notify) {
debugger;
return { type: SHOW_NOTIFICATION, notify }
};
export function getData() {
debugger;
return { type: DATA_REQUESTED };
}
export function getDupa() {
debugger;
return { type: "DUPA" };
} |
import React from 'react';
import { findDOMNode } from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils';
import Tooltip from '../src/Tooltip';
import innerText from './innerText';
describe('Tooltip', () => {
it('Should render a Tooltip', () => {
const title = 'Test';
const instance = ReactTestUtils.renderIntoDocument(<Tooltip>{title}</Tooltip>);
const instanceDom = findDOMNode(instance);
assert.equal(instanceDom.tagName, 'DIV');
assert.equal(instanceDom.className, 'rs-tooltip');
assert.equal(innerText(instanceDom), title);
});
it('Should render at left', () => {
const instance = ReactTestUtils.renderIntoDocument(<Tooltip placement="left" />);
const instanceDom = findDOMNode(instance);
assert.ok(instanceDom.className.match(/\bleft\b/));
});
it('Should render at left 10px', () => {
const instance = ReactTestUtils.renderIntoDocument(<Tooltip positionLeft={10} />);
const instanceDom = findDOMNode(instance);
assert.equal(instanceDom.style.left, '10px');
});
it('Should render at top 10px', () => {
const instance = ReactTestUtils.renderIntoDocument(<Tooltip positionTop={10} />);
const instanceDom = findDOMNode(instance);
assert.equal(instanceDom.style.top, '10px');
});
it('Should have a custom className', () => {
const instance = ReactTestUtils.renderIntoDocument(<Tooltip className="custom" />);
assert.ok(findDOMNode(instance).className.match(/\bcustom\b/));
});
it('Should have a custom style', () => {
const fontSize = '12px';
const instance = ReactTestUtils.renderIntoDocument(<Tooltip style={{ fontSize }} />);
assert.equal(findDOMNode(instance).style.fontSize, fontSize);
});
it('Should have a custom className prefix', () => {
const instance = ReactTestUtils.renderIntoDocument(<Tooltip classPrefix="custom-prefix" />);
assert.ok(findDOMNode(instance).className.match(/\bcustom-prefix\b/));
});
});
|
import React from "react"
import styled from "styled-components"
import { Header3 } from "../../../../styles/Headlines"
import { ElementContainer } from "../../../../styles/Containers"
const Headline3 = () => {
return (
<ElementContainer column setMobileMarginTop={30}>
<ExtendHeader3 upper primary mobileLarge>
Strength
</ExtendHeader3>
<ExtendHeader3 primary mobileMedium>
is the answer
</ExtendHeader3>
</ElementContainer>
)
}
export default Headline3
const ExtendHeader3 = styled(Header3)`
color: #2b2b2b;
`
|
'use strict';
let mongoose = require ("mongoose");
let Schema = mongoose.Schema;
let BasePlugins = require ("./plugins/BasePlugins");
// create a schema
let schema = new Schema({
_id: { type: Number, inc: true},
type_id: Number,
class_id: Number,
game_id: Number,
spq: {type: Number, default: 10},
play: Number,
time: Number,
answers: [Schema.Types.Mixed],
content: [Schema.Types.Mixed],
});
let col_name = 'exam_events';
schema.set('autoIndex', false);
schema.plugin(BasePlugins, {col_name: col_name});
module.exports = mongoose.model(col_name, schema); |
/**
* Method of overriding the size of viewport in web page using the `@viewport` rule, replacing Apple's own popular `<meta>` viewport implementation. Includes the `extend-to-zoom` width value.
*
* See: https://caniuse.com/css-deviceadaptation
*/
import { checkAtRule } from '../../utils/util.js';
/**
* @type {import('../features').Feature}
*/
export default checkAtRule('viewport');
|
angular.module('app.routes', [])
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
.state('blueCar.rentals', {
url: '/rentals',
views: {
'side-menu21': {
templateUrl: 'templates/rentals.html',
controller: 'rentalsCtrl'
}
}
})
.state('blueCar.profile', {
url: '/profile',
views: {
'side-menu21': {
templateUrl: 'templates/profile.html',
controller: 'profileCtrl'
}
}
})
.state('blueCar.settiings', {
url: '/settings',
views: {
'side-menu21': {
templateUrl: 'templates/settiings.html',
controller: 'settiingsCtrl'
}
}
})
.state('blueCar', {
url: '/cars',
templateUrl: 'templates/blueCar.html',
controller: 'blueCarCtrl'
})
$urlRouterProvider.otherwise('/cars/rentals')
}); |
'use strict';
const boom = require('boom');
const jwt = require('jsonwebtoken');
const TokenExtractor = require('./extractor');
const Config = require('../config/env');
module.exports = function () {
return {
authenticate: async function (request, h) {
const token = TokenExtractor.extract(request);
if (!token) {
return h.unauthenticated(boom.unauthorized('Header format should be Authorization: Bearer [token]', 'Bearer'));
}
try {
const credentials = jwt.verify(token, Config.token.secret);
return h.authenticated({ credentials, artifacts: token });
} catch (err) {
return h.unauthenticated(boom.unauthorized(err.message, 'Bearer'));
}
}
};
};
|
/*!
* base-pkg <https://github.com/node-base/base-pkg>
*
* Copyright (c) 2016-2017, Jon Schlinkert.
* Released under the MIT License.
*/
'use strict';
const isValid = require('is-valid-app');
const debug = require('debug')('base-pkg');
const Expand = require('expand-pkg');
const Pkg = require('pkg-store');
module.exports = function(options) {
if (typeof options === 'string') {
options = { cwd: options };
}
return function(app) {
if (!isValid(app, 'base-pkg')) return;
debug('initializing from <%s>', __filename);
app.pkg = new Pkg(Object.assign({ cwd: process.cwd() }, app.options, options));
app.pkg.expand = function() {
const pkg = new Expand();
return pkg.expand(Object.assign({}, app.pkg.data));
};
};
};
|
Ext.Loader.setConfig({
enabled: true
});
//Ext.Loader.setPath('Ext.ux', '../../../Scripts/Ext4.0/ux');
Ext.Loader.setPath('Ext.ux', '../../../Scripts/Views/ProductParticulars');
Ext.require([
'Ext.ux.CheckColumn'
]);
var ToolStore = Ext.create('Ext.data.Store', {
model: 'GIGADE.Function',
proxy: {
type: 'ajax',
url: '/Function/GetFunction',
actionMethods: 'post',
reader: {
type: 'json'
}
}
});
var ToolWin = function (row) {
var t_sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections) {
Ext.getCmp("ToolGrid").down('#t_remove').setDisabled(selections.length == 0);
Ext.getCmp("ToolGrid").down('#t_edit').setDisabled(selections.length == 0);
}
}
});
var ToolGrid = Ext.create('Ext.grid.Panel', {
id: 'ToolGrid',
store: ToolStore,
columnLines: true,
frame: true,
columns: [
{ header: NUMBER, xtype: 'rownumberer', width: 50, align: 'center' },
{ header: TOOL_NAME, dataIndex: 'FunctionName', width: 150, align: 'center' },
{ header: TOOL_CODE, dataIndex: 'FunctionCode', width: 150, align: 'center' },
{ header: ISAUTHORIZED, xtype: 'checkcolumn', dataIndex: 'IsEdit', width: 60, align: 'center' }
],
tbar: [
{ xtype: 'button', text: ADD, iconCls: 'icon-add', handler: function () { SaveToolWin(row); } },
{ xtype: 'button', id: 't_edit', text: EDIT, iconCls: 'icon-edit', disabled: true, handler: function () { onToolEditClick(row); } },
{ xtype: 'button', id: 't_remove', text: REMOVE, iconCls: 'icon-remove', disabled: true, handler: function () { onToolRemoveClick(row); } }
],
listeners: {
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
},
selModel: t_sm
});
Ext.create('Ext.window.Window', {
title: TOOL_MGR_TITLE,
items: [ToolGrid],
width: 500,
height: document.documentElement.clientHeight * 400 / 783,
layout: 'fit',
labelWidth: 100,
closeAction: 'destroy',
resizable: false,
modal: 'true',
listeners: {
"show": function () {
ToolStore.load({
params: { TopValue: Ext.htmlEncode(row.data.RowId), Type: 2 }
});
}
}
}).show();
}
onToolEditClick = function (frow) {
var row = Ext.getCmp("ToolGrid").getSelectionModel().getSelection();
if (row.length == 0) {
Ext.Msg.alert(INFORMATION, NO_SELECTION);
}
else if (row.length > 1) {
Ext.Msg.alert(INFORMATION, ONE_SELECTION);
} else if (row.length == 1) {
SaveToolWin(frow, row[0]);
}
}
onToolRemoveClick = function (frow) {
var row = Ext.getCmp("ToolGrid").getSelectionModel().getSelection();
if (row.length < 0) {
Ext.Msg.alert(INFORMATION, NO_SELECTION);
}
else {
Ext.Msg.confirm(CONFIRM, Ext.String.format(DELETE_INFO, row.length), function (btn) {
if (btn == 'yes') {
var rowIDs = '';
for (var i = 0; i < row.length; i++) {
rowIDs += row[i].data.RowId + '|';
}
Ext.Ajax.request({
url: '/Function/DeleteFunction',
method: 'post',
params: { rowID: rowIDs },
success: function (form, action) {
var result = Ext.decode(form.responseText);
Ext.Msg.alert(INFORMATION, SUCCESS);
if (result.success) {
ToolStore.load({
params: { TopValue: Ext.htmlEncode(frow.data.RowId), Type: 2 }
});
}
},
failure: function () {
}
});
}
});
}
} |
import styled from "styled-components";
export const Wrapper1 = styled.div`
display: flex;
flex-wrap: wrap;
margin-bottom: 1rem;
text-align: left;
`;
export const Each = styled.div``;
export const Label = styled.label`
font-weight: bold;
margin-bottom: 0.5rem;
display: block;
`;
export const Input = styled.input`
display: flex;
flex-direction: row;
font: inherit;
padding: 0.5rem;
border-radius: 5px;
border: 2px solid blue;
flex: 1;
max-width: 100%;
width: 15rem;
`;
export const Wrapper2 = styled.div`
text-align: center;
`;
export const Button = styled.button``;
|
import { createStore } from 'vuex';
import { getAdminInfoRequest } from '../utils/adminRequest';
const store = createStore({
state: {
permission: null,
noticeTotal: 0,
noticeOrderCount: 0,
},
mutations: {
increaseNoticeOrderCount(state, payload) {
state.noticeOrderCount += payload.count;
state.noticeTotal += payload.count;
},
decreaseNoticeOrderCount(state, payload) {
state.noticeOrderCount -= payload.count;
state.noticeTotal -= payload.count;
},
clearNoticeOrderCount(state) {
state.noticeTotal -= state.noticeOrderCount;
state.noticeOrderCount = 0;
},
},
actions: {
getPermission(context) {
return new Promise((resolve, reject) => {
let username = sessionStorage.getItem('username');
getAdminInfoRequest(username).then((res) => {
if (res.state) {
context.state.permission = res.permission;
resolve(res.permission);
} else {
console.log(res.msg);
reject(res.msg);
}
});
});
},
},
modules: {},
});
export default store;
|
export const SAVE_OTHERDATAS = 'save_otherdatas' //保存断货补单王数据 |
function compareArrays(first, second) {
return (
first.every(e => second.includes(e)) && second.every(e => first.includes(e))
);
}
export default compareArrays;
|
export const AllTeamLogos = {
Arizona_Cardinals: require('./arizona_cardinals.png').default,
Atlanta_Falcons: require('./atlanta_falcons.png').default,
Baltimore_Ravens: require('./baltimore_ravens.png').default,
Buffalo_Bills: require('./buffalo_bills.png').default,
Carolina_Panthers: require('./carolina_panthers.png').default,
Chicago_Bears: require('./chicago_bears.png').default,
Cincinnati_Bengals: require('./cincinnati_bengals.png').default,
Cleveland_Browns: require('./cleveland_browns.png').default,
Dallas_Cowboys: require('./dallas_cowboys.png').default,
Denver_Broncos: require('./denver_broncos.png').default,
Detroit_Lions: require('./detroit_lions.png').default,
Green_Bay_Packers: require('./green_bay_packers.png').default,
Houston_Texans: require('./houston_texans.png').default,
Indianapolis_Colts: require('./indianapolis_colts.png').default,
Jacksonville_Jaguars: require('./jacksonville_jaguars.png').default,
Kansas_City_Chiefs: require('./kansas_city_chiefs.png').default,
Las_Vegas_Raiders: require('./las_vegas_raiders.png').default,
Los_Angeles_Chargers: require('./los_angeles_chargers.png').default,
Los_Angeles_Rams: require('./los_angeles_rams.png').default,
Miami_Dolphins: require('./miami_dolphins.png').default,
Minnesota_Vikings: require('./minnesota_vikings.png').default,
New_England_Patriots: require('./new_england_patriots.png').default,
New_Orleans_Saints: require('./new_orleans_saints.png').default,
New_York_Giants: require('./new_york_giants.png').default,
New_York_Jets: require('./new_york_jets.png').default,
Philadelphia_Eagles: require('./philadelphia_eagles.png').default,
Pittsburgh_Steelers: require('./pittsburgh_steelers.png').default,
San_Francisco_49ers: require('./san_francisco_49ers.png').default,
Seattle_Seahawks: require('./seattle_seahawks.png').default,
Tampa_Bay_Buccaneers: require('./tampa_bay_buccaneers.png').default,
Tennessee_Titans: require('./tennessee_titans.png').default,
Washington_Football_Team: require('./washington_football_team.png').default
} |
const express = require('express')
const router = express.Router()
const userController = require('../controller/userController')
const contentController = require('../controller/contentController')
router.post('/register', userController.signUp)
router.post('/signin', userController.signInUser)
router.get('/alluser', userController.getAllUser)
router.get('/singleuser/:id', userController.getSingleUser)
router.put('/profile/:id', userController.updateProfile)
router.post('/post', contentController.createContent)
router.get('/allcontent', contentController.getAllPost)
router.get('/singlepost/:id', contentController.getSinglePost)
router.put('/updatepost/:id', contentController.updateSinglePost)
router.delete('/deletepost/:id', contentController.deletePost)
module.exports = router;
|
import React, { Component } from 'react'
import { Redirect, Link } from 'react-router-dom'
import { LinkContainer } from "react-router-bootstrap";
import { Collapse, Alert, Col, Row } from "react-bootstrap"
import { app } from 'config/base'
import bayty_icon from 'assets/img/bayty_icon1.png';
import FirestoreServices from 'services/FirestoreServices';
class Login extends Component {
constructor() {
super()
this.state = {
redirect: false,
formStatusAlert: {
alert: false,
showRegisterLink: false,//when the email is wrong we show a link to the registration page
type: "info", //indicates that we should show an alert msg due to form invalid
alertMsg: "", //message shown when form can not be submitted cause form is not valid
}
}
this.authWithEmailPassword = this.authWithEmailPassword.bind(this)
this.reportError = this.reportError.bind(this)
}
reportError(msg, registerLink = false) {
this.setState({
formStatusAlert: {
alert: true,
showRegisterLink: registerLink,
type: 'danger',
alertMsg: msg,
showSuccessfulSubmit: false
}
});
}
authWithEmailPassword(event) {
event.preventDefault()
const email = this.emailInput.value
const password = this.passwordInput.value
app.auth().fetchProvidersForEmail(email)
.then((providers) => {
if (providers.length === 0) {
// create user
this.reportError('الايميل المستخدم غير مسجل مسبقا.', true)
//} else if (providers.indexOf("password") === -1) {
// this means the user is registered using SSO so point him to SSO singin
} else {
console.log("fetchProvidersForEmail")
// sign in with email/password and return user object on success
return app.auth().signInWithEmailAndPassword(email, password)
}
})
.then((user) => {
const { adminFlag } = this.props.location.state || { adminFlag: false };
if (user && user.email) {
FirestoreServices.readDBRecord('group', user.uid).then((value) => {
const { admin } = value;
if (adminFlag && !admin) {
this.reportError('User is not admin.', true)
return;
}
console.log('Autentication Passed successfully!')
const { setCurrentUser } = this.props;
setCurrentUser(user, admin);
this.setState({
redirect: true
})
})
}
})
.catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/account-exists-with-different-credential') {
this.reportError('كلمة السر غير صحيحة. ');
} else if (errorCode === 'auth/email-already-in-use') {
this.reportError('البريد الالكتروني مسجل مسبقا. نرجو استخدام عنوان آخر أو طلب استرداد كلمة سر في حال كانت كلمة السر مفقودة');
} else if (errorCode === 'auth/invalid-email') {
this.reportError('عنوان البريد الالكتروني غير صحيح');
} else if (errorCode === 'auth/wrong-password') {
this.reportError('كلمة السر غير صحيحة. ');
} else {
this.reportError("حدث خطأ غير معروف. نرجو ابلاغ الصيانة: " + errorCode + errorMessage);
}
})
}
render() {
const { from } = this.props.location.state || { from: { pathname: '/' }, adminFlag: false }
const { redirect } = this.state
if (redirect) {
console.log('redirect to ', from)
return (
<Redirect to={from.pathname} />
)
}
return (
<div style={{ height: '100vh' }} className="loginreg">
<form onSubmit={(event) => this.authWithEmailPassword(event)}
ref={(form) => { this.loginForm = form }}>
<div className="loginregtitle">
<img src={bayty_icon} alt=""/>
<h2 style={{ color: 'rgb(26,156,142)' }}>تسجيل الدخول </h2>
</div>
<Collapse in={this.state.formStatusAlert.alert}>
<Alert
bsStyle={this.state.formStatusAlert.type}
>
{this.state.formStatusAlert.alertMsg}
{this.state.formStatusAlert.showRegisterLink
? <Link to="/registration"> انقر هنا للتسجيل كمستخدم جديد </Link>
: null
}
</Alert>
</Collapse>
<Row>
<Col lg={12} sm={12}>
</Col>
<Col sm={12} lg={12} >
<div className="form-group" >
<input id="inputEmail" name="email" type="email" ref={(input) => { this.emailInput = input }} placeholder="عنوان البريد الالكتروني"></input>
</div>
</Col>
<Col sm={12} lg={12}>
<div className="form-group">
<input id="inputPassword" name="password" type="password" ref={(input) => { this.passwordInput = input }} placeholder="كلمة السر"></input>
</div>
</Col>
</Row>
<div className="form-group">
<button type="submit" >تسجيل دخول</button>
<LinkContainer to="/resetpassword" activeClassName="active" style={{ cursor: "pointer" }}>
<p><span style={{ cursor: "pointer" }}> نسيت كلمة المرور؟ </span></p>
</LinkContainer>
<p > <span style={{ color: "black" }}>ليس لديك حساب؟</span>
<LinkContainer to="/registration" activeClassName="active" style={{ cursor: "pointer" }}>
<span > قم بالتسجيل</span>
</LinkContainer></p>
</div>
</form>
</div>
)
}
}
export default Login
|
export const APP_CONSTANT = {
APP: 'app',
SITE_KEY: '6Le7Fx8UAAAAAOGXo166nXZsaxKVvnA3Bq2gqJ0B'
};
export const IMG_CONSTANT = {
BASE_PATH : "/assets/img/login_img/" ,
ICON_PATH:"/assets/img/icons/",
IMAGE_PATH:"/assets/img/"
};
export const MESSAGE_CONSTANT ={
}
|
const express = require("express");
const router = express.Router();
const {
newOrder,
singleOrder,
myOrders,
} = require("../controllers/ordersController");
const { isAuthenticatedUser, authorizeRole } = require("../middlewares/auth");
router.route("/order/new").post(isAuthenticatedUser, newOrder);
router.route("/order/me").get(isAuthenticatedUser, myOrders);
router.route("/order/:id").get(isAuthenticatedUser, singleOrder);
module.exports = router;
|
import React from "react";
import {Button, Card, InputNumber} from "antd";
class Disabled extends React.Component {
state = {
disabled: true,
};
toggle = () => {
this.setState({
disabled: !this.state.disabled,
});
};
render() {
return (
<Card className="gx-card" title="Disabled">
<InputNumber min={1} max={10} disabled={this.state.disabled} defaultValue={3}/>
<div style={{marginTop: 20}}>
<Button onClick={this.toggle} type="primary">Toggle disabled</Button>
</div>
</Card>
);
}
}
export default Disabled;
|
const security = require('./security')
const user = require('./user')
const files = require('./files')
module.exports = {
Security: security,
User: user,
Files: files
}
|
module.exports = {
quoteProps: "consistent",
semi: true,
};
|
import { observable, action } from 'mobx'
class ChartData {
@observable columnData = []
@action
updateColumnData(data) {
this.columnData = data
}
}
export default new ChartData() |
var n1;
var n2;
var mArr = [];
var IsFirstClick = true;
var firstElement;
var secondElement;
var getBoardSizeValues = function(){
n1 = $('#rows').val();
n2 = $('#columns').val();
createNumbers();
createBoard();
}
// var onCardClick = function(){
// if (IsFirstClick){
// firstElement = $(this);
// var firstCardVal = firstElement.attr('cardNum');
// firstElement.html(firstCardVal);
// IsFirstClick = false;
// }
// else{
// secondElement = $(this);
// var secondCardVal = secondElement.attr("cardNum");
// secondElement.html(secondCardVal);
// if(firstElement.attr('cardNum') != secondElement.attr('cardNum'))
// setTimeout(function(){ notEqual();},3000);
// IsFirstClick = true;
// }
// }
var notEqual = function(){
firstElement.html("X");
secondElement.html("X");
}
var createNumbers = function () {
var maxNum = (n1*n2)/2;
var minNum = 0;
for (var i = 0; i < maxNum; i++){
mArr [i*2] = mArr[(i*2)+1] = i+1;
}
shuffle(minNum,maxNum*2);
}
var createBoard = function(){
var str = "";
var len = mArr.len;
for (var i = 0; i < mArr.length; i++) {
str += "<div style='float:left;width:60px'><button class='card' cardNum='"
+ mArr[i] + "' style='float:left;width:60px'>X"
str += "</button></div>";
if ((i+1) % n2 == 0)
str += "<br><br>";
};
$("body").append(str);
}
var shuffle = function (minNum,maxNum){
var i = 0;
while (i < maxNum*2)
{
var randNum1 = getRandomInt(minNum,maxNum);
var randNum2 = getRandomInt(minNum,maxNum);
swap (randNum1,randNum2);
i++;
}
}
var getRandomInt = function(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var swap = function (num1,num2){
var tmp = mArr [num1];
mArr[num1] = mArr[num2];
mArr[num2] = tmp;
}
$("#submit").click(function(){
getBoardSizeValues();
$(".values").hide();
var cardsElement = document.getElementsByClassName("card");
console.log(cardsElement[0]);
for(var i = 0 ; i < cardsElement.length; i++){
cardsElement[i].onclick = onCardClick;
}
// $('.card').click(onCardClick);
})
var onCardClick = function(e){
if(IsFirstClick){
firstElement = e.srcElement;
firstCardVal = firstElement.getAttribute("cardNum");
console.log(firstElement);
firstElement.innerHTML = firstCardVal;
IsFirstClick = false;
}
else
{
secondElement = e.srcElement;
secondCardVal = secondElement.getAttribute("cardNum");
secondElement.innerHTML = secondCardVal;
IsFirstClick = true;
}
}
|
import React, {useState} from 'react'
import './Siderbar.scss'
import { Menu } from 'antd';
import {
Link
} from "react-router-dom";
const Siderbar = () =>{
const list = [
{
name: '发现音乐',
path: '/home',
activePath: ['/home']
},
{
name: '视频',
path: '/personal',
activePath: ['/personal']
},
{
name: '直播',
path: '/video',
activePath: ['/video']
},
{
name: '朋友',
path: '/friends',
activePath: ['/friends']
},
{
name: '私人FM',
path: '/personalFM',
activePath: ['/personalFM']
},
{
name: '推荐',
path: '/introduce',
activePath: ['/introduce']
},
{
name: '推荐',
path: '/introduce',
activePath: ['/introduce']
},
{
name: '推荐',
path: '/introduce',
activePath: ['/introduce']
},
{
name: '推荐',
path: '/introduce',
activePath: ['/introduce']
},
{
name: '推荐',
path: '/introduce',
activePath: ['/introduce']
},
{
name: '推荐',
path: '/introduce',
activePath: ['/introduce']
},
{
name: '直播',
path: '/video',
activePath: ['/video']
},
{
name: '朋友',
path: '/friends',
activePath: ['/friends']
},
{
name: '私人FM',
path: '/personalFM',
activePath: ['/personalFM']
},
]
const listleft = list.map((item, index)=>{
return(
<li key={index}>
<a href={item.path} className={item.activePath.includes(window.location.pathname) ? 'titlelist' : ''}>
{item.name}</a>
</li>
)
})
return(
<div className="siderbar">
<ul>
{listleft}
</ul>
</div>
)
}
export default Siderbar; |
/* eslint-disable */
import Quill from '../quill.js';
import CodeBlock, { CodeBlockContainer } from '../formats/code';
import './helpers/unit';
// import './unit/blots/scroll';
// import './unit/blots/block';
// import './unit/blots/block-embed';
// import './unit/blots/inline';
// import './unit/core/editor';
// import './unit/core/selection';
// import './unit/core/quill';
// import './unit/formats/color';
// import './unit/formats/link';
// import './unit/formats/script';
// import './unit/formats/align';
// import './unit/formats/code';
// import './unit/formats/header';
// import './unit/formats/indent';
// import './unit/formats/list';
// import './unit/formats/bold';
// import './unit/formats/table';
// import './unit/modules/clipboard';
// import './unit/modules/history';
// import './unit/modules/keyboard';
// import './unit/modules/syntax';
// import './unit/modules/table';
// import './unit/modules/toolbar';
// import './unit/ui/picker';
// import './unit/theme/base/tooltip';
import './unit1/formats/bold';
// Syntax version will otherwise be registered
Quill.register(CodeBlockContainer, true);
Quill.register(CodeBlock, true);
export default Quill;
|
import { RECSEN_ERRO_INESPERADO, RECSEN_INTERNET_INOPERANTE, RECSEN_END_RECUPERACAO, RECSEN_START_RECUPERACAO, RECSEN_CHANGE_FIELD, RECSEN_RECUPERAR } from "../actions/EsqueciSenhaAction";
import { alterarState } from "./FuncoesGenericas";
const INITIAL_STATE = {email: '', loading: false, sucesso: true, mensagemFalha: '', executado: false};
export default (state = INITIAL_STATE, action) => {
switch(action.type){
case RECSEN_CHANGE_FIELD: {
let newState = alterarState(state, 'email', action.value);
return alterarState(newState, 'executado', false);
}
case RECSEN_START_RECUPERACAO: {
return {
...state, loading: true
}
}
case RECSEN_END_RECUPERACAO: {
return {
...state, loading: false, sucesso: true, executado: true
}
}
case RECSEN_INTERNET_INOPERANTE: {
// console.log('erro de internet...');
let newState = {
...state,
sucesso: false,
executado: true,
loading: false,
mensagemFalha: 'Favor verificar sua internet. Não foi possível se comunicar com o soneca servidor!'
};
// console.log(newState);
return newState;
}
case RECSEN_ERRO_INESPERADO: {
return {
...state,
loading: false,
executado: true,
sucesso: false,
mensagemFalha: action.mensagemFalha
}
}
case RECSEN_RECUPERAR: {
return state;
}
default: {
return state;
}
}
} |
function delegate(callingObject, methodOwner, methodName) {
return function() {
return methodOwner[methodName].apply(callingObject, arguments);
};
}
function Person(firstName, lastName, age, gender) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.gender = gender;
}
Person.prototype.fullName = function() {
return this.firstName + ' ' + this.lastName;
}
Person.prototype.communicate = function() {
console.log('Communicating');
}
Person.prototype.eat = function() {
console.log('Eating');
}
Person.prototype.sleep = function() {
console.log('Sleeping');
}
function Doctor(firstName, lastName, age, gender, specialization) {
Person.call(this, firstName, lastName, age, gender);
this.specialization = specialization;
}
Object.setPrototypeOf(Doctor.prototype, Person.prototype);
Doctor.prototype.diagnose = function() {
console.log('Diagnosing');
}
function Professor(firstName, lastName, age, gender, subject) {
Person.call(this, firstName, lastName, age, gender);
this.subject = subject;
}
Object.setPrototypeOf(Professor.prototype, Person.prototype);
Professor.prototype.teach = function() {
console.log('Teaching');
}
function Student(firstName, lastName, age, gender, degree) {
Person.call(this, firstName, lastName, age, gender);
this.degree = degree;
}
Object.setPrototypeOf(Student.prototype, Person.prototype);
Student.prototype.study = function() {
console.log('Studying');
}
function GraduateStudent(firstName, lastName, age, gender, degree, graduateDegree) {
Student.call(this, firstName, lastName, age, gender, degree);
this.graduateDegree = graduateDegree;
}
Object.setPrototypeOf(GraduateStudent.prototype, Student.prototype);
GraduateStudent.prototype.research = function() {
console.log('Researching');
}
let professional = {
invoice: function() {
console.log(`${this.fullname} is billing customer.`);
},
payTax: function() {
console.log(`${this.fullname} is paying taxes.`);
},
}
function extend(obj, mixin) {
Object.keys(mixin).forEach(key => obj[key] = delegate(obj, mixin, key));
return obj;
}
var doctor = extend(new Doctor('foo', 'bar', 21, 'gender', 'Pediatrics'), professional);
console.log(doctor instanceof Person); // logs true
console.log(doctor instanceof Doctor); // logs true
doctor.eat(); // logs 'Eating'
doctor.communicate(); // logs 'Communicating'
doctor.sleep(); // logs 'Sleeping'
console.log(doctor.fullName()); // logs 'foo bar'
doctor.diagnose(); // logs 'Diagnosing'
var professor = extend(new Professor('foo', 'bar', 21, 'gender', 'Systems Engineering'), professional);
console.log(professor instanceof Person); // logs true
console.log(professor instanceof Professor); // logs true
professor.eat(); // logs 'Eating'
professor.communicate(); // logs 'Communicating'
professor.sleep(); // logs 'Sleeping'
console.log(professor.fullName()); // logs 'foo bar'
professor.teach(); // logs 'Teaching'
doctor.invoice(); // logs 'foo bar is Billing customer'
doctor.payTax(); // logs 'foo bar Paying taxes'
professional.invoice = function() {
console.log(this.fullName() + ' is Asking customer to pay');
};
doctor.invoice(); // logs 'foo bar is Asking customer to pay'
professor.invoice(); // logs 'foo bar is Asking customer to pay'
professor.payTax(); // logs 'foo bar Paying taxes'
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var FoodSchema = new Schema({
name: {type: String, required: true},
peso: String,
description: String,
image: String,
type: String,
expires: {type: Date},
create: {type: Date},
user_id: String,
state: String,
lat: String,
lng: String,
});
module.exports = mongoose.model('Food', FoodSchema); |
/***********
Advanced routing and resolves
>>> https://medium.com/opinionated-angularjs/advanced-routing-and-resolves-a2fcbf874a1c#.q9i3lmnjp
>>> https://scotch.io/tutorials/angular-routing-using-ui-router
>>> http://www.funnyant.com/angularjs-ui-router/
>>> https://github.com/angular-ui/ui-router
>>> https://github.com/angular-ui/ui-router/wiki
>>> https://github.com/angular-ui/ui-router/issues/64
>>> http://stackoverflow.com/questions/23585065/angularjs-ui-router-change-url-without-reloading-state
**************/
'use strict';
var app = require('angular').module('noteshareApp');
app.controller('MenuController', require('./controllers/MenuController'))
app.controller('MainController', require('./controllers/MainController'))
app.controller('AboutController', require('./controllers/AboutController'))
app.controller('UserPreferenceController', require('./controllers/UserPreferenceController'))
app.constant("mathJaxDelay", 1100)
app.constant("notFoundErrorDocumentId", 11)
app.constant("notFoundErrorDocumentTitle", 11)
// configure our routes
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
// route for the home page
.state('home', {
url: '/',
templateUrl : 'pages/signin.html',
controller : 'SigninController'
})
.state('about', {
url: '/about',
templateUrl : 'pages/about.html',
controller : 'AboutController'
})
.state('user', {
url: '/user/:id',
templateUrl : 'pages/site.html',
controller : 'SiteController'
})
/***
.state('site', {
url: '/public/:id',
templateUrl : 'pages/site.html',
controller : 'SiteController'
})
.state('siteDocument', {
url: '/site/:site/:doc_id',
templateUrl : 'pages/site.html',
controller : 'SiteDocumentController'
})
.state('foo', {
url: 'foo',
templateUrl : 'pages/about.html',
controller : 'AboutController'
})
.state('foo2', {
url: 'foo/:id',
templateUrl : 'pages/about.html',
controller : 'AboutController'
})
**/
.state('signin', {
url: '/signin',
templateUrl : 'pages/signin.html',
controller : 'SigninController'
})
.state('newdocument', {
url: '/newdocument',
templateUrl : 'pages/newdocument.html',
controller : 'newDocumentController'
})
// route for the contact page
.state('documents', {
url: '/documents/:id?option',
templateUrl : 'pages/documents.html',
controller : 'documentsController'
})
.state('document', {
url: '/documents/:id',
templateUrl : 'pages/documents.html',
controller : 'documentsController'
})
.state('printdocument', {
url: '/printdocument/:id',
templateUrl : 'pages/printdocument.html',
controller : 'PrintDocumentController'
})
.state('exportlatex', {
url: '/exportlatex/:id',
templateUrl : 'pages/exportlatex.html',
controller : 'ExportLatexController'
})
.state('editdocument', {
url: '/editdocument',
templateUrl : 'pages/editdocument.html',
controller : 'editDocumentController'
})
.state('editOneDocument', {
url: '/editdocument/:id',
templateUrl : 'pages/editdocument.html',
controller : 'editDocumentController'
})
// http://benfoster.io/blog/ui-router-optional-parameters
// http://best-web-creation.com/articles/view/id/angular-js-ui-router-opt-params?lang=en
// http://stackoverflow.com/questions/30225424/angular-ui-router-more-optional-parameters-in-one-state
.state('deletedocument', {
url: '/deletedocument/mode',
templateUrl : 'pages/documents.html',
controller : 'DeleteDocumentController',
params : { mode: {value: 'soft'} }
/*
controller: function($scope, $stateParams) {
$scope.mode = $stateParams.mode;
} */
})
.state('signup', {
url: '/signup',
templateUrl : 'pages/signup.html',
controller : 'SignupController'
})
.state('images', {
url: '/images',
templateUrl : 'pages/images.html',
controller : 'ImagesController'
})
.state('getimage', {
url: '/images/:id',
templateUrl: 'pages/images.html',
controller : 'ImagesController'
})
.state('userpreferences', {
url: '/userpreferences',
templateUrl: 'pages/userpreferences.html',
controller: 'UserPreferenceController'
})
.state('imageupload', {
url: '/imageupload',
templateUrl : 'pages/imageupload.html',
controller : 'ImageUploadController'
})
.state('backups', {
url: '/backups',
templateUrl: 'pages/backups.html',
controller: 'BackupController'
})
.state('backupmanager', {
url: '/backupmanager?id',
templateUrl: 'pages/backupmanager.html',
controller: 'BackupManagerController'
})
.state('admin', {
url: '/admin',
templateUrl: 'pages/admin.html',
controller: 'AdminController'
})
// This following enables requests like
// http://www.manuscripta/go/jc.home
// http://www.manuscripta/go/jc.qft
// where jc.home, jc.qft is the identifier of a document.
// these are namespace by the prefix USERNAME.
.state('go', {
url: '/:id',
templateUrl : 'pages/documents.html',
controller : 'documentsController'
})
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
app.controller('stageController', function ($scope) { $scope.repeat = 5; });
|
/*jshint globalstrict:false, strict:false */
/* global getOptions, assertTrue, assertFalse, assertEqual, arango */
//////////////////////////////////////////////////////////////////////////////
/// @brief test for soft shutdown of a coordinator
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2021 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB Inc, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2021, ArangoDB Inc, Cologne, Germany
//////////////////////////////////////////////////////////////////////////////
let jsunity = require('jsunity');
const pu = require('@arangodb/testutils/process-utils');
const request = require("@arangodb/request");
const internal = require("internal");
const db = require("internal").db;
const time = internal.time;
const wait = internal.wait;
const statusExternal = internal.statusExternal;
var graph_module = require("@arangodb/general-graph");
var EPS = 0.0001;
let pregel = require("@arangodb/pregel");
const graphName = "UnitTest_pregel";
const vColl = "UnitTest_pregel_v", eColl = "UnitTest_pregel_e";
function testAlgoStart(a, p) {
let pid = pregel.start(a, graphName, p);
assertTrue(typeof pid === "string");
return pid;
}
function testAlgoCheck(pid) {
let stats = pregel.status(pid);
console.warn("Pregel status:", stats);
return stats.state !== "running" && stats.state !== "storing";
}
function getServers(role) {
return global.instanceInfo.arangods.filter((instance) => instance.role === role);
};
function waitForShutdown(arangod, timeout) {
let startTime = time();
while (true) {
if (time() > startTime + timeout) {
assertTrue(false, "Instance did not shutdown quickly enough!");
return;
}
let status = statusExternal(arangod.pid, false);
console.warn("External status:", status);
if (status.status === "TERMINATED") {
arangod.exitStatus = status;
delete arangod.pid;
break;
}
wait(0.5);
}
};
function waitForAlive(timeout, baseurl, data) {
let res;
let all = Object.assign(data || {}, { method: "get", timeout: 1, url: baseurl + "/_api/version" });
const end = time() + timeout;
while (time() < end) {
res = request(all);
if (res.status === 200 || res.status === 401 || res.status === 403) {
break;
}
console.warn("waiting for server response from url " + baseurl);
wait(0.5);
}
return res.status;
};
function restartInstance(arangod) {
let options = global.testOptions;
options.skipReconnect = false;
pu.reStartInstance(options, global.instanceInfo, {});
waitForAlive(30, arangod.url, {});
};
function testSuite() {
let cn = "UnitTestSoftShutdown";
return {
setUp : function() {
db._drop(cn);
let collection = db._create(cn, {numberOfShards:2, replicationFactor:2});
for (let i = 0; i < 10; ++i) {
collection.insert({Hallo:i});
}
},
tearDown : function() {
db._drop(cn);
},
testSoftShutdownWithoutTraffic : function() {
let coordinators = getServers('coordinator');
assertTrue(coordinators.length > 0);
let coordinator = coordinators[0];
// Now use soft shutdown API to shut coordinator down:
let status = arango.GET("/_admin/shutdown");
assertFalse(status.softShutdownOngoing);
let res = arango.DELETE("/_admin/shutdown?soft=true");
assertEqual("OK", res);
status = arango.GET("/_admin/shutdown");
assertTrue(status.softShutdownOngoing);
assertEqual(0, status.AQLcursors);
assertEqual(0, status.transactions);
waitForShutdown(coordinator, 30);
restartInstance(coordinator);
},
testSoftShutdownWithAQLCursor : function() {
let coordinators = getServers('coordinator');
assertTrue(coordinators.length > 0);
let coordinator = coordinators[0];
// Create an AQL cursor:
let data = {
query: `FOR x in ${cn} RETURN x`,
batchSize: 1
};
let resp = arango.POST("/_api/cursor", data);
console.warn("Produced AQL cursor:", resp);
// Now use soft shutdown API to shut coordinator down:
let res = arango.DELETE("/_admin/shutdown?soft=true");
assertEqual("OK", res);
let status = arango.GET("/_admin/shutdown");
assertTrue(status.softShutdownOngoing);
assertEqual(1, status.AQLcursors);
assertEqual(1, status.transactions);
// It should fail to create a new cursor:
let respFailed = arango.POST("/_api/cursor", data);
assertTrue(respFailed.error);
assertEqual(503, respFailed.code);
// Now slowly read the cursor through:
for (let i = 0; i < 8; ++i) {
wait(2);
let next = arango.PUT("/_api/cursor/" + resp.id,{});
console.warn("Read document:", next);
assertTrue(next.hasMore);
}
// And the last one:
wait(2);
let next = arango.PUT("/_api/cursor/" + resp.id,{});
console.warn("Read last document:", next, "awaiting shutdown...");
assertFalse(next.hasMore);
assertFalse(next.error);
assertEqual(200, next.code);
// And now it should shut down in due course...
waitForShutdown(coordinator, 30);
restartInstance(coordinator);
},
testSoftShutdownWithAQLCursorDeleted : function() {
let coordinators = getServers('coordinator');
assertTrue(coordinators.length > 0);
let coordinator = coordinators[0];
// Create an AQL cursor:
let data = {
query: `FOR x in ${cn} RETURN x`,
batchSize: 1
};
let resp = arango.POST("/_api/cursor", data);
console.warn("Produced AQL cursor:", resp);
let status = arango.GET("/_admin/shutdown");
assertFalse(status.softShutdownOngoing);
// Now use soft shutdown API to shut coordinator down:
let res = arango.DELETE("/_admin/shutdown?soft=true");
assertEqual("OK", res);
status = arango.GET("/_admin/shutdown");
assertTrue(status.softShutdownOngoing);
assertEqual(1, status.AQLcursors);
assertEqual(1, status.transactions);
// It should fail to create a new cursor:
let respFailed = arango.POST("/_api/cursor", data);
assertTrue(respFailed.error);
assertEqual(503, respFailed.code);
// Now slowly read the cursor through:
for (let i = 0; i < 8; ++i) {
wait(2);
let next = arango.PUT("/_api/cursor/" + resp.id,{});
console.warn("Read document:", next);
assertTrue(next.hasMore);
}
// Instead of the last one, now delete the cursor:
wait(2);
let next = arango.DELETE("/_api/cursor/" + resp.id,{});
console.warn("Deleted cursor:", next, "awaiting shutdown...");
assertFalse(next.hasMore);
assertFalse(next.error);
assertEqual(202, next.code);
// And now it should shut down in due course...
waitForShutdown(coordinator, 30);
restartInstance(coordinator);
},
testSoftShutdownWithStreamingTrx : function() {
let coordinators = getServers('coordinator');
assertTrue(coordinators.length > 0);
let coordinator = coordinators[0];
// Create a streaming transaction:
let data = { collections: {write: [cn]} };
let resp = arango.POST("/_api/transaction/begin", data);
console.warn("Produced transaction:", resp);
// Now use soft shutdown API to shut coordinator down:
let status = arango.GET("/_admin/shutdown");
assertFalse(status.softShutdownOngoing);
let res = arango.DELETE("/_admin/shutdown?soft=true");
assertEqual("OK", res);
status = arango.GET("/_admin/shutdown");
assertTrue(status.softShutdownOngoing);
assertEqual(0, status.AQLcursors);
assertEqual(1, status.transactions);
// It should fail to create a new trx:
let respFailed = arango.POST("/_api/transaction/begin", data);
assertTrue(respFailed.error);
assertEqual(503, respFailed.code);
// Now wait for some seconds:
wait(10);
// And commit the transaction:
resp = arango.PUT(`/_api/transaction/${resp.result.id}`, {});
assertFalse(resp.error);
assertEqual(200, resp.code);
// And now it should shut down in due course...
waitForShutdown(coordinator, 30);
restartInstance(coordinator);
},
testSoftShutdownWithAQLStreamingTrxAborted : function() {
let coordinators = getServers('coordinator');
assertTrue(coordinators.length > 0);
let coordinator = coordinators[0];
// Create a streaming transaction:
let data = { collections: {write: [cn]} };
let resp = arango.POST("/_api/transaction/begin", data);
console.warn("Produced transaction:", resp);
let status = arango.GET("/_admin/shutdown");
assertFalse(status.softShutdownOngoing);
// Now use soft shutdown API to shut coordinator down:
let res = arango.DELETE("/_admin/shutdown?soft=true");
assertEqual("OK", res);
status = arango.GET("/_admin/shutdown");
assertTrue(status.softShutdownOngoing);
assertEqual(0, status.AQLcursors);
assertEqual(1, status.transactions);
// It should fail to create a new trx:
let respFailed = arango.POST("/_api/transaction/begin", data);
assertTrue(respFailed.error);
assertEqual(503, respFailed.code);
// Now wait for some seconds:
wait(10);
// And abort the transaction:
resp = arango.DELETE(`/_api/transaction/${resp.result.id}`);
assertFalse(resp.error);
assertEqual(200, resp.code);
// And now it should shut down in due course...
waitForShutdown(coordinator, 30);
restartInstance(coordinator);
},
testSoftShutdownWithAsyncRequest : function() {
let coordinators = getServers('coordinator');
assertTrue(coordinators.length > 0);
let coordinator = coordinators[0];
// Create a streaming transaction:
let data = { query: `RETURN SLEEP(15)` };
let resp = arango.POST_RAW("/_api/cursor", data, {"x-arango-async":"store"});
console.warn("Produced cursor asynchronously:", resp);
// Now use soft shutdown API to shut coordinator down:
let status = arango.GET("/_admin/shutdown");
assertFalse(status.softShutdownOngoing);
let res = arango.DELETE("/_admin/shutdown?soft=true");
assertEqual("OK", res);
status = arango.GET("/_admin/shutdown");
console.warn("status1:", status);
assertTrue(status.softShutdownOngoing);
assertEqual(0, status.AQLcursors);
assertEqual(1, status.transactions);
assertEqual(1, status.pendingJobs);
assertEqual(0, status.doneJobs);
assertFalse(status.allClear);
// It should fail to create a new cursor:
let respFailed = arango.POST_RAW("/_api/cursor", data, {"x-arango-async":"store"});
assertTrue(respFailed.error);
assertEqual(503, respFailed.code);
// Now wait for some seconds:
wait(20); // Let query terminate, then the job should be done
status = arango.GET("/_admin/shutdown");
console.warn("status2:", status);
assertTrue(status.softShutdownOngoing);
assertEqual(0, status.AQLcursors);
assertEqual(0, status.transactions);
assertEqual(0, status.pendingJobs);
assertEqual(1, status.doneJobs);
assertFalse(status.allClear);
// And collect the job result:
resp = arango.PUT(`/_api/job/${resp.headers["x-arango-async-id"]}`, {});
assertFalse(resp.error);
assertEqual(201, resp.code);
// And now it should shut down in due course...
waitForShutdown(coordinator, 30);
restartInstance(coordinator);
},
testSoftShutdownWithQueuedLowPrio : function() {
let coordinators = getServers('coordinator');
assertTrue(coordinators.length > 0);
let coordinator = coordinators[0];
// Create a streaming transaction:
let op = `require("internal").wait(1); return 1;`;
let jobs = [];
for (let i = 0; i < 128; ++i) {
// that is more than we have threads, so there should be a queue
let resp = arango.POST_RAW("/_admin/execute", op, {"x-arango-async":"store"});
jobs.push(resp.headers["x-arango-async-id"]);
}
console.warn("Produced 128 jobs asynchronously:", jobs);
// Now use soft shutdown API to shut coordinator down:
let status = arango.GET("/_admin/shutdown");
console.warn("status0:", status);
assertFalse(status.softShutdownOngoing);
assertTrue(status.lowPrioOngoingRequests > 0);
assertTrue(status.lowPrioQueuedRequests > 0);
let res = arango.DELETE("/_admin/shutdown?soft=true");
assertEqual("OK", res);
status = arango.GET("/_admin/shutdown");
console.warn("status1:", status);
assertTrue(status.softShutdownOngoing);
assertTrue(status.lowPrioOngoingRequests > 0);
assertTrue(status.lowPrioQueuedRequests > 0);
assertFalse(status.allClear);
// Now until all jobs are done:
let startTime = time();
while (true) {
status = arango.GET("/_admin/shutdown");
if (status.lowPrioQueuedRequests === 0 &&
status.lowPrioOngoingRequests === 0) {
break; // all good!
}
if (time() - startTime > 90) {
// 45 seconds should be enough for at least 2 threads
// to execute 128 requests, usually, it will be much faster.
assertTrue(false, "finishing jobs took too long");
}
console.warn("status2:", status);
assertTrue(status.softShutdownOngoing);
assertEqual(128, status.pendingJobs + status.doneJobs);
assertFalse(status.allClear);
wait(0.5);
}
// Now collect the job results:
for (let j of jobs) {
assertEqual(1, arango.PUT(`/_api/job/${j}`, {}));
}
status = arango.GET("/_admin/shutdown");
console.warn("status3:", status);
assertTrue(status.softShutdownOngoing);
assertEqual(0, status.pendingJobs);
assertEqual(0, status.doneJobs);
assertTrue(status.allClear);
// And now it should shut down in due course...
waitForShutdown(coordinator, 30);
restartInstance(coordinator);
},
};
}
function testSuitePregel() {
'use strict';
return {
/////////////////////////////////////////////////////////////////////////
/// @brief set up
/////////////////////////////////////////////////////////////////////////
setUp: function () {
var guck = graph_module._list();
var exists = guck.indexOf("demo") !== -1;
if (exists || db.demo_v) {
console.warn("Attention: graph_module gives:", guck, "or we have db.demo_v:", db.demo_v);
return;
}
var graph = graph_module._create(graphName);
db._create(vColl, { numberOfShards: 4 });
graph._addVertexCollection(vColl);
db._createEdgeCollection(eColl, {
numberOfShards: 4,
replicationFactor: 1,
shardKeys: ["vertex"],
distributeShardsLike: vColl
});
var rel = graph_module._relation(eColl, [vColl], [vColl]);
graph._extendEdgeDefinitions(rel);
var vertices = db[vColl];
var edges = db[eColl];
vertices.insert([{ _key: 'A', sssp: 3, pagerank: 0.027645934 },
{ _key: 'B', sssp: 2, pagerank: 0.3241496 },
{ _key: 'C', sssp: 3, pagerank: 0.289220 },
{ _key: 'D', sssp: 2, pagerank: 0.0329636 },
{ _key: 'E', sssp: 1, pagerank: 0.0682141 },
{ _key: 'F', sssp: 2, pagerank: 0.0329636 },
{ _key: 'G', sssp: -1, pagerank: 0.0136363 },
{ _key: 'H', sssp: -1, pagerank: 0.01363636 },
{ _key: 'I', sssp: -1, pagerank: 0.01363636 },
{ _key: 'J', sssp: -1, pagerank: 0.01363636 },
{ _key: 'K', sssp: 0, pagerank: 0.013636363 }]);
edges.insert([{ _from: vColl + '/B', _to: vColl + '/C', vertex: 'B' },
{ _from: vColl + '/C', _to: vColl + '/B', vertex: 'C' },
{ _from: vColl + '/D', _to: vColl + '/A', vertex: 'D' },
{ _from: vColl + '/D', _to: vColl + '/B', vertex: 'D' },
{ _from: vColl + '/E', _to: vColl + '/B', vertex: 'E' },
{ _from: vColl + '/E', _to: vColl + '/D', vertex: 'E' },
{ _from: vColl + '/E', _to: vColl + '/F', vertex: 'E' },
{ _from: vColl + '/F', _to: vColl + '/B', vertex: 'F' },
{ _from: vColl + '/F', _to: vColl + '/E', vertex: 'F' },
{ _from: vColl + '/G', _to: vColl + '/B', vertex: 'G' },
{ _from: vColl + '/G', _to: vColl + '/E', vertex: 'G' },
{ _from: vColl + '/H', _to: vColl + '/B', vertex: 'H' },
{ _from: vColl + '/H', _to: vColl + '/E', vertex: 'H' },
{ _from: vColl + '/I', _to: vColl + '/B', vertex: 'I' },
{ _from: vColl + '/I', _to: vColl + '/E', vertex: 'I' },
{ _from: vColl + '/J', _to: vColl + '/E', vertex: 'J' },
{ _from: vColl + '/K', _to: vColl + '/E', vertex: 'K' }]);
},
//////////////////////////////////////////////////////////////////////////
/// @brief tear down
//////////////////////////////////////////////////////////////////////////
tearDown: function () {
graph_module._drop(graphName, true);
},
testPageRank: function () {
let coordinators = getServers('coordinator');
assertTrue(coordinators.length > 0);
let coordinator = coordinators[0];
// Start a pregel run:
let pid = testAlgoStart("pagerank", { threshold: EPS / 1000, resultField: "result", store: true });
console.warn("Started pregel run:", pid);
// Now use soft shutdown API to shut coordinator down:
let res = arango.DELETE("/_admin/shutdown?soft=true");
console.warn("Shutdown got:", res);
assertEqual("OK", res);
let status = arango.GET("/_admin/shutdown");
assertTrue(status.softShutdownOngoing);
assertEqual(1, status.pregelConductors);
// It should fail to create a new pregel run:
let gotException = false;
try {
testAlgoStart("pagerank", { threshold: EPS / 10, resultField: "result", store: true });
} catch(e) {
console.warn("Got exception for new run, good!", JSON.stringify(e));
gotException = true;
}
assertTrue(gotException);
status = arango.GET("/_admin/shutdown");
assertTrue(status.softShutdownOngoing);
let startTime = time();
while (!testAlgoCheck(pid)) {
console.warn("Pregel still running...");
wait(0.2);
if (time() - startTime > 60) {
assertTrue(false, "Pregel did not finish in time.");
}
}
status = arango.GET("/_admin/shutdown");
assertTrue(status.softShutdownOngoing);
// And now it should shut down in due course...
waitForShutdown(coordinator, 30);
restartInstance(coordinator);
},
};
}
jsunity.run(testSuite);
jsunity.run(testSuitePregel);
return jsunity.done();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.