text
stringlengths 7
3.69M
|
|---|
export const GET_FAQS = 'GET_FAQS';
export const ADD_FAQ = 'ADD_FAQ';
export const DELETE_FAQ = 'DELETE_FAQ';
export const MODIFY_FAQ = 'MODIFY_FAQ';
export const GET_REQUESTS = 'GET_REQUESTS';
export const ADD_REQUEST = 'ADD_REQUEST';
export const DELETE_REQUEST = 'DELETE_REQUEST';
export const MODIFY_REQUEST = 'MODIFY_REQUEST';
export const GET_REQUESTS_LOCATION = 'GET_REQUESTS_LOCATION';
export const GET_OFFERS = 'GET_OFFERS';
export const ADD_OFFER = 'ADD_OFFER';
export const DELETE_OFFER = 'DELETE_OFFER';
export const MODIFY_OFFER = 'MODIFY_OFFER';
export const GET_OFFERS_LOCATION = 'GET_OFFERS_LOCATION';
export const SET_VISIBLE_FALSE = 'SET_VISIBLE_FALSE';
export const GET_TOPICS = 'GET_TOPICS';
export const ADD_TOPIC = 'ADD_TOPIC';
export const DELETE_TOPIC = 'DELETE_TOPIC';
export const ADD_CHAT = 'ADD_CHAT';
export const GET_CHATS = 'GET_CHATS';
export const GET_COURSES = 'GET_COURSES';
export const ADD_COURSE = 'ADD_COURSE';
export const DELETE_COURSE = 'DELETE_COURSE';
export const MODIFY_COURSE = 'MODIFY_COURSE';
export const GET_UNIVERSITIES = 'GET_UNIVERSITIES';
export const GET_TIPS = 'GET_TIPS';
export const ADD_TIP = 'ADD_TIP';
export const DELETE_TIP = 'DELETE_TIP';
export const GET_EVENTS = 'GET_EVENTS';
export const ADD_EVENT = 'ADD_EVENT';
export const DELETE_EVENT = 'DELETE_EVENT';
export const LOGIN = 'LOGIN';
export const SIGNUP = 'SIGNUP';
export const LOGOFF = 'LOGOFF';
export const GET_USER = 'GET_USER';
export const GET_USER_CHATS = 'GET_USER_CHATS';
export const GET_USER_OBJECTS = 'GET_USER_OBJECTS';
export const LOADING_LOGIN = 'LOADING_LOGIN';
|
const canvas = document.querySelector('#canvas')
const ctx = canvas.getContext('2d')
const data = [4, 8, 2, 3, 10]
const colors = ['orange', 'green', 'blue', 'yellow', 'teal']
let total = 0
for (let i = 0; i < data.length; i++) {
total += data[i]
}
let prevAngle = 0
for (let i = 0; i < data.length; i++) {
//fraction that this pie slice represents
const fraction = data[i] / total
//calc starting angle
const angle = prevAngle + fraction * Math.PI * 2
//draw the pie slice
ctx.fillStyle = colors[i]
//create a path
ctx.beginPath()
ctx.moveTo(250, 250)
ctx.arc(250, 250, 100, prevAngle, angle, false)
ctx.lineTo(250, 250)
//fill it
ctx.fill()
//stroke it
ctx.strokeStyle = 'black'
ctx.stroke()
//update for next time through the loop
prevAngle = angle
}
|
/*
* Pencil Model
*
* This contains defalut Pencil model.
*/
import mongoose from 'mongoose';
import { strictEqual } from 'assert';
const Schema = mongoose.Schema;
const PencilSchema = new Schema({
item: {
type: 'String',
required: false,
},
info: {
type: 'String',
required: false,
},
slug: {
type: 'String',
required: false,
},
cuid: {
type: 'String',
required: false,
},
createdBy: {
type: 'String',
required: false,
},
created_at: {
type: 'Date',
default: Date.now,
required: false,
},
});
export default mongoose.model('Pencil', PencilSchema);
|
import { mirrorPlugin } from '@freesewing/plugin-mirror'
import { base } from './base.mjs'
const pluginMirror = ({ points, Point, paths, Path, snippets, Snippet, options, macro, part }) => {
if (['mirror', 'all'].indexOf(options.plugin) !== -1) {
points.mirrorA = new Point(0, 0)
points.mirrorB = new Point(70, 30)
points.mirrorC = new Point(0, 50)
points.mirrorD = new Point(30, -30)
paths.mirrorA = new Path()
.move(points.mirrorA)
.line(points.mirrorB)
.attr('class', 'dashed note')
.attr('data-text', 'Mirror A')
.attr('data-text-class', 'right')
paths.mirrorB = new Path()
.move(points.mirrorC)
.line(points.mirrorD)
.attr('class', 'dashed note')
.attr('data-text', 'Mirror B')
.attr('data-text-class', 'right')
points.b1 = new Point(10, 10).attr('data-text', 1)
points.h2 = new Point(20, 10).attr('data-text', 2)
points.h3 = new Point(30, 10).attr('data-text', 3)
points.v2 = new Point(10, 20).attr('data-text', 2)
points.v3 = new Point(10, 30).attr('data-text', 3)
points.a = new Point(10, 0)
points.b = new Point(30, 30)
points.c = new Point(50, 50)
points.d = new Point(12, 34)
points.e = new Point(54, 34)
snippets.a = new Snippet('button', points.b)
paths.a = new Path().move(points.a).line(points.b)
paths.b = new Path().move(points.e).curve(points.a, points.d, points.c)
if (options.mirrorLine !== 'none') {
macro('mirror', {
mirror:
options.mirrorLine === 'a'
? [points.mirrorA, points.mirrorB]
: [points.mirrorC, points.mirrorD],
points: [
points.b1,
points.h2,
points.h3,
points.v2,
points.v3,
points.a,
points.b,
points.c,
points.d,
points.e,
],
paths: [paths.a, paths.b],
clone: options.mirrorClone,
})
}
}
return part
}
export const mirror = {
name: 'plugintest.mirror',
after: base,
options: {
mirrorLine: { dflt: 'a', list: ['a', 'b', 'none'], menu: 'mirror' },
mirrorClone: { bool: true, menu: 'mirror' },
},
plugins: mirrorPlugin,
draft: pluginMirror,
}
|
'use strict'
function llenartext(mensaje){
console.log(document.querySelector('#mailtext'));
document.querySelector('#mailtext').innerHTML = texto;
}
const minuto_inicial = 2;
let time = minuto_inicial * 60;
const divcont = document.getElementById("countdowd");
var temp = setInterval(updatecountdowd, 1000);
function updatecountdowd(){
const minuto = Math.floor(time / 60);
let second = time % 60;
second = second < 10 ? '0' + second : second;
divcont.innerHTML = `0${minuto} :${second} min`;
time--;
if(time == -1){
console.log(time);
clearInterval(temp);
console.log(document.getElementById("ingresar"));
}
}
|
/*
* Copyright (C) 2009-2013 SAP AG or an SAP affiliate company. All rights reserved
*/
jQuery.sap.require("sap.ca.ui.utils.resourcebundle");
sap.ui.controller("sap.ca.ui.dialog.Confirm", {
_CONFIRM_NOTE_ID: "TXA_NOTE",
_CONFIRM_BUTTON_ID: "BTN_CONFIRM",
_CONFIRM_DIALOG_ID: "DLG_CONFIRM",
_CONFIRM_VERTICALLAYOUT_SM_ID: "VLT_ADDINFO",
_CONFIRM_TEXT_EMPTYLINE: "TXT_EMPTYLINE",
_bNoteMandatory: false,
_sPreviousInput: "",
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* @memberOf About
*/
onInit: function() {
if (jQuery.device.is.phone === false) {
var oDlg = this.getView().byId(this._CONFIRM_DIALOG_ID);
oDlg.setContentWidth("25em");
}
//set visible binding
var oVerticalLayout = this.getView().byId(this._CONFIRM_VERTICALLAYOUT_SM_ID);
oVerticalLayout.bindProperty("visible", {
path:'/additionalInformation',
formatter: function(oInfo) {
return (oInfo && oInfo.length>0) ? true : false;
}
});
var oEmptyText = this.getView().byId(this._CONFIRM_TEXT_EMPTYLINE);
oEmptyText.bindProperty("visible", {
path:'/additionalInformation',
formatter: function(oInfo) {
return (oInfo && oInfo.length>0) ? false : true;
}
});
},
onBeforeOpenDialog: function(){
//remove previous note value
var oTXANote = this.getView().byId(this._CONFIRM_NOTE_ID);
oTXANote.setValue("");
this._sPreviousInput = "";
//get the noteMandatory property via model
this._bNoteMandatory = false;
var oDlgModel = this.getView().byId(this._CONFIRM_DIALOG_ID).getModel();
if (oDlgModel) {
this._bNoteMandatory = oDlgModel.getProperty("/noteMandatory");
//set the confirm button correspondingly
if (this._bNoteMandatory) {
this.enableConfirmButton(false);
oTXANote.setPlaceholder(sap.ca.ui.utils.resourcebundle.getText("YMSG_TEXT_NOTE_MANDATORY"));
} else {
this.enableConfirmButton(true);
oTXANote.setPlaceholder(sap.ca.ui.utils.resourcebundle.getText("YMSG_TEXT_NOTE"));
}
//set note visible or not
if (this._bNoteMandatory) {
oTXANote.setVisible(true);
} else {
if (oDlgModel.getProperty("/showNote")) {
oTXANote.setVisible(true);
} else {
oTXANote.setVisible(false);
}
}
}
},
onConfirmDialog: function(oEvent) {
var oTXANote = this.getView().byId(this._CONFIRM_NOTE_ID);
var oResult = {
isConfirmed: true,
sNote: oTXANote.getValue()
};
sap.ca.ui.dialog.factory.closeDialog(this._CONFIRM_DIALOG_ID, oResult);
},
onCancelDialog: function(oEvent) {
var oResult = {
isConfirmed: false
};
sap.ca.ui.dialog.factory.closeDialog(this._CONFIRM_DIALOG_ID, oResult);
},
onNoteInput: function(oEvent) {
var sNewValue = oEvent.getParameters().value?oEvent.getParameters().value:oEvent.getParameters().newValue;
sNewValue = jQuery.trim(sNewValue); //remove the starting and ending white spaces
if (sNewValue && !this._sPreviousInput) {
//set the confirm button enabled
this.enableConfirmButton(true);
} else {
if (this._sPreviousInput && !sNewValue && this._bNoteMandatory) {
//set the confirm button disabled
this.enableConfirmButton(false);
}
}
this._sPreviousInput = (sNewValue)?sNewValue:"";
},
enableConfirmButton: function(bEnabled) {
var oBTNConfirm = this.getView().byId(this._CONFIRM_BUTTON_ID);
if (oBTNConfirm.getEnabled() !== bEnabled) {
oBTNConfirm.setEnabled(bEnabled);
// if (!bEnabled) { //make the button in disabled/enabled style
// oBTNConfirm.addStyleClass("sapMBtnDisabled");
// } else {
// oBTNConfirm.removeStyleClass("sapMBtnDisabled");
// }
oBTNConfirm.rerender(); //rerender to SHOW button in the dialog is enabled/disabled
}
},
formatVisible: function(sText) {
if (sText && sText.length>0) return true;
return false;
}
/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
* @memberOf About
*/
// onBeforeRendering: function() {
//
// },
/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
* @memberOf About
*/
// onAfterRendering: function() {
//
// },
/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* @memberOf About
*/
// onExit: function() {
//
// }
});
|
// pages/mine/mine.js
const app = getApp()
Page({
data: {
userInfo:null,
},
login:function(e){
this.verifyLogin().then(()=>{
let userInfo = e.detail.userInfo
if (userInfo){
app.globalData.UserInfo = userInfo;
this.setData({
userInfo:userInfo
})
}
})
},
getUserInfo:function(){
wx.getUserInfo({
success: (res) => {
let userInfo = res.userInfo
if (userInfo){
app.globalData.UserInfo = userInfo;
this.setData({
userInfo:userInfo
})
}
},
})
},
verifyLogin:function(){
return new Promise((resolve,reject)=>{
wx.login({
success(res){
if(res.errMsg.split(":")[1] == 'ok'){
resolve(res.code)
}else{
reject()
}
}
})
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.checkSession({
success: (res) => {
this.getUserInfo()
},
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
var firebase = require("firebase/app");
var admin = require("firebase-admin");
let db = admin.firestore();
exports.isAdmin = function (req, res, next) {
var user = firebase.auth().currentUser;
if (user) {
if (user.uid === 'YnakLXc4V7ZVuRIAoG79Hj1Q33t1' || user.uid === 'FKDn7vzAwShERQ0haNRwnDIs7ju1') {
const userDoc = db.collection('users').doc(user.uid);
userDoc.get()
.then(doc => {
const user = doc.data();
req.user = user;
next();
})
} else {
// res.render('getLogin', { showLogOutBtn: false, currentUser : '' });
req.user = '';
next();
}
} else {
// next();
res.render('getLogin', { showLogOutBtn: false, currentUser : '' });
}
}
|
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import actions from '../actions';
import Card from 'material-ui/lib/card/card';
import CardText from 'material-ui/lib/card/card-text';
import RaisedButton from 'material-ui/lib/raised-button';
class Login extends Component {
static propTypes = {
loginError: PropTypes.string,
onLogIn: PropTypes.func.isRequired
}
render() {
return (
<Card style={{
maxWidth: '800px',
margin: '30px auto',
padding: '50px'
}}>
<CardText style={{
textAlign: 'center'
}}>
{this.props.loginError}
To start chatting away, please log in with your Google account.
</CardText>
<RaisedButton style={{
display: 'block'
}} onClick={this.props.onLogIn} label="Log in with Google" primary />
</Card>
);
}
}
function select(state) {
return {
loginError: state.auth.loginError
};
}
const bindActions = {
onLogIn: actions.authLoginRequest
};
export default connect(select, bindActions)(Login);
|
// pages/look_car_detail_02/look_car_detail_02.js
const mta = require('../../utils/public/mta_analysis.js')
const tool = require('../../utils/tool/tool.js')
const request_01 = require('../../utils/request/request_01.js');
const method = require('../../utils/tool/method.js');
const router = require('../../utils/tool/router.js');
const authorization = require('../../utils/tool/authorization.js');
const alert = require('../../utils/tool/alert.js');
const api = require('../../utils/request/request_03.js');
const app = getApp(); //获取应用实例
let time = null;
Page({
/**
* 页面的初始数据
*/
data: {
IMGSERVICE: app.globalData.IMGSERVICE,
options: {},
navIndex: 0,
lookCarDetail: {},
isShowForm: false,
formsType: 2,
vehicle: {},
car_type_list_index: 0,
car_details: [],
scrollTop: 0,
isSwitchIng: false,
isPlayVedio: false,
videoUrl: '',
iconList: [
{ img: app.globalData.IMGSERVICE + '/car_detail/icon_01.png', url: '/pages/bargain_index/bargain_index?activity_id=47' },
{ img: app.globalData.IMGSERVICE + '/car_detail/icon_02.png', url: '/pages/assemble/pin/pin?activity_id=44' },
{ img: app.globalData.IMGSERVICE + '/car_detail/icon_03s.png', url: '/pages/index/index' }
],
carcol: [ //t60颜色图
{ img: 't60_col1.png', txt: '旭日橙/珠光白双色' },
{ img: 't60_col2.png', txt: '烈焰红/曜石黑双色' },
{ img: 't60_col3.png', txt: '珠光白/曜石黑双色' },
{ img: 't60_col4.png', txt: '烈焰红' },
{ img: 't60_col5.png', txt: '曜石黑' },
{ img: 't60_col6.png', txt: '钨钢灰' },
{ img: 't60_col7.png', txt: '旭日橙' },
{ img: 't60_col8.png', txt: '晴空蓝' },
{ img: 't60_col9.png', txt: '珠光白' }
],
t70carcol: [ //t70颜色图
{ img: 't70bg6.png', txt: '旭日橙' },
{ img: 't70bg7.png', txt: '朝霞红' },
{ img: 't70bg8.png', txt: '珠光白' },
{ img: 't70bg9.png', txt: '翡丽灰' },
{ img: 't70bg10.png', txt: '曜石黑' }
],
d60carcol: [ //t70颜色图
{ img: 'd60col1.png', txt: '晴空蓝' },
{ img: 'd60col2.png', txt: '映日棕' },
{ img: 'd60col3.png', txt: '辰辉银' },
{ img: 'd60col4.png', txt: '赤兔红' },
{ img: 'd60col5.png', txt: '珠光白' },
{ img: 'd60col6.png', txt: '曜石黑' }
],
swiper1: 0, //控制第一个swiper
swiper2: 0, //控制第二个swiper
swiper3: 0, //控制第三个swiper
swiper4: 0, //控制t70第1个swiper
swiper5: 0, //控制t70第2个swiper
swiper6: 0, //控制t70第3个swiper
swiper7: 0, //控制t70第4个swiper
swiper8: 0, //控制t70第5个swiper
swiper9: 0, //控制d60第1个swiper
swiper10: 0, //控制d60第2个swiper
swiper11: 0, //控制d60第3个swiper
swiper12: 0,
rogincol: 0, //初始选择的颜色
carid: '',
swiper1_txt: ['共享全球供应商体系', '日产HR16发动机', '日产XTRONIC CVT无级变速器', 'Zone Body区域组合+1200Mpa高强钢车身','ASCD定速巡航', 'HSA上坡起步辅助系统', '博世9.1版ESP车身电子稳定系统', '日产同平台开发生产'], //部件名称
swiper2_txt: ['“星耀式” LED光导尾灯', '“星航” 投射式LED前大灯', '17英寸切削铝合金轮辋', '悬浮式车顶', '全景天窗', '科技范高质感内饰', 'Multi-Layer人体工学座椅', '“星空点阵式” 启辰家族前格栅'], //部件名称
swiper3_txt: ['AEB自主紧急制动系统', 'BSW变道盲区预警系统', 'LDW车道偏离预警系统', '多场景远程控制', '远程控制车辆', '智能语音助手', '10+8英寸大尺寸智能双屏交互', '智能全时导航'], //部件名称
t70_swiper1_txt: ['LED光扩散粒子后尾灯', '18英寸铝合金双色切割工艺轮辋', '钻石绗缝皮质座椅', '丰富的收纳空间', '10.1英寸高清多点触控屏', '炮筒式高清晰组合仪表盘', '多功能D型真皮方向盘(带控制键)', '投射式鹰眼前大灯'], //部件名称
t70_swiper2_txt: ['全时在线导航', '智慧语音助手', '手机远程控制', '数字化车联&互联网信息娱乐', '车辆智能安防体系', '异常诊断手机提醒 '], //部件名称
t70_swiper3_txt: ['流媒体后视镜', '3D全景式监控影像系统', '后视镜自动折叠', 'TPMS胎压监测系统', '智能电动尾门'], //部件名称
t70_swiper4_txt: ['先进的XTRONIC CVT无级变速器', '多连杆独立后悬挂', 'ESP车身电子稳定系统', '日产全球战略引擎MR20发动机', '先进的XTRONIC CVT无级变速器', '多连杆独立后悬挂', 'ESP车身电子稳定系统', '日产全球战略引擎MR20发动机'], //部件名称
t70_swiper5_txt: ['专业制造工艺', 'ABS+EBD+BA三位一体智能刹车辅助系统', 'ESS紧急制动提醒系统', 'ATC主动循迹控制系统', '雷诺-日产-三菱联盟品质标准'], //部件名称
d60_swiper1_txt: ['车辆智能安防系统', '在线娱乐系统', '智能人机语音交互', '手机远程控制', '车载W i f i热点', '人性化贴心全时导航'], //部件名称
d60_swiper2_txt: ['宽敞大尺寸天窗', 'Multi-Layer人体工学座椅', '663mm后排膝部空间', '宽敞大尺寸天窗', 'Multi-Layer人体工学座椅', '663mm后排膝部空间'], //部件名称
d60_swiper3_txt: ['锐利的鹰眼LED前大灯', '星空点阵式前格栅', '红镰式光导LED组合尾灯', '驾驶员导向飞航式驾驶舱设计', '人体工学D型多功能方向盘', '高品质透气性菱格皮质座椅', '4756mm优越车身长度'], //部件名称
d60_swiper4_txt: ['XTRONIC CVT无级变速器', '5.6L/100km低油耗', '带横向稳定杆的扭力梁式悬挂系统', 'Zone Body高性能区域车身结构', 'ABS+EBD+BA三位一体智能刹车辅助系统', '博世9.1版ESP车身电子稳定系统', 'TPMS智能胎压监测系统', 'EPKB电子驻车系统', 'HR16发动机'], //部件名称
swp1_img: [ //t60第一个swiper资源
{ img: 'Tb60_sw1.png', type: 1 },
{ img: 'Tb60_sw2.png', type: 2, vUrl: "Tb60_sw2.mp4"},
{ img: 'Tb60_sw3.png', type: 2, vUrl: "Tb60_sw3.mp4"},
{ img: 'Tb60_sw4.png', type: 2, vUrl: "Tb60_sw5.mp4"},
// { img: 'Tb60_sw5.png', type: 1},
{ img: 'Tb60_sw6.png?2', type: 1 },
{ img: 'Tb60_sw7.png', type: 2, vUrl: "Tb60_sw7.mp4"},
{ img: 'Tb60_sw8.png', type: 2, vUrl: "Tb60_sw8.mp4"},
{ img: 'Tb60_sw9.png', type: 1}
],
swp3_img: [ //t60第三个swiper资源
{ img: 'Tb60_sw3_1.png', type: 2, vUrl: "Tb60_sw3_1.mp4"},
{ img: 'Tb60_sw3_2.png', type: 2, vUrl: "Tb60_sw3_2.mp4"},
{ img: 'Tb60_sw3_3.png', type: 2, vUrl: "Tb60_sw3_3.mp4"},
{ img: 'Tb60_sw3_5.png', type: 2, vUrl: "Tb60_sw3_5.mp4"},
{ img: 'Tb60_sw3_6.png', type: 2, vUrl: "Tb60_sw3_6.mp4"},
{ img: 'Tb60_sw3_7.png', type: 2, vUrl: "Tb60_sw3_7.mp4"},
{ img: 'Tb60_sw3_8.png', type: 2, vUrl: "Tb60_sw3_8.mp4"},
{ img: 'Tb60_sw3_9.png', type: 2, vUrl: "Tb60_sw3_9.mp4"}
],
t70_swiper2_img: [ // t70第二个swiper
{ img: 'tb70_2_6.png', type: 2, vUrl: "tb70_2_6.mp4" },
{ img: 'tb70_2_3.png', type: 2, vUrl: "tb70_2_3.mp4" },
{ img: 'tb70_2_4.png', type: 2, vUrl: "tb70_2_4.mp4" },
{ img: 'tb70_2_1.png', type: 2, vUrl: "tb70_2_1.mp4" },
{ img: 'tb70_2_2.png', type: 2, vUrl: "tb70_2_2.mp4" },
{ img: 'tb70_2_5.png', type: 2, vUrl: "tb70_2_5.mp4" }
],
t70_swiper2_imgs: [ // t70第二个swiper 的小轮播图
{ img: 'tb70_2_5.png', type: 2, vUrl: "tb70_2_5.mp4" },
{ img: 'tb70_2_6.png', type: 2, vUrl: "tb70_2_6.mp4" },
{ img: 'tb70_2_3.png', type: 2, vUrl: "tb70_2_3.mp4" },
{ img: 'tb70_2_4.png', type: 2, vUrl: "tb70_2_4.mp4" },
{ img: 'tb70_2_1.png', type: 2, vUrl: "tb70_2_1.mp4" },
{ img: 'tb70_2_2.png', type: 2, vUrl: "tb70_2_2.mp4" }
],
isplay: false, // 是否在播放视频
vbtn: true, // 是否显示 播放按钮
popstu: 1, // 留资弹窗状态
curvio: null, // 当前创建的video
_currxl:0,//开车门当前序列帧
id:null,
v:102
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
// console.log(options);
this.setData({ carid: options.id })
mta.Page.init() //腾讯统计
mta.Event.stat("look_car_other", {})
this.setData({ id: options.id })
if (wx.getStorageSync("shareIds").channel_id) mta.Event.stat("channel_sunode", { channelid: wx.getStorageSync("shareIds").channel_id })
request_01.login(() => {
this.initData(options)
})
//是否显示最新icon
this.setData({ isShowIcon: 1 })
api.isShowIcon().then(res => {
console.log("显示icon返回", res)
this.setData({ isShowIcon: res.data.data })
console.log("isShowIcon", this.data.isShowIcon)
})
// this.xlfuc();
},
//两个icon动画
aimateInit() {
if (this.data.isAnimate) return
clearInterval(this.data.animateInit)
this.data.animateInit = setInterval(() => {
this.setData({ isAnimate: true })
setTimeout(res => {
this.setData({ isAnimate: false });
}, 800)
}, 3000)
},
onShow() {
this.aimateInit()
},
onHide() {
clearInterval(time);
clearInterval(this.data.animateInit);
},
onUnload() {
clearInterval(time);
clearInterval(this.data.animateInit);
},
//选择车款
bindRegionChange(e) {
if (this.data.car_type_list_index == e.detail.value) return
this.setData({ isSwitchIng: true })
tool.loading("")
setTimeout(() => {
tool.loading_h()
this.data.car_type_list_index = e.detail.value
tool.alert(`当前级别:${this.data.lookCarDetail.car_details[this.data.car_type_list_index].name}`)
this.car_details()
}, 800)
},
//当前车款配置
car_details() {
this.setData({
car_details: this.data.lookCarDetail.car_details[this.data.car_type_list_index].values,
isIconShow: true,
isSwitchIng: false
})
// tool.loading_h()
},
//页面初始化
initData(options) {
// tool.loading("加载中")
console.log("---", options.id);
Promise.all([
request_01.lookCarDetail({
user_id: wx.getStorageSync('userInfo').user_id,
id: options.id,
})
])
.then((value) => {
//success
const lookCarDetail = value[0].data.data;
this.setData({
lookCarDetail,
car_type_list: lookCarDetail.car_type_list
})
wx.setNavigationBarTitle({
title: this.data.lookCarDetail.car_name
})
this.car_details()
})
.catch((reason) => {
//fail
})
.then(() => {
//complete
this.setData({
options,
})
})
},
//详情图片加载完成
bindload() {
// tool.loading_h()
},
//导航列表
navList(e) {
const index = e.currentTarget.dataset.index;
const navIndex = this.data.navIndex;
if (navIndex == index) return;
this.setData({
navIndex: index,
})
this.setData({ scrollTop: 0 })
},
//立即下定
downPayment() {
const lookCarDetail = this.data.lookCarDetail;
console.log("lookCarDetail", lookCarDetail)
this.setData({
vehicle: {
img: lookCarDetail.car_img,
title: lookCarDetail.car_name,
price: lookCarDetail.car_prize,
},
isShowForm: true,
})
},
//留资弹窗打开、关闭
isShowForm() {
this.setData({
isShowForm: false,
})
},
//提交
submit(e) {
const detail = e.detail;
const userInfo = wx.getStorageSync('userInfo');
const lookCarDetail = this.data.lookCarDetail;
alert.loading({
str: '提交中'
})
request_01.lookCarSubmit({
user_id: userInfo.user_id, //用户ID
look_car_id: lookCarDetail.look_car_id, //看车ID
name: detail.name, //留资姓名
mobile: detail.phone, //留资电话
v_code: detail.code || '', //短信验证码
dl_code: detail.storeCode, //专营店编码
car_type: '', //车型 可不填
}).then((value) => {
//success
const status = value.data.status;
if (status == 1) {
alert.loading_h()
// mta.Event.stat("booking_car_other", { name: detail.name, phone: detail.phone, city: detail.region.join('--') })
{ userinfo: `${detail.name} ${detail.phone} ${detail.region.join('--')}` }
alert.confirm({ title: "预约成功", content: `您已成功预约的试驾,稍后将有工作人员联系您,请保持电话畅通。`, confirms: "好的,#0C5AC0", cancels: false }).then(res => {
this.setData({
isShowForm: false,
})
})
} else {
alert.alert({
str: value.data.msg,
})
}
})
.catch(() => {
//fail
alert.loading_h()
})
.then(() => {
//complete
})
},
//页面跳转
jump(e) {
tool.jump_nav(e.currentTarget.dataset.url)
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
let id = this.data.id;
let txt = '';
let imageUrl = '';
switch (id) {
case '11':
txt = '启辰星,A+级SUV头等舱,“混元”美学的秘密,等你来探索!';
imageUrl = `${this.data.IMGSERVICE}/gaiban/`
break;
case '6':
txt = '启辰T60,高品质智趣SUV,星级品质,焕新登场!';
imageUrl = `${this.data.IMGSERVICE}/gaiban/share_T60.png?1`
break;
case '3':
txt = '启辰D60,高品质智联家轿,智联生活,即刻开启!';
imageUrl = `${this.data.IMGSERVICE}/gaiban/share_D60.png`
break;
case '9':
txt = '全新启辰T90,高品质跨界SUV,跨有界,悦无限!';
imageUrl = `${this.data.IMGSERVICE}/gaiban/share_T90.png`
break;
case '7':
txt = '启辰T70,高品质智联SUV,品质来袭!';
imageUrl = `${this.data.IMGSERVICE}/gaiban/share_T70.png`
break;
case '5':
txt = '启辰D60EV,长续航合资纯电家轿,智无忧,趣更远!';
imageUrl = `${this.data.IMGSERVICE}/gaiban/share_D60EV.png`
break;
case '10':
txt = '启辰e30,我的第一台纯电精品车,智在灵活,趣动精彩!';
imageUrl = `${this.data.IMGSERVICE}/gaiban/share_E30.png`
break;
case '13':
txt = '启辰T60EV,智领合资纯电SUV,智无忧,趣更远!';
imageUrl = `${this.data.IMGSERVICE}/gaiban/share_T60EV.png`
break;
}
return {
title: `${txt}`,
path: `/pages/look_car_detail_04/look_car_detail_04?id=${this.data.id}`,
imageUrl: imageUrl
}
},
moreBtn() {
tool.jump_red("/pages/index/index")
},
swiperchange(e) { // 滑动切换 swiper
// console.log(e);
let type = e.currentTarget.dataset.type;
this.setData({
vbtn: true,
swiper1: type == 1 ? e.detail.current : this.data.swiper1,
swiper2: type == 2 ? e.detail.current : this.data.swiper2,
swiper3: type == 3 ? e.detail.current : this.data.swiper3,
swiper4: type == 4 ? e.detail.current : this.data.swiper4,
swiper5: type == 5 ? e.detail.current : this.data.swiper5,
swiper6: type == 6 ? e.detail.current : this.data.swiper6,
swiper7: type == 7 ? e.detail.current : this.data.swiper7,
swiper8: type == 8 ? e.detail.current : this.data.swiper8,
swiper9: type == 9 ? e.detail.current : this.data.swiper9,
swiper10: type == 10 ? e.detail.current : this.data.swiper10,
swiper11: type == 11 ? e.detail.current : this.data.swiper11,
swiper12: type == 12 ? e.detail.current : this.data.swiper12,
})
console.log(this.data.swiper7);
console.log(this.data.swiper1, this.data.swiper2);
},
changecol(e) { // 选择车子颜色
let index = e.currentTarget.dataset.index;
this.setData({ rogincol: index })
console.log(index)
},
// 播放视频
setplay(e) {
console.log(e.currentTarget.dataset.vurl)
if (e.currentTarget.dataset.vurl.indexOf("mp4")==-1)return;
this.setData({
isplay: true,
});
setTimeout(() => {
this.setData({
videoUrl: e.currentTarget.dataset.vurl
})
this.isOpenVideo()
}, 1000);
console.log('2', this.data.isplay);
},
// 视频播放弹窗开关
isOpenVideo() {
this.setData({
isPlayVedio: !this.data.isPlayVedio,
isplay: false,
})
},
//播放
videoPlay() {
console.log('开始播放')
// var videoplay = wx.createVideoContext()
this.data.curvio.play()
},
// 暂停播放
videoPause() {
console.log('暂停播放')
// var videoplay = wx.createVideoContext()
this.data.curvio.pause()
},
// 显示播放按钮
showplay() {
if (this.data.vbtn) return;
this.setData({ vbtn: true })
setTimeout(() => {
this.setData({ vbtn: false })
}, 3000)
},
changetab(e) { // 点击左右切换轮播
let id = e.currentTarget.dataset.id;
let type = e.currentTarget.dataset.type;
let len = e.currentTarget.dataset.length;
console.log(id, type);
this.setData({
swiper1: id == 1 && type == 1 ? this.data.swiper1 == 0 ? len : --this.data.swiper1 : id == 1 && type == 2 ? this.data.swiper1 == len ? 0 : ++this.data.swiper1 : this.data.swiper1,
swiper2: id == 2 && type == 1 ? this.data.swiper2 == 0 ? len : --this.data.swiper2 : id == 2 && type == 2 ? this.data.swiper2 == len ? 0 : ++this.data.swiper2 : this.data.swiper2,
swiper3: id == 3 && type == 1 ? this.data.swiper3 == 0 ? len : --this.data.swiper3 : id == 3 && type == 2 ? this.data.swiper3 == len ? 0 : ++this.data.swiper3 : this.data.swiper3,
swiper4: id == 4 && type == 1 ? this.data.swiper4 == 0 ? len : --this.data.swiper4 : id == 4 && type == 2 ? this.data.swiper4 == len ? 0 : ++this.data.swiper4 : this.data.swiper4,
swiper5: id == 5 && type == 1 ? this.data.swiper5 == 0 ? len : --this.data.swiper5 : id == 5 && type == 2 ? this.data.swiper5 == len ? 0 : ++this.data.swiper5 : this.data.swiper5,
swiper6: id == 6 && type == 1 ? this.data.swiper6 == 0 ? len : --this.data.swiper6 : id == 6 && type == 2 ? this.data.swiper6 == len ? 0 : ++this.data.swiper6 : this.data.swiper6,
swiper7: id == 7 && type == 1 ? this.data.swiper7 == 0 ? len : --this.data.swiper7 : id == 7 && type == 2 ? this.data.swiper7 == len ? 0 : ++this.data.swiper7 : this.data.swiper7,
swiper8: id == 8 && type == 1 ? this.data.swiper8 == 0 ? len : --this.data.swiper8 : id == 8 && type == 2 ? this.data.swiper8 == len ? 0 : ++this.data.swiper8 : this.data.swiper8,
swiper9: id == 9 && type == 1 ? this.data.swiper9 == 0 ? len : --this.data.swiper9 : id == 9 && type == 2 ? this.data.swiper9 == len ? 0 : ++this.data.swiper9 : this.data.swiper9,
swiper10: id == 10 && type == 1 ? this.data.swiper10 == 0 ? len : --this.data.swiper10 : id == 10 && type == 2 ? this.data.swiper10 == len ? 0 : ++this.data.swiper10 : this.data.swiper10,
swiper11: id == 11 && type == 1 ? this.data.swiper11 == 0 ? len : --this.data.swiper11 : id == 11 && type == 2 ? this.data.swiper11 == len ? 0 : ++this.data.swiper11 : this.data.swiper11,
swiper12: id == 12 && type == 1 ? this.data.swiper12 == 0 ? len : --this.data.swiper12 : id == 12 && type == 2 ? this.data.swiper12 == len ? 0 : ++this.data.swiper12 : this.data.swiper12,
})
},
closelz() {// 关闭填写
this.setData({ popstu: 2 })
},
tabSwiper(e){// 点击精准切换
let type = e.currentTarget.dataset.type;
let tab = e.currentTarget.dataset.tab;
let len = e.currentTarget.dataset.len-1;
console.log(type,tab,len);
this.setData({
swiper1: type == 1 ? (tab == -1 ? len : tab) : this.data.swiper1,
swiper2: type == 2 ? (tab == -1 ? len : tab) : this.data.swiper2,
swiper3: type == 3 ? (tab == -1 ? len : tab) : this.data.swiper3,
swiper4: type == 4 ? (tab == -1 ? len : tab) : this.data.swiper4,
swiper5: type == 5 ? (tab == -1 ? len : tab) : this.data.swiper5,
swiper6: type == 6 ? (tab == -1 ? len : tab) : this.data.swiper6,
swiper7: type == 7 ? (tab == -1 ? len : tab) : this.data.swiper7,
swiper8: type == 8 ? (tab == -1 ? len : tab) : this.data.swiper8,
swiper9: type == 9 ? (tab == -1 ? len : tab) : this.data.swiper9,
swiper10: type == 10 ? (tab == -1 ? len : tab) : this.data.swiper10,
swiper11: type == 11 ? (tab == -1 ? len : tab) : this.data.swiper11,
swiper12: type == 12 ? (tab == -1 ? len : tab) : this.data.swiper12,
})
},
xlfuc(){// 控制序列帧
let currxl = 0;
clearInterval(time);
time = setInterval(()=>{
if (currxl==3)currxl=0;
this.setData({ _currxl:currxl});
++currxl;
console.log(this.data._currxl);
},1000)
}
})
|
import PlanePRG from 'gl/programs/plane';
import Plane from 'gl/geoms/quad';
import GUI from 'dev/gui';
var prg = null;
export default class LightMap {
constructor(gl, texture){
this.gl = gl;
if(prg == null){
prg = PlanePRG(gl);
}
this.geom = Plane();
this.uvs = this.geom.uvs;
this.prg = prg;
// Setting up default buffers
this.verticesBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.verticesBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.geom.vertices, gl.STATIC_DRAW);
this.verticesBuffer.itemSize = this.geom.itemSize;
this.verticesBuffer.numItems = this.geom.vertices.length / this.geom.itemSize;
if(this.uvs){
this.textureBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.textureBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW);
}
this.prg.use();
this.exposure = 0.52;
this.decay = 0.95;
this.density = 1;
this.weight = 0.24;
this.lightPositionOnScreen = {
x: 0.5,
y: 0.5
};
this.prg.exposure( this.exposure );
this.prg.decay( this.decay );
this.prg.density( this.density );
this.prg.weight( this.weight );
var ctrl = GUI.addFolder('ambient');
ctrl.add(this, 'exposure', 0, 1);
ctrl.add(this, 'decay', 0, 2);
ctrl.add(this, 'density', 0, 1);
ctrl.add(this, 'weight', 0, 1);
this.texture = texture;
}
render(camera, lights){
let gl = this.gl;
if(lights){
return;
}
this.prg.use();
gl.disable(gl.DEPTH_TEST);
gl.blendFunc(gl.ONE, gl.ONE);
gl.bindBuffer(gl.ARRAY_BUFFER, this.verticesBuffer);
gl.enableVertexAttribArray( this.prg.aVertexPosition() );
gl.vertexAttribPointer( this.prg.aVertexPosition(), this.verticesBuffer.itemSize, gl.FLOAT, false, 0, 0 );
if(this.textureBuffer){
gl.bindBuffer(gl.ARRAY_BUFFER, this.textureBuffer);
gl.enableVertexAttribArray( this.prg.aUv() );
gl.vertexAttribPointer( this.prg.aUv(), 2, gl.FLOAT, false, 0, 0 );
}
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.uniform1i(this.prg.program.uSampler, 0);
this.prg.exposure( this.exposure );
this.prg.decay( this.decay );
this.prg.density( this.density );
this.prg.weight( this.weight );
gl.drawArrays(gl.TRIANGLE_STRIP, 0, this.verticesBuffer.numItems);
gl.enable(gl.DEPTH_TEST);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
}
}
|
import React, { Component } from 'react';
export default class extends Component {
constructor(props) {
super(props);
}
handleChange = (e) => {
const { onChange } = this.props;
onChange && onChange(e.target.value);
}
render() {
const { name, value } = this.props;
return (
<textarea
name={name}
value={value}
onChange={this.handleChange}
/>
)
}
}
|
'use strict';
var Q = require('q');
var path = require('path');
var chalk = require('chalk');
var cps = require('cps-api');
var cpsData = require('./apidata');
var cpsConn = new cps.Connection(cpsData.url, cpsData.dbName, cpsData.username, cpsData.password, "document", "document/id", cpsData.account);
//mongo stuff
var DATABASE_URI = require(path.join(__dirname, '../env')).DATABASE_URI;
//mongo stuff
var mongoose = require('mongoose');
var db = mongoose.connect(DATABASE_URI).connection;
// Require our models -- these should register the model into mongoose
// so the rest of the application can simply call mongoose.model('User')
// anywhere the User model needs to be used.
require('./models/user');
var startDbPromise = new Q(function (resolve, reject) {
cpsConn.on('open', resolve);
cpsConn.on('error', reject);
});
console.log(chalk.yellow('Opening connection to Clusterpoint . . .'));
startDbPromise.then(function () {
console.log(chalk.green('Clusterpoint connection opened!'));
});
module.exports = {
startDbPromise: startDbPromise,
cpsConn : cpsConn
};
|
const FenwickTree = require('../fenwickTree')
test("should create fenwick tree of correct size", () => {
const f = new FenwickTree(5)
expect(f.size).toBe(5 + 1)
for (let i = 0; i < 5; i += 1) {
expect(f.treeArray[i]).toBe(0)
}
const f2 = new FenwickTree(499)
expect(f2.size).toBe(499 + 1)
})
describe("create and insert", () => {
it('should create correct tree', function () {
const inputArray = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3];
const f = new FenwickTree(inputArray.length)
expect(f.size).toBe(inputArray.length + 1)
inputArray.forEach((value, index) => {
f.increase(index + 1, value)
})
expect(f.toString()).toBe("0,3,5,-1,10,5,9,-3,19,7,9,3")
expect(f.query(1)).toBe(3)
expect(f.query(2)).toBe(5)
expect(f.query(3)).toBe(4)
expect(f.query(4)).toBe(10)
expect(f.query(5)).toBe(15)
expect(f.query(6)).toBe(19)
expect(f.query(7)).toBe(16)
expect(f.query(8)).toBe(19)
expect(f.query(9)).toBe(26)
expect(f.query(10)).toBe(28)
expect(f.query(11)).toBe(31)
expect(f.queryRange(1, 1)).toBe(3)
expect(f.queryRange(1, 2)).toBe(5)
expect(f.queryRange(2, 4)).toBe(7)
expect(f.queryRange(6, 9)).toBe(11)
f.increase(3, 1)
expect(f.query(1)).toBe(3)
expect(f.query(2)).toBe(5)
expect(f.query(3)).toBe(5)
expect(f.query(4)).toBe(11)
expect(f.query(5)).toBe(16)
expect(f.query(6)).toBe(20)
expect(f.query(7)).toBe(17)
expect(f.query(8)).toBe(20)
expect(f.query(9)).toBe(27)
expect(f.query(10)).toBe(29)
expect(f.query(11)).toBe(32)
expect(f.queryRange(1, 1)).toBe(3)
expect(f.queryRange(1, 2)).toBe(5)
expect(f.queryRange(2, 4)).toBe(8)
expect(f.queryRange(6, 9)).toBe(11)
})
it('should correctly execute queries', () => {
const tree = new FenwickTree(5)
tree.increase(1, 4)
tree.increase(3, 7)
expect(tree.query(1)).toBe(4)
expect(tree.query(3)).toBe(11)
expect(tree.query(5)).toBe(11)
expect(tree.queryRange(2, 3)).toBe(7)
tree.increase(2, 5)
expect(tree.query(5)).toBe(16)
tree.increase(1, 3)
expect(tree.queryRange(1, 1)).toBe(7)
expect(tree.query(5)).toBe(19)
expect(tree.queryRange(1, 5)).toBe(19)
})
it("should create tree from array", () => {
const inputArray = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3];
const f = FenwickTree.fromArray(inputArray)
expect(f.size).toBe(inputArray.length + 1)
expect(f.toString()).toBe("0,3,5,-1,10,5,9,-3,19,7,9,3")
expect(f.query(1)).toBe(3)
expect(f.query(2)).toBe(5)
expect(f.query(3)).toBe(4)
expect(f.query(4)).toBe(10)
expect(f.query(5)).toBe(15)
expect(f.query(6)).toBe(19)
expect(f.query(7)).toBe(16)
expect(f.query(8)).toBe(19)
expect(f.query(9)).toBe(26)
expect(f.query(10)).toBe(28)
expect(f.query(11)).toBe(31)
expect(f.queryRange(1, 1)).toBe(3)
expect(f.queryRange(1, 2)).toBe(5)
expect(f.queryRange(2, 4)).toBe(7)
expect(f.queryRange(6, 9)).toBe(11)
f.increase(3, 1)
expect(f.query(1)).toBe(3)
expect(f.query(2)).toBe(5)
expect(f.query(3)).toBe(5)
expect(f.query(4)).toBe(11)
expect(f.query(5)).toBe(16)
expect(f.query(6)).toBe(20)
expect(f.query(7)).toBe(17)
expect(f.query(8)).toBe(20)
expect(f.query(9)).toBe(27)
expect(f.query(10)).toBe(29)
expect(f.query(11)).toBe(32)
expect(f.queryRange(1, 1)).toBe(3)
expect(f.queryRange(1, 2)).toBe(5)
expect(f.queryRange(2, 4)).toBe(8)
expect(f.queryRange(6, 9)).toBe(11)
})
it('should throw exceptions', () => {
const tree = new FenwickTree(5)
const increaseAtInvalidLowIndex = () => {
tree.increase(0, 1)
};
const increaseAtInvalidHighIndex = () => {
tree.increase(10, 1)
};
const queryInvalidLowIndex = () => {
tree.query(0)
};
const queryInvalidHighIndex = () => {
tree.query(10)
};
const rangeQueryInvalidIndex = () => {
tree.queryRange(3, 2)
};
expect(increaseAtInvalidLowIndex).toThrowError()
expect(increaseAtInvalidHighIndex).toThrowError()
expect(queryInvalidLowIndex).toThrowError()
expect(queryInvalidHighIndex).toThrowError()
expect(rangeQueryInvalidIndex).toThrowError()
})
})
|
import { ResizeSensor } from 'css-element-queries';
import PropTypes from 'prop-types';
import React, { useEffect, useRef, useState } from 'react';
const propTypes = {
handleSize: PropTypes.number,
handle: PropTypes.node,
hover: PropTypes.bool,
leftImage: PropTypes.string.isRequired,
leftImageAlt: PropTypes.string,
leftImageCss: PropTypes.object, // eslint-disable-line
leftImageLabel: PropTypes.string,
onSliderPositionChange: PropTypes.func,
rightImage: PropTypes.string.isRequired,
rightImageAlt: PropTypes.string,
rightImageCss: PropTypes.object, // eslint-disable-line
rightImageLabel: PropTypes.string,
skeleton: PropTypes.element,
sliderLineColor: PropTypes.string,
sliderLineWidth: PropTypes.number,
sliderPositionPercentage: PropTypes.number,
};
const defaultProps = {
handleSize: 40,
handle: null,
hover: false,
leftImageAlt: '',
leftImageCss: {},
leftImageLabel: null,
onSliderPositionChange: () => {},
rightImageAlt: '',
rightImageCss: {},
rightImageLabel: null,
skeleton: null,
sliderLineColor: '#ffffff',
sliderLineWidth: 2,
sliderPositionPercentage: 0.5,
};
function ReactCompareImage(props) {
const {
handleSize,
handle,
hover,
leftImage,
leftImageAlt,
leftImageCss,
leftImageLabel,
onSliderPositionChange,
rightImage,
rightImageAlt,
rightImageCss,
rightImageLabel,
skeleton,
sliderLineColor,
sliderLineWidth,
sliderPositionPercentage,
} = props;
// 0 to 1
const [sliderPosition, setSliderPosition] = useState(
sliderPositionPercentage,
);
const [containerWidth, setContainerWidth] = useState(0);
const [leftImgLoaded, setLeftImgLoaded] = useState(false);
const [rightImgLoaded, setRightImgLoaded] = useState(false);
const [isSliding, setIsSliding] = useState(false);
const containerRef = useRef();
const rightImageRef = useRef();
const leftImageRef = useRef();
// keep track container's width in local state
useEffect(() => {
const updateContainerWidth = () => {
const currentContainerWidth = containerRef.current.getBoundingClientRect()
.width;
setContainerWidth(currentContainerWidth);
};
// initial execution must be done manually
updateContainerWidth();
// update local state if container size is changed
const containerElement = containerRef.current;
const resizeSensor = new ResizeSensor(containerElement, () => {
updateContainerWidth();
});
return () => {
resizeSensor.detach(containerElement);
};
}, []);
useEffect(() => {
// consider the case where loading image is completed immediately
// due to the cache etc.
const alreadyDone = leftImageRef.current.complete;
alreadyDone && setLeftImgLoaded(true);
return () => {
// when the left image source is changed
setLeftImgLoaded(false);
};
}, [leftImage]);
useEffect(() => {
// consider the case where loading image is completed immediately
// due to the cache etc.
const alreadyDone = rightImageRef.current.complete;
alreadyDone && setRightImgLoaded(true);
return () => {
// when the right image source is changed
setRightImgLoaded(false);
};
}, [rightImage]);
const allImagesLoaded = rightImgLoaded && leftImgLoaded;
useEffect(() => {
const handleSliding = event => {
const e = event || window.event;
// Calc Cursor Position from the left edge of the viewport
const cursorXfromViewport = e.touches ? e.touches[0].pageX : e.pageX;
// Calc Cursor Position from the left edge of the window (consider any page scrolling)
const cursorXfromWindow = cursorXfromViewport - window.pageXOffset;
// Calc Cursor Position from the left edge of the image
const imagePosition = rightImageRef.current.getBoundingClientRect();
let pos = cursorXfromWindow - imagePosition.left;
// Set minimum and maximum values to prevent the slider from overflowing
const minPos = 0 + sliderLineWidth / 2;
const maxPos = containerWidth - sliderLineWidth / 2;
if (pos < minPos) pos = minPos;
if (pos > maxPos) pos = maxPos;
setSliderPosition(pos / containerWidth);
// If there's a callback function, invoke it everytime the slider changes
if (onSliderPositionChange) {
onSliderPositionChange(pos / containerWidth);
}
};
const startSliding = e => {
setIsSliding(true);
// Prevent default behavior other than mobile scrolling
if (!('touches' in e)) {
e.preventDefault();
}
// Slide the image even if you just click or tap (not drag)
handleSliding(e);
window.addEventListener('mousemove', handleSliding); // 07
window.addEventListener('touchmove', handleSliding); // 08
};
const finishSliding = () => {
setIsSliding(false);
window.removeEventListener('mousemove', handleSliding);
window.removeEventListener('touchmove', handleSliding);
};
const containerElement = containerRef.current;
if (allImagesLoaded) {
// it's necessary to reset event handlers each time the canvasWidth changes
// for mobile
containerElement.addEventListener('touchstart', startSliding); // 01
window.addEventListener('touchend', finishSliding); // 02
// for desktop
if (hover) {
containerElement.addEventListener('mousemove', handleSliding); // 03
containerElement.addEventListener('mouseleave', finishSliding); // 04
} else {
containerElement.addEventListener('mousedown', startSliding); // 05
window.addEventListener('mouseup', finishSliding); // 06
}
}
return () => {
// cleanup all event resteners
containerElement.removeEventListener('touchstart', startSliding); // 01
window.removeEventListener('touchend', finishSliding); // 02
containerElement.removeEventListener('mousemove', handleSliding); // 03
containerElement.removeEventListener('mouseleave', finishSliding); // 04
containerElement.removeEventListener('mousedown', startSliding); // 05
window.removeEventListener('mouseup', finishSliding); // 06
window.removeEventListener('mousemove', handleSliding); // 07
window.removeEventListener('touchmove', handleSliding); // 08
};
}, [allImagesLoaded, containerWidth, hover, sliderLineWidth]); // eslint-disable-line
// Image size set as follows.
//
// 1. right(under) image:
// width = 100% of container width
// height = auto
//
// 2. left(over) imaze:
// width = 100% of container width
// height = right image's height
// (protrudes is hidden by css 'object-fit: hidden')
const styles = {
container: {
boxSizing: 'border-box',
position: 'relative',
width: '100%',
overflow: 'hidden',
},
rightImage: {
display: 'block',
height: 'auto', // Respect the aspect ratio
width: '100%',
...rightImageCss,
},
leftImage: {
clip: `rect(auto, ${containerWidth * sliderPosition}px, auto, auto)`,
display: 'block',
height: '100%', // fit to the height of right(under) image
objectFit: 'cover', // protrudes is hidden
position: 'absolute',
top: 0,
width: '100%',
...leftImageCss,
},
slider: {
alignItems: 'center',
cursor: !hover && 'ew-resize',
display: 'flex',
flexDirection: 'column',
height: '100%',
justifyContent: 'center',
left: `${containerWidth * sliderPosition - handleSize / 2}px`,
position: 'absolute',
top: 0,
width: `${handleSize}px`,
},
line: {
background: sliderLineColor,
boxShadow:
'0px 3px 1px -2px rgba(0, 0, 0, 0.2), 0px 2px 2px 0px rgba(0, 0, 0, 0.14), 0px 1px 5px 0px rgba(0, 0, 0, 0.12)',
flex: '0 1 auto',
height: '100%',
width: `${sliderLineWidth}px`,
},
handleCustom: {
alignItems: 'center',
boxSizing: 'border-box',
display: 'flex',
flex: '1 0 auto',
height: 'auto',
justifyContent: 'center',
width: 'auto',
},
handleDefault: {
alignItems: 'center',
border: `${sliderLineWidth}px solid ${sliderLineColor}`,
borderRadius: '100%',
boxShadow:
'0px 3px 1px -2px rgba(0, 0, 0, 0.2), 0px 2px 2px 0px rgba(0, 0, 0, 0.14), 0px 1px 5px 0px rgba(0, 0, 0, 0.12)',
boxSizing: 'border-box',
display: 'flex',
flex: '1 0 auto',
height: `${handleSize}px`,
justifyContent: 'center',
width: `${handleSize}px`,
},
leftArrow: {
border: `inset ${handleSize * 0.15}px rgba(0,0,0,0)`,
borderRight: `${handleSize * 0.15}px solid ${sliderLineColor}`,
height: '0px',
marginLeft: `-${handleSize * 0.25}px`, // for IE11
marginRight: `${handleSize * 0.25}px`,
width: '0px',
},
rightArrow: {
border: `inset ${handleSize * 0.15}px rgba(0,0,0,0)`,
borderLeft: `${handleSize * 0.15}px solid ${sliderLineColor}`,
height: '0px',
marginRight: `-${handleSize * 0.25}px`, // for IE11
width: '0px',
},
leftLabel: {
background: 'rgba(0, 0, 0, 0.5)',
color: 'white',
left: '5%',
opacity: isSliding ? 0 : 1,
padding: '10px 20px',
position: 'absolute',
top: '50%',
transform: 'translate(0,-50%)',
transition: 'opacity 0.1s ease-out',
},
rightLabel: {
background: 'rgba(0, 0, 0, 0.5)',
color: 'white',
opacity: isSliding ? 0 : 1,
padding: '10px 20px',
position: 'absolute',
right: '5%',
top: '50%',
transform: 'translate(0,-50%)',
transition: 'opacity 0.1s ease-out',
},
};
return (
<>
{skeleton && !allImagesLoaded && (
<div style={{ ...styles.container }}>{skeleton}</div>
)}
<div
style={{
...styles.container,
display: allImagesLoaded ? 'block' : 'none',
}}
ref={containerRef}
data-testid="container"
>
<div>
<img
onLoad={() => setRightImgLoaded(true)}
alt={rightImageAlt}
data-testid="right-image"
ref={rightImageRef}
src={rightImage}
style={styles.rightImage}
/>
</div>
<div>
<img
onLoad={() => setLeftImgLoaded(true)}
alt={leftImageAlt}
data-testid="left-image"
ref={leftImageRef}
src={leftImage}
style={styles.leftImage}
/>
</div>
<div style={styles.slider}>
<div style={styles.line} />
{handle ? (
<div style={styles.handleCustom}>{handle}</div>
) : (
<div style={styles.handleDefault}>
<div style={styles.leftArrow} />
<div style={styles.rightArrow} />
</div>
)}
<div style={styles.line} />
</div>
{/* labels */}
{leftImageLabel && <div style={styles.leftLabel}>{leftImageLabel}</div>}
{rightImageLabel && (
<div style={styles.rightLabel}>{rightImageLabel}</div>
)}
</div>
</>
);
}
ReactCompareImage.propTypes = propTypes;
ReactCompareImage.defaultProps = defaultProps;
export default ReactCompareImage;
|
/**
* Created by intralizee on 2016-06-07.
*/
var config = require('./../../config');
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(config.database.use === 'cloud' ? config.database.cloud : config.database.local);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(cb) {
console.log('[!] Successfully connected to MongoDB...');
config.database.use === 'cloud' ? console.log(config.database.cloud) : console.log(config.database.local);
});
// When the mongodb server goes down, mongoose emits a 'disconnected' event
mongoose.connection.on('disconnected', () => { console.log('-> lost connection'); });
// The driver tries to automatically reconnect by default, so when the
// server starts the driver will reconnect and emit a 'reconnect' event.
mongoose.connection.on('reconnect', () => { console.log('-> reconnected'); });
// Mongoose will also emit a 'connected' event along with 'reconnect'. These
// events are interchangeable.
mongoose.connection.on('connected', () => { console.log('-> connected'); });
var clientSchema = mongoose.Schema({
socketId: String,
uuid: String,
token: String,
channel: String,
online: false,
timestamp: Date
});
var publicKeysSchema = mongoose.Schema({
socket_id: String,
publicKeyServer: String,
secretKeyServer: String
});
var forgeSchema = mongoose.Schema({
socket_id: String,
key: String,
iv: String
});
var userSchema = mongoose.Schema({
username: String,
password: String,
contact: {
email: String
},
info: {
ip : {
login : {
now: String,
previous: String,
history: {
type: Array,
default: []
}
}
},
date : {
registration: {
type: Date,
default: Date.now
},
login: {
now : Date,
previous : Date,
history : {
type: Array,
default: []
}
}
}
},
devices: []
});
exports.User = mongoose.model('User', userSchema);
exports.Clients = mongoose.model('Clients', clientSchema);
|
var drag = false;
var rect = {};
var canvas2;
var IsFG = true;
var index = 100;
var scaleFactor;
var imgData;
var canvas;
var cloneData;
let Radius = 5;
let MaskBG = 127;
//let MaskFG = 126;
var segimgname = "segment.png";
setCallbacks();
function setCallbacks() {
var inputElement = document.getElementById("my-file");
canvas = document.getElementById("canvas1");
inputElement.addEventListener("change", onLoadImage, false);
canvas.addEventListener("mouseup", onMouseUp, false);
canvas.addEventListener("mousedown", onMouseDown, false);
canvas.addEventListener("mousemove", onMouseMove, false);
}
function getMousePos(evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function onMouseUp(e) {
drag = false;
}
function onMouseDown(e) {
drag = true;
}
function onMouseMove(e) {
//var canvas=document.getElementById("canvas1");
var cxt=canvas.getContext("2d")
if(drag)
{
var mousePos = getMousePos(e);
if(IsFG){
cxt.beginPath();
cxt.arc(mousePos.x,mousePos.y,Radius,0,360,false);
if(index==100)
{
cxt.fillStyle="green";
}
else if(index==30)
{
cxt.fillStyle="red";
}
else
{
cxt.fillStyle="blue";
}
cxt.fill();
cxt.closePath();
for(var i=-1*Radius;i<Radius+1;i++)
for(var j=-1*Radius;j<Radius+1;j++)
{
if(Math.sqrt(i*i+j*j)<=Radius)
{
var ii=Math.floor(Math.max(0, Math.min(mousePos.y+i,canvas.height-1)));
var jj=Math.floor(Math.max(0, Math.min(mousePos.x+j,canvas.width-1)));
imgData.data[4*jj+ii*canvas.width*4+3] = (index);
}
}
}
else
{
cxt.beginPath();
cxt.arc(mousePos.x,mousePos.y,Radius,0,360,false);
cxt.fillStyle="black";
cxt.fill();
cxt.closePath();
for(var i=-1*Radius;i<Radius+1;i++)
for(var j=-1*Radius;j<Radius+1;j++)
{
if(Math.sqrt(i*i+j*j)<=Radius)
{
var ii=Math.floor(Math.max(0, Math.min(mousePos.y+i,canvas.height-1)));
var jj=Math.floor(Math.max(0, Math.min(mousePos.x+j,canvas.width-1)));
imgData.data[4*jj+ii*canvas.width*4+3] = MaskBG;
}
}
}
}
return ;
}
function clearFg()
{
var ctx = canvas.getContext('2d');
imgData.data.set(cloneData.data);
ctx.putImageData(imgData, 0, 0);
}
function onLoadImage(e) {
//var fileReturnPath = document.getElementsByClassName('form-control');
canvas = document.getElementById('canvas1');
var canvasWidth = 600;
var canvasHeight = 600;
var ctx = canvas.getContext('2d');
var url = URL.createObjectURL(e.target.files[0]);
segimgname = e.target.files[0].name+".png";
var img = new Image();
img.onload = function() {
scaleFactor = Math.min((canvasWidth / img.width), (canvasHeight / img.height));
canvas.width = img.width * scaleFactor;
canvas.height = img.height * scaleFactor;
ctx.drawImage(img, 0, 0, img.width * scaleFactor, img.height * scaleFactor);
imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
cloneData = ctx.createImageData(canvas.width, canvas.height);
cloneData.data.set(imgData.data);
}
img.src = url;
}
function switchObj1()
{
IsFG = true;
index = 100;
}
function switchObj2()
{
IsFG = true;
index = 30;
}
function switchObj3()
{
IsFG = true;
index = 20;
}
function switchBg()
{
IsFG = false;
}
function downloadImage()
{
var dlcanvas = document.getElementById("canvas2");
var dlimg = dlcanvas.toDataURL("image/png");
var download = document.createElement('a');
download.href = dlimg; //'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
download.download = segimgname;
download.click();
}
function Segment()
{
var canvas2 = document.getElementById('canvas2');
canvas2.width = canvas.width;
canvas2.height = canvas.height;
var ctx2 = canvas2.getContext('2d');
var res = ctx2.createImageData(canvas.width, canvas.height);
var mask = Module._malloc(imgData.data.length*imgData.data.BYTES_PER_ELEMENT);
var buf = Module._malloc(imgData.data.length*imgData.data.BYTES_PER_ELEMENT);
Module.HEAPU8.set(imgData.data, buf);
var gamma = 10;
var num = 3;
var masklist = Module._malloc(num);
var tmp = new Uint8Array( num );
tmp[0] = 100;
tmp[1] = 30;
tmp[2] = 20;
Module.HEAPU8.set(tmp, masklist);
console.log(tmp);
res.data.set(cloneData.data);
Module._process(buf, mask, canvas.width, canvas.height, num, masklist, gamma);
for(var y=0; y<canvas.height; y++)
for(var x=0; x<canvas.width; x++)
{
var label = Module.getValue(mask+x+y*canvas.width, "i8");
/*
if(label==MaskBG)
{
res.data[4*x+y*canvas.width*4+3] = 0;
}
else if(label==tmp[0])
{
res.data[4*x+y*canvas.width*4+0] = 0;
res.data[4*x+y*canvas.width*4+1] = 255;
res.data[4*x+y*canvas.width*4+2] = 0;
res.data[4*x+y*canvas.width*4+3] = 255;
}
else if(label==tmp[1])
{
res.data[4*x+y*canvas.width*4+0] = 255;
res.data[4*x+y*canvas.width*4+1] = 0;
res.data[4*x+y*canvas.width*4+2] = 0;
res.data[4*x+y*canvas.width*4+3] = 255;
}
else if(label==tmp[2])
{
res.data[4*x+y*canvas.width*4+0] = 0;
res.data[4*x+y*canvas.width*4+1] = 0;
res.data[4*x+y*canvas.width*4+2] = 255;
res.data[4*x+y*canvas.width*4+3] = 255;
}
*/
}
ctx2.putImageData(res, 0, 0);
Module._free(buf);
Module._free(mask);
Module._free(masklist);
}
|
let exec;
try {
exec = require('cordova/exec');
} catch (error) {
console.log('Cordova exec not found');
exec = function (cb, err, PLUGIN_NAME, RootCheck, args) {
console.log('Invoked RootCheck:' + RootCheck);
cb();
};
}
var PLUGIN_NAME = 'certCheck';
var certCheck = {
getMd5Signature: function (cb, err) {
exec(cb, err, PLUGIN_NAME, 'getMd5Signature', []);
}
};
module.exports = certCheck;
|
const _ = require('lodash');
function deepFreeze(object) {
if (!_.isObjectLike(object)) {
return;
}
Object.freeze(object);
_.forOwn(object, function(value) {
if (!_.isObjectLike(value) || Object.isFrozen(value)) {
return;
}
deepFreeze(value);
});
return object;
}
module.exports = {
deepFreeze,
};
|
/* eslint-disable consistent-return */
/**
* 福利商城 已完成订单
*/
import React, { Component, PureComponent } from 'react';
import {
StyleSheet,
Dimensions,
View,
Text,
Button,
Image,
ScrollView,
TouchableOpacity,
} from 'react-native';
import { connect } from 'rn-dva';
import moment from 'moment';
import Header from '../../components/Header';
import CommonStyles from '../../common/Styles';
import WMGoodsWrap from '../../components/WMGoodsWrap';
import ShowBigPicModal from '../../components/ShowBigPicModal';
import * as requestApi from '../../config/requestApi';
import ShareTemplate from '../../components/ShareTemplate';
import { getPreviewImage } from '../../config/utils';
import { NavigationComponent } from '../../common/NavigationComponent';
const { width, height } = Dimensions.get('window');
class WMOrderCompleteDetailScreen extends NavigationComponent {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
this.state = {
orderData: {
lotteryTime: new Date(),
},
goodsData: {
state: '',
},
winnerInfo: {
pictures: [],
thirdWinningTime: new Date(),
thirdWinningNumber: '',
thirdWinningNo: 0,
lotteryNumber: 0,
factDrawDate: moment().format('YYYY-MM-DD HH:mm:ss'),
},
showImgLimit: 3,
limit: 10,
page: 1,
showBingPicVisible: false, // 显示大图modal状态
showImgIndex: 0, // 显示大图,显示第几张图
userBuyRecord: [], // 所有用户购买记录
showShareModal: false, // 显示分享弹窗
showBigPicArr: [], // 显示大图资源
};
}
blurState = {
showBingPicVisible: false, // 显示大图modal状态
showShareModal: false, // 显示分享弹窗
}
componentDidMount() {
Loading.show();
// this.getOrderDetail()
this.getDetailJLottery();
this.getAllUserBuyList();
}
componentWillUnmount() {
super.componentWillUnmount();
Loading.hide();
}
// 获取中奖人晒单信息
getDetailJLottery = () => {
const goodsData = this.props.navigation.getParam('params');
requestApi.detailJLottery({
// sequenceId: '5c131526033455380df889bf',
sequenceId: goodsData.termNumber,
orderId: goodsData.orderId,
}).then((res) => {
console.log('resres', res);
const temp = [];
res.pictures && res.pictures.map((item) => {
temp.push({
type: 'images',
url: item,
});
});
if (res.videoMainUrl !== null && res.videoUrl !== null && res.videoMainUrl !== '' && res.videoUrl !== '') {
temp.push({
type: 'video',
url: res.videoUrl,
mainPic: res.videoMainUrl,
});
}
this.setState({
winnerInfo: res,
goodsData,
showBigPicArr: temp,
});
}).catch((err) => {
console.log(err);
});
}
// 获取订单详情
getOrderDetail = () => {
const goodsData = this.props.navigation.getParam('params');
console.log('goodsData', goodsData);
Loading.show();
console.log('params', goodsData);
const params = {
orderId: goodsData.orderId,
};
requestApi.qureyWMOrderDetail(params).then((res) => {
console.log('orderDetail', res);
if (res) {
this.setState({
orderData: res,
goodsData,
});
}
}).catch((err) => {
console.log(err);
});
}
// 获取其他购买用户的记录
getAllUserBuyList = () => {
const { limit, page } = this.state;
const goodsData = this.props.navigation.getParam('params');
const param = {
limit,
page,
sequenceId: goodsData.termNumber,
orderId: goodsData.orderId,
};
requestApi.jSequenceJoinQPage(param).then((res) => {
console.log('购买记录', res);
const temp = [];
if (res) {
res.data.map((item) => {
const tempItem = item;
tempItem.showMore = false;
temp.push(tempItem);
});
}
this.handleChangeState('userBuyRecord', temp);
}).catch((err) => {
console.log(err);
});
}
handleToogleShow = () => {
const { showImgLimit } = this.state;
const len = showImgLimit === 3 ? 9 : 3;
this.handleChangeState('showImgLimit', len);
}
getOperateBtn = (itemData) => {
const { navigation } = this.props;
const { showImgLimit, winnerInfo, showBigPicArr } = this.state;
if (!itemData) return;
switch (itemData.lottery) {
// eslint-disable-next-line consistent-return
case 'SHARE_LOTTERY': return (
<View style={{ paddingBottom: 10 }}>
<Text style={[styles.showOrderText]}>{winnerInfo.content}</Text>
<View style={styles.showOrderImgWrap}>
{
showBigPicArr && showBigPicArr.map((item, index) => {
if (index > showImgLimit - 1) return null;
return (
<TouchableOpacity key={index} onPress={() => { this.setState({ largeImage: item, showBingPicVisible: true, showImgIndex: index }); }}>
<Image style={styles.showOrderImg} defaultSource={require('../../images/skeleton/skeleton_img.png')} source={{ uri: (item.type === 'video') ? item.mainPic : item.url }} />
{
(item.type === 'video')
? (
<View style={{
height: '100%', width: '100%', position: 'absolute', ...CommonStyles.flex_center,
}}
>
<Image style={{ height: 40, width: 40 }} source={require('../../images/index/video_play_icon.png')} />
</View>
)
: null
}
</TouchableOpacity>
);
})
}
</View>
{
showBigPicArr && showBigPicArr.length > 3 && (
<TouchableOpacity onPress={this.handleToogleShow}>
<Text style={styles.showMoreImgBtn}>{showImgLimit === 3 ? '展开' : '收起'}</Text>
</TouchableOpacity>
)
}
</View>
);
case 'LOSING_LOTTERY': return null;
// eslint-disable-next-line consistent-return
case 'SHARE_AUDIT_ING': return (
<TouchableOpacity style={styles.prizeInfoOperateWrap} onPress={() => { }}>
<Text style={styles.prizeInfoBtn}>晒单审核中</Text>
</TouchableOpacity>
);
// eslint-disable-next-line consistent-return
case 'WINNING_LOTTERY': return (
<TouchableOpacity style={styles.prizeInfoOperateWrap} onPress={() => { navigation.navigate('WMShowOrder', { orderInfo: itemData, callback: () => { this.getDetailJLottery(); } }); }}>
<Text style={styles.prizeInfoBtn}>晒单返券</Text>
</TouchableOpacity>
);
// eslint-disable-next-line consistent-return
case 'SHARE_AUDIT_FAIL': return (
<TouchableOpacity style={styles.prizeInfoOperateWrap} onPress={() => { navigation.navigate('WMShowOrder', { orderInfo: itemData, callback: () => { this.getDetailJLottery(); } }); }}>
<Text style={styles.prizeInfoBtn}>重新晒单</Text>
</TouchableOpacity>
);
default: null;
}
}
handleChangeState = (key, value, callback = () => { }) => {
this.setState({
[key]: value,
}, () => {
callback();
});
}
// 所有人购买记录
handleToogleShowMore = (item, index) => {
const { userBuyRecord } = this.state;
item.showMore = !item.showMore;
userBuyRecord[index] = item;
this.handleChangeState('userBuyRecord', userBuyRecord);
}
render() {
const { navigation, orderData } = this.props;
const {
goodsData, showBingPicVisible, showImgIndex, userBuyRecord, showShareModal, winnerInfo, showImgLimit, showBigPicArr,
} = this.state;
console.log('userBuyRecord', userBuyRecord);
console.log('orderData', winnerInfo);
const gzDataList = [
{
label: '公证开奖时间:',
value: moment(winnerInfo.thirdWinningTime * 1000).format('YYYY-MM-DD HH:mm'),
},
{
label: '公证开奖期数:',
value: winnerInfo.thirdWinningNo || 0,
},
{
label: '公证开奖号码:',
value: winnerInfo.thirdWinningNumber || 0,
},
];
const isShow = navigation.getParam('isShow', false); // 是否是展示作用,如果是,不显示操作按钮
console.log('showBigPicArr', showBigPicArr);
return (
<View style={styles.container}>
<Header
navigation={navigation}
goBack
title="中奖详情"
rightView={(
<TouchableOpacity onPress={() => { this.handleChangeState('showShareModal', true); }}>
<Image style={styles.headRißghtIcon} source={require('../../images/wm/wmshare_icon.png')} />
</TouchableOpacity>
)}
/>
<ScrollView
style={{ marginBottom: CommonStyles.footerPadding }}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
>
{
// 新增的公证开奖
<View style={styles.gzWrpa}>
{
gzDataList.map((item, index) => {
const paddingBottom = index === gzDataList.length - 1 ? null : { paddingBottom: 0 };
return (
<View style={[CommonStyles.flex_start, { padding: 10 }, paddingBottom]} key={index}>
<Text style={styles.btmLabel}>{item.label}</Text>
<Text style={[styles.btmLabel, (index === 1) ? styles.redColor : null]}>{item.value}</Text>
</View>
);
})
}
</View>
}
{/* 中奖人信息,有可能存在时间过期了,但是没人参与的订单(从首页最新揭晓进入的时候) */}
<View style={styles.prizeWrap}>
{
winnerInfo.lotteryNumber
? (
<View style={[styles.flexStart, (orderData.state === 'SHARE_LOTTERY' ? {} : styles.borderBottom)]}>
<WMGoodsWrap
imgHeight={60}
imgWidth={60}
imgUrl={winnerInfo.avatar}
title={winnerInfo.nickname}
goodsTitleStyle={{ fontSize: 14, color: '#222' }}
showProcess={false}
showPrice={false}
imgStyle={styles.imgStyle}
numberOfLines={1}
goodsWrap={orderData.state === 'SHARE_LOTTERY' ? { paddingBottom: 0 } : {}}
>
<View style={[styles.flexStart, { marginTop: 10 }]}>
<Text style={styles.prizeInfoLabel}>中奖编号:</Text>
<Text style={[styles.prizeInfoLabel, styles.color_red]}>{winnerInfo.lotteryNumber}</Text>
</View>
<View style={[styles.flexStart, { marginTop: 1 }]}>
<Text style={styles.prizeInfoLabel}>开奖时间:</Text>
<Text style={styles.prizeInfoLabel}>{moment(winnerInfo.factDrawDate * 1000).format('YYYY-MM-DD HH:mm:ss')}</Text>
</View>
</WMGoodsWrap>
</View>
)
: null
}
{
// 如果是本人中奖 显示操作按钮和晒单信息
winnerInfo.isSelfLottery === 1 && !isShow && this.getOperateBtn(winnerInfo)
}
{
// 如果不是本人,且晒单通过,只显示晒单信息
winnerInfo.isSelfLottery === 0
? winnerInfo.lottery === 'SHARE_LOTTERY'
? (
<React.Fragment>
<Text style={styles.showOrderText}>{winnerInfo.content}</Text>
<View style={styles.showOrderImgWrap}>
{
showBigPicArr && showBigPicArr.map((item, index) => {
if (index > showImgLimit - 1) return;
return (
// eslint-disable-next-line react/no-array-index-key
<TouchableOpacity key={index} onPress={() => { this.setState({ largeImage: item, showBingPicVisible: true, showImgIndex: index }); }}>
<Image style={styles.showOrderImg} defaultSource={require('../../images/skeleton/skeleton_img.png')} source={{ uri: (item.type === 'video' ? item.mainPic : getPreviewImage(item.url, '50p')) }} />
</TouchableOpacity>
);
})
}
</View>
{
showBigPicArr && showBigPicArr.length > 3 && (
<TouchableOpacity onPress={this.handleToogleShow}>
<Text style={styles.showMoreImgBtn}>{showImgLimit === 3 ? '展开' : '收起'}</Text>
</TouchableOpacity>
)
}
{/* <View style={[styles.flexEnd, styles.commentWrap]}>
<Image style={{ width: 12, height: 12 }} source={require('../../images/wm/wm_comment_icon.png')} />
<Text style={styles.commentBtn}>评论</Text>
</View> */}
</React.Fragment>
)
: null
: null
}
</View>
{/* 所有人购买历史 */}
<View style={styles.carshListWrap}>
{
// orderData.goodsType !== 4 && dataList.map((item, index) => {
userBuyRecord && userBuyRecord.length !== 0 && userBuyRecord.map((item, index) => (
// eslint-disable-next-line react/no-array-index-key
<View style={styles.buyListItem} key={index}>
<View style={[styles.flexStart_noCenter]}>
<TouchableOpacity activeOpacity={item.userType !== 'muser' ? 0.7 : 1} onPress={() => { item.userType !== 'muser' ? nativeApi.jumpPersonalCenter(item.userId) : null; }}>
<Image source={{ uri: getPreviewImage(item.avatar, '50p') }} style={styles.carshListItemimg} />
</TouchableOpacity>
<View style={[styles.flex_1, styles.buyListItemRightWrap]}>
<View style={styles.flextBetwwen}>
<View style={styles.flexStart}>
<Text style={styles.buyListItemTitle}>购买注数:</Text>
<Text style={[styles.buyListItemTitle, { color: '#EE6161', paddingLeft: 5 }]}>{item.orderNumber}</Text>
</View>
<Text style={styles.buyListItemTime}>
购买时间:
{moment(item.createdAt * 1000).format('YYYY-MM-DD')}
</Text>
</View>
{
item.lotteryNumbers.map((itemData, j) => {
if (item.showMore) {
return (
<Text key={j} style={styles.buyListItemNum}>
编号:
{itemData}
</Text>
);
}
if (j <= 2) {
return (
<Text key={j} style={styles.buyListItemNum}>
编号:
{itemData}
</Text>
);
}
})
}
{
item.lotteryNumbers.length > 3 && (
<TouchableOpacity onPress={() => { this.handleToogleShowMore(item, index); }}>
<Text style={[styles.showMoreImgBtn, { paddingLeft: 0 }]}>{item.showMore ? '收起' : '展开'}</Text>
</TouchableOpacity>
)
}
</View>
</View>
</View>
))
}
</View>
</ScrollView>
{/* 分享 */}
{
showShareModal && (
<ShareTemplate
type="WMOrderList"
onClose={() => { this.handleChangeState('showShareModal', false); }}
shareParams={winnerInfo}
/>
)
}
{/* 查看大图 */}
<ShowBigPicModal
ImageList={showBigPicArr}
visible={showBingPicVisible}
showImgIndex={showImgIndex}
onClose={() => { this.handleChangeState('showBingPicVisible', false); }}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
},
flex_1: {
flex: 1,
},
flexStart: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
},
flexEnd: {
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
},
flexStart_noCenter: {
flexDirection: 'row',
justifyContent: 'flex-start',
},
flextBetwwen: {
justifyContent: 'space-between',
flexDirection: 'row',
alignItems: 'center',
},
headRightIcon: {
marginRight: 25,
},
prizeWrap: {
// borderWidth: 1,
// borderColor: 'rgba(215,215,215,0.5)',
borderRadius: 8,
backgroundColor: '#fff',
overflow: 'hidden',
marginTop: 10,
marginHorizontal: 10,
},
prizeInfoTitle: {
fontSize: 14,
color: '#222',
lineHeight: 17,
},
prizeInfoLabel: {
fontSize: 12,
color: '#222',
},
color_red: {
color: '#EE6161',
},
prizeInfoOperateWrap: {
padding: 15,
borderRadius: 8,
margin: 10,
paddingVertical: 13,
backgroundColor: CommonStyles.globalHeaderColor,
},
prizeInfoBtn: {
color: '#fff',
textAlign: 'center',
},
carshListWrap: {
margin: 10,
borderRadius: 8,
backgroundColor: '#fff',
// borderWidth: 1,
// borderColor: 'rgba(215,215,215,0.5)',
},
buyListItem: {
padding: 15,
borderBottomWidth: 1,
borderColor: '#F1F1F1',
},
carshListItemimg: {
height: 40,
width: 40,
borderRadius: 8,
},
buyListItemRightWrap: {
paddingLeft: 10,
},
buyListItemTitle: {
fontSize: 14,
color: '#222',
},
buyListItemTime: {
fontSize: 10,
color: '#222',
},
buyListItemNum: {
fontSize: 12,
color: '#555',
marginTop: 3,
},
showOrderText: {
backgroundColor: '#fff',
fontSize: 12,
color: '#555',
paddingHorizontal: 12,
lineHeight: 17,
paddingTop: 10,
},
showOrderImgWrap: {
backgroundColor: '#fff',
flexDirection: 'row',
justifyContent: 'flex-start',
flexWrap: 'wrap',
paddingLeft: 15,
paddingTop: 5,
},
showOrderImg: {
width: 80,
height: 80,
marginRight: 5,
marginTop: 5,
},
commentWrap: {
padding: 15,
borderBottomColor: '#f1f1f1',
borderBottomWidth: 1,
},
commentBtn: {
fontSize: 12,
color: '#777',
paddingLeft: 3,
},
showMoreImgBtn: {
color: CommonStyles.globalHeaderColor,
fontSize: 12,
paddingLeft: 15,
marginTop: 5,
paddingBottom: 5,
},
imgStyle: {
borderRadius: 8,
},
gzWrpa: {
backgroundColor: '#fff',
margin: 10,
marginBottom: 0,
borderRadius: 8,
},
btmLabel: {
fontSize: 14,
color: '#555',
},
redColor: {
color: '#EE6161',
},
});
export default connect(
state => ({ orderData: state.welfare.wmOrderDetail }),
)(WMOrderCompleteDetailScreen);
|
describe('riq-grid', function () {
it('should be awesome', function () {
expect('awesome').toBeTruthy();
});
})
|
import styled from "styled-components";
import colors from "../../styles/variables";
const Wrapper = styled.section`
display: block;
`;
export const LoadMore = styled.div`
width: 100%;
border: none;
text-align: center;
background: transparent;
.post-button {
font-size: 18px;
}
button {
color: #fff;
font-weight: bold;
padding: 0.5rem;
border: none;
border-radius: 4px;
background: ${colors.pink};
}
`;
export default Wrapper;
|
function hello(o){console.log("Hi~"+o)}hello("jwon");
|
import {
defaultEndNames,
defaultGatewayNames,
defaultIntermediateNames,
defaultStartNames,
defaultTaskNames,
} from '@/components/nodes/defaultNames';
import cloneDeep from 'lodash/cloneDeep';
export default class Node {
static diagramPropertiesToCopy = ['x', 'y', 'width', 'height'];
static definitionPropertiesToNotCopy = ['$type', 'id'];
static eventDefinitionPropertiesToNotCopy = ['errorRef', 'messageRef'];
type;
definition;
diagram;
pool;
constructor(type, definition, diagram) {
this.type = type;
this.definition = definition;
this.diagram = diagram;
}
isBpmnType(...types) {
return types.includes(this.definition.$type);
}
canBeDefaultFlow() {
const validSources = [
'bpmn:ExclusiveGateway',
'bpmn:InclusiveGateway',
];
return this.definition.$type === 'bpmn:SequenceFlow'
&& validSources.includes(this.definition.sourceRef.$type);
}
isType(type) {
return this.type === type;
}
isStartEvent() {
return Object.keys(defaultStartNames).includes(this.type);
}
isEndEvent() {
return Object.keys(defaultEndNames).includes(this.type);
}
isTask() {
return Object.keys(defaultTaskNames).includes(this.type);
}
isGateway() {
return Object.keys(defaultGatewayNames).includes(this.type);
}
isIntermediateEvent() {
return Object.keys(defaultIntermediateNames).includes(this.type);
}
get id() {
return this.definition.id;
}
set id(id) {
this.definition.id = id;
}
setIds(nodeIdGenerator) {
const [nodeId, diagramId] = nodeIdGenerator.generate();
if (!this.id) {
this.id = nodeId;
}
if (this.diagram) {
this.diagram.id = diagramId;
this.diagram.bpmnElement = this.definition;
}
}
clone(nodeRegistry, moddle, $t) {
const definition = nodeRegistry[this.type].definition(moddle, $t);
const diagram = nodeRegistry[this.type].diagram(moddle);
const clonedNode = new this.constructor(this.type, definition, diagram);
clonedNode.id = null;
clonedNode.pool = this.pool;
Node.diagramPropertiesToCopy.forEach(prop => clonedNode.diagram.bounds[prop] = this.diagram.bounds[prop]);
Object.keys(this.definition).filter(key => !Node.definitionPropertiesToNotCopy.includes(key)).forEach(key => {
const definition = this.definition.get(key);
const clonedDefinition = typeof definition === 'object' ? cloneDeep(definition) : definition;
if (key === 'eventDefinitions') {
for (var i in clonedDefinition) {
if (definition[i].signalRef && !clonedDefinition[i].signalRef) {
clonedDefinition[i].signalRef = { ...definition[i].signalRef };
}
}
}
clonedNode.definition.set(key, clonedDefinition);
});
Node.eventDefinitionPropertiesToNotCopy.forEach(
prop => clonedNode.definition.eventDefinitions &&
clonedNode.definition.eventDefinitions[0] &&
clonedNode.definition.eventDefinitions[0].hasOwnProperty(prop) &&
clonedNode.definition.eventDefinitions[0].set(prop, null)
);
return clonedNode;
}
getTargetProcess(processes, processNode) {
return this.pool
? processes.find(({ id }) => id === this.pool.component.node.definition.get('processRef').id)
: processNode.definition;
}
static isTimerType(type) {
return [
'processmaker-modeler-start-timer-event',
'processmaker-modeler-intermediate-catch-timer-event',
].includes(type);
}
}
|
'use strict';
/** @member {Object} */
var winston = require('winston');
var fs = require('fs');
var path = require('path');
/** @member {Object} */
var nconf = require('nconf');
var async = require('async');
var _ = require('lodash');
var cors = require('cors');
var express = require('express');
var app = express();
var server;
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var useragent = require('express-useragent');
var favicon = require('serve-favicon');
var compress = require('compression');
var ejs = require('ejs');
var middleware = require('./server/middleware');
var model = require('./server/models');
var utils = require('./server/utils');
var logger = require('./server/logger');
var userAgent = require('./server/socket.io/userAgent');
var authentication = require('./server/services/authentication');
var customerSuccess = require('./server/database/customerSuccess');
if (nconf.get('app:ssl')) {
server = require('https').createServer({
key: fs.readFileSync(nconf.get('app:ssl').key),
cert: fs.readFileSync(nconf.get('app:ssl').cert)
}, app);
} else {
server = require('http').createServer(app);
}
module.exports.server = server;
server.on('error', function (err) {
winston.error(err);
if (err.code === 'EADDRINUSE') {
winston.error('uuChat address in use, exiting...');
process.exit(1);
} else if (err.code === 'EADDRNOTAVAIL') {
winston.error('uuChat ip address is not avail, exiting...');
process.exit(1);
} else {
throw err;
}
});
server.sessionStore = function () {
var redisHost = nconf.get('redis:host');
if (_.isEmpty(redisHost)) {
var SequelizeStore = require('connect-session-sequelize')(session.Store);
var sequelize = require('./server/models/index').sequelize;
winston.info(sequelize.Message);
return new SequelizeStore({
db: sequelize
});
} else {
var connectRedis = require("connect-redis")(session);
var storeRedis = new connectRedis({
host: nconf.get('redis:host'),
port: nconf.get('redis:port'),
ttl: nconf.get('redis:ttl'),
db: 0
});
return storeRedis;
}
};
module.exports.listen = function () {
async.waterfall([
function (next) {
//initial database
model.init(next);
},
function (next) {
setupExpress(app, next);
next();
},
function (next) {
checkRedisStarted(next);
},
function (next) {
expressListen();
next(null, '');
}
], function (err, result) {
if (err) {
switch (err.message) {
case 'redis-need-start':
winston.error('you need to start redis, eg: redis-server /usr/local/redis/redis.conf &');
break;
case 'redis-version-too-lower':
winston.error('you redis version is too lower , please update redis version above 3.0.0');
break;
case 'logger-folder-need-create':
winston.error('logger folder need create in root directory.');
default:
winston.error(err);
break;
}
process.exit();
}
winston.info("Web server has started");
});
};
function baseHtmlRoute(app, middlewareDev) {
app.use(express.static(path.join(__dirname, '../dist')));
//need filter css, js, images files
app.use(fileFilters);
app.use(session({
store: server.sessionStore(),
secret: nconf.get('socket.io:secretKey'),
key: nconf.get('socket.io:sessionKey'),
cookie: setupCookie(),
resave: false,
saveUninitialized: true
}));
app.get('/', middleware.jsCDN, function response(req, res) {
var html = path.join(__dirname, '../dist/index.html');
htmlRender(middlewareDev, res, html);
});
app.get('/webview', middleware.jsCDN, function response(req, res) {
setupSession(req, res);
var html = path.join(__dirname, '../dist/app/index.html');
htmlRender(middlewareDev, res, html);
});
app.get('/login', middleware.jsCDN, function response(req, res) {
customerSuccess.count(null, function (err, data) {
if(err) { return; }
if(data === 0){
var html = path.join(__dirname, '../dist/register.ejs');
var cdnFile = getCNDFile(req, null);
ejsRender(middlewareDev, cdnFile, res, html);
} else {
var html = path.join(__dirname, '../dist/app.ejs');
var cdnFile = getCNDFile(req, null);
cdnFile['socketIO'] = '';
ejsRender(middlewareDev, cdnFile, res, html);
}
});
});
app.get('/demo', function response(req, res) {
var html = path.join(__dirname, '../dist/customer.html');
htmlRender(middlewareDev, res, html);
});
app.get('/search', middleware.jsCDN, function response(req, res) {
var html = path.join(__dirname, '../dist/search.ejs');
ejsRender(middlewareDev, getCNDFile(req, null), res, html);
});
app.get('/console', middleware.jsCDN, function response(req, res) {
var html = path.join(__dirname, '../dist/console.ejs');
ejsRender(middlewareDev, getCNDFile(req, ['momentMinJS']), res, html);
});
app.get('/reset/:invited_code', middleware.jsCDN, function response(req, res) {
var html = path.join(__dirname, '../dist/resetPassword.ejs');
ejsRender(middlewareDev, getCNDFile(req, ['momentMinJS']), res, html);
});
app.get('/console/index', middleware.jsCDN, function response(req, res) {
if (!req.session.csid) {
res.redirect('/console');
}
var html = path.join(__dirname, '../dist/console.ejs');
ejsRender(middlewareDev, getCNDFile(req, ['momentMinJS']), res, html);
});
app.get('/chat', middleware.jsCDN, function response(req, res) {
if (!req.session.csid) {
res.redirect('/login');
} else {
var customerSuccess = require('./server/socket.io/customerSuccess');
var csid = req.session.csid;
winston.info(req.session);
if (_.isEmpty(customerSuccess.get(csid))) {
customerSuccess.create({csid: csid, name: req.session.csName, photo: req.session.photo});
}
}
var html = path.join(__dirname, '../dist/app.ejs');
ejsRender(middlewareDev, getCNDFile(req, ['socketIO']), res, html);
});
app.get('/register/:invited_code', middleware.jsCDN, function response(req, res) {
var invitedCode = req.params.invited_code;
var decode = authentication.validateInvitation(invitedCode);
console.log('--------------------- invitedCode is: ' + decode.email);
if(_.isEmpty(decode.email)){
res.redirect('/login');
} else {
var html = path.join(__dirname, '../dist/register.ejs');
var cdnFile = getCNDFile(req, null);
cdnFile['invitedCode'] = invitedCode;
ejsRender(middlewareDev, cdnFile, res, html);
}
});
//opts.credentials = true;
//cors(middleware.corsOptionsDelegate),
app.get('/s', middleware.jsCDN, function response(req, res) {
res.setHeader("P3P", "CP=CAO PSA OUR"); // For IE set cookie
req.inframUrl = req.query.r;
setupSession(req, res);
var html = path.join(__dirname, '../dist/storage.html');
//htmlRender(middlewareDev, res, html);
ejsRender(middlewareDev, autoCNDFile(req, null, ['socketIO']), res, html);
});
app.get('/404', middleware.jsCDN, function response(req, res) {
var html = path.join(__dirname, '../dist/404.html');
htmlRender(middlewareDev, res, html);
});
app.get('/503', middleware.jsCDN, function response(req, res) {
var html = path.join(__dirname, '../dist/503.html');
htmlRender(middlewareDev, res, html);
});
}
function htmlRender(middlewareDev, res, html) {
if (middlewareDev) {
res.write(middlewareDev.fileSystem.readFileSync(html));
res.end();
} else {
res.render(html);
}
}
function ejsRender(middlewareDev, jsObj, res, html) {
if (middlewareDev) {
var returnHtml = ejs.render(middlewareDev.fileSystem.readFileSync(html).toString(), jsObj);
res.write(returnHtml);
res.end();
} else {
res.render(html, jsObj);
}
}
function setupExpress(app, callback) {
//app.set('showStackError', true);
//app.disable('x-powered-by'); // http://expressjs.com/zh-cn/advanced/best-practice-security.html
//app.set('json spaces', process.env.NODE_ENV === 'development' ? 4 : 0);
app.use(require("morgan")(
global.env === 'development' ? 'tiny' : 'short',
{ stream: {
write: message => logger.info(message.trim())
}
}
));
app.use('/static/images', express.static(path.join(__dirname, './client/static/images')));
app.use('/content/upload', express.static(path.join(__dirname, '../content/upload')));
app.use('/content/avatar', express.static(path.join(__dirname, '../content/avatar')));
app.use('/public', express.static(path.join(__dirname, '../content/html')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser(nconf.get('socket.io:secretKey')));
app.use(useragent.express());
setupFavicon(app);
if (global.env === 'development') {
var webpack = require('webpack');
var webpackMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var config = require('../tools/webpack.config.dev.js');
var compiler = webpack(config);
var middlewareDev = webpackMiddleware(compiler, {
publicPath: config.output.publicPath,
contentBase: 'src',
stats: {
colors: true,
hash: false,
timings: true,
chunks: false,
chunkModules: false,
modules: false
}
});
app.use(middlewareDev);
app.use(webpackHotMiddleware(compiler, {
log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000
}));
baseHtmlRoute(app, middlewareDev);
} else {
baseHtmlRoute(app, null);
app.enable('cache');
app.enable('minification');
app.use(compress());
}
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
app.enable('view cache');
var routes = require('./server/routes');
routes(app, middleware);
//app.use(middleware.checkAccountPermissions);
setupAutoLocale(app, callback);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
logger.error("~~~~~~ has 404 error, please see browser console log!", req.url);
res.status(404);
res.redirect('/404');
});
app.use(function (err, req, res, next) {
logger.error("~~~~~~ has 503 error!", req.url);
logger.error(err.stack);
res.status(503);
res.redirect('/503');
});
winston.info('setup express success!');
}
function setupFavicon(app) {
app.use(favicon(path.join(__dirname, 'client/static/images/uuchat.ico')));
}
function setupCookie() {
var oneMonth = 30 * 86400000;
var cookie = {
expires: new Date(Date.now() + oneMonth)
};
var relativePath = nconf.get('app:relative_path');
if (relativePath !== '') {
cookie.path = relativePath;
}
return cookie;
}
function setupSession(req, res) {
var cid = '';
var ua = req.useragent;
if (req.session.cid) {
cid = req.session.cid;
} else {
cid = require('uuid/v4')(); //gen uuid
req.session.cid = cid;
ua.needSnycDB = true;
}
//res.cookie('uu.c', cid, {expires: new Date(Date.now() + 900000), httpOnly: true, path: '/'});
var headers = req ? req.headers : {};
var host = headers.host;
var referer = headers.referer || '';
if (!host) {
var url = require('url');
host = url.parse(referer).host || '';
}
var ip = headers['x-forwarded-for'] || req.connection.remoteAddress;
ua.cid = cid;
ua.ip = ip;
ua.host = host;
if (req.inframUrl) {
ua.url = req.inframUrl;
} else {
ua.url = req.protocol + '://' + req.get('host') + req.originalUrl;
}
userAgent.create(ua);
//winston.info('Customer session had set');
}
function fileFilters(req, res, next) {
var originalUrl = req.originalUrl;
var fileFilters = ['css', 'js', 'png', 'jpg', 'jpeg', 'ico'];
var flag = false;
var suffix = originalUrl.split('.').pop();
if (fileFilters.indexOf(suffix) !== -1) {
flag = true;
}
if (flag) {
res.render(path.join(__dirname, originalUrl));
} else {
next();
}
}
function getCNDFile(req, keys) {
var defaultKeys = ['reactMinJS', 'reactDomMinJS'];
return autoCNDFile(req, defaultKeys, keys);
}
function autoCNDFile(req, defaultKeys, keys) {
if (!defaultKeys) {
defaultKeys = [];
}
if (keys) {
defaultKeys = defaultKeys.concat(keys);
}
var isoCode = req.session.isoCode;
if (!isoCode) {
isoCode = nconf.get('CDN:DEFAULT');
}
var js = nconf.get('CDN:' + isoCode);
var rtnArray;
if (!_.isEmpty(js)) {
rtnArray = js
} else {
let d = nconf.get('CDN:DEFAULT');
rtnArray = nconf.get('CDN:' + d);
}
return _.reduce(rtnArray, function (result, value, key) {
if (_.indexOf(defaultKeys, key) >= 0) {
result[key] = value;
}
return result;
}, {});
}
//check redis has started;
function checkRedisStarted(callback) {
var redisHost = nconf.get('redis:host');
if (!_.isEmpty(redisHost)) {
utils.lsof(nconf.get('redis:port'), function (data) {
if (data.length > 0) {
winston.info('');
winston.info("[redis] has started");
} else {
callback(new Error('redis-need-start'));
}
});
//version print
if (global.env !== 'development') {
var _redis = require("../node_modules/connect-redis/node_modules/redis"),
client = _redis.createClient();
client.info(function () {
var info = client.server_info;
var versions = info.versions;
if (versions[0] < 3) {
callback(new Error('redis-version-too-lower'));
} else {
winston.info("[redis] version = %s", info.redis_version);
winston.info("[redis] executable = %s", info.executable);
winston.info("[redis] config file = %s", info.config_file);
winston.info('');
}
});
}
}
callback();
}
function setupAutoLocale(app, callback) {
}
function expressListen() {
var configAddress = nconf.get('app:address');
var address = ((configAddress === '0.0.0.0' || !configAddress) ? '0.0.0.0' : configAddress);
//server.listen.apply(server, args);
server.listen(nconf.get('app:port'), address, function () {
process.setMaxListeners(0);
process.env.TZ = 'Hongkong';
});
server.on('listening', function onListening() {
var addr = server.address();
var bind = typeof addr === 'string' ?
'pipe ' + addr :
'port ' + addr.port;
var chalk = require('chalk');
winston.info();
winston.info(chalk.green('Listening on ' + bind));
});
}
|
const Discord = require('discord.js')
const client = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
client.login("")
let servers = []; //Array of servers
let notificationUsers = []; // list of users
let events = []; // This will be array of events
let signUpChannel = '';
let submitRemindersChannel = '';
let approveRemindersChannel = '';
var signUpMessageId = '';
//database stuff
const fs = require('fs') //importing file save
var xpPathUserData = 'userData.json'
var xpReadUserData = fs.readFileSync(xpPathUserData);
var xpFileUserData = JSON.parse(xpReadUserData); //ready for use
var xpPathReminders = 'notifications.json'
var xpReadReminders = fs.readFileSync(xpPathReminders);
var xpFileReminders = JSON.parse(xpReadReminders);
//var xpPathChannel = 'channelData.json'
//var xpReadChannel = fs.readFileSync(xpPathChannel);
//var xpFileChannel = JSON.parse(xpReadChannel);
client.on('ready', () => {
console.log("Connected as " + client.user.tag);
client.user.setActivity("out for you", {type: 'WATCHING'});
loadData();
const signUpMes = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Sign up sheet')
.setDescription('This is the sign up sheet for CoronaTimes class reminders! \n\nHave you ever found yourself trying to cram for a assignment or test that snuck up on you too fast? \n\nThats where I come in, Daily reminders in the morning via DM of assignments due in the future, tests coming up or any other important events coming up! \n\nSimply signup and react to the classes you are in. To unsubscribe simply un react to the message! \n\nUsers can use the request-reminder channel submit reminders for a class using the specified format. \n\n Please feel free to DM the creator @CoronaTime if you have any problems or to request new features!!')
.setAuthor('CoronaTime', 'https://assets.prucenter.com/brew-images/_639x639_crop_center-center_none/corona.jpg?mtime=20180403160236&focal=none')
.addFields(
{ name: 'React: 🍺', value: 'To Sign Up!'},
{ name: 'React: 0️⃣', value: 'For ENSF 409', inline:true},
{ name: 'React: 1️⃣', value: 'For ENCM 369', inline:true},
{ name: 'React: 2️⃣', value: 'For ENEL 327', inline:true},
{ name: 'React: 3️⃣', value: 'For Math 271', inline:true},
{ name: 'React: 4️⃣', value: 'For CPSC 319', inline:true},
{ name: 'React: 5️⃣', value: 'For BMEN 309', inline:true},
{ name: 'React: 6️⃣', value: 'For COMS 363', inline:true},
{ name: 'React: 7️⃣', value: 'For ENGG 209', inline:true},
{ name: 'React: 8️⃣', value: 'For ENGG 481', inline:true}
)
.setFooter('Disclamer: This is in no way a substitute for not knowing when things are due. This is only a additional tool to remind you when a class has something due. If you miss an assignment because my bot did not remind you it is in no way my responsibility, by signing up you agree to this.');
let signUpChan = client.channels.cache.get(signUpChannel);
if(signUpMessageId == ''){
signUpChan.send(signUpMes).then(signUpMes => {
signUpMes.react('🍺');
signUpMes.react('0️⃣');
signUpMes.react('1️⃣');
signUpMes.react('2️⃣');
signUpMes.react('3️⃣');
signUpMes.react('4️⃣');
signUpMes.react('5️⃣');
signUpMes.react('6️⃣');
signUpMes.react('7️⃣');
signUpMes.react('8️⃣');
signUpMessageId = signUpMes.id;
});
}else{
console.log('test here');
client.channels.cache.get(signUpChannel).messages.fetch(signUpMessageId);
}
const requestMessage = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('HOW TO USE')
.setAuthor('CoronaTime', 'https://assets.prucenter.com/brew-images/_639x639_crop_center-center_none/corona.jpg?mtime=20180403160236&focal=none')
.setDescription('To submit a request for a class notification please follow the format below carefully or it will not be aproved, request will auto delete after sending, DO NOT resend, this is normal. After the request is approved it will be added to the upcoming events for that class and so long as your signed up you will recieve daily reminders until its over.')
.addField('Template:', '!remind [CLASSNAME] [EVENT] [MONTH NUMBER] [DAY NUMBER] [24 HOUR NUMBER] [MINUTE NUMBER] [EITHER AM OR PM]')
.addField('Example for ENSF409 assignment 2 thats due on january 1st at 3:30pm', '!remind ENSF409 Assignment2 1 1 3 30 pm')
.addField('IMPORTANT NOTES:', '1) Write the Class in all caps and no space between course code eg. ENSF409 or ENCM369 or CPSC319 \n\n 2) The Event also should have no spaces in it, for assignment 1, write: Assignment1. For Test 2, write: Test2, however caps doesnt matter for this field. \n\n3) The month, day, hour, and minutes should all be numbers! \n\n 4) The hour MUST be in 24 version for now! \n\n5) The last field simply write "am" or "pm"');
let reqChan = client.channels.cache.get(submitRemindersChannel);
//reqChan.send(requestMessage);
})
function loadData(){
for(let i = 0; i < xpFileUserData.Users.notificationUsers.length; i++){
notificationUsers.push(xpFileUserData.Users.notificationUsers[i]);
console.log(notificationUsers[i]);
}
for(let i = 0; i < xpFileReminders.Reminders.events.length; i++){
var proccessReminder = new reminder(xpFileReminders.Reminders.events[i].theClass, xpFileReminders.Reminders.events[i].theReminder, xpFileReminders.Reminders.events[i].theMonth, xpFileReminders.Reminders.events[i].theDay, xpFileReminders.Reminders.events[i].theHour, xpFileReminders.Reminders.events[i].theMinutes, xpFileReminders.Reminders.events[i].theAmOrPm,xpFileReminders.Reminders.events[i].theAuthor);
events.push(proccessReminder);
console.log(events[i]);
}
}
client.on('messageReactionAdd', (reaction, user) => {
if(user == client.user){
return
}
if(reaction.message.author != client.user){
return
}
if(reaction.message.id == signUpMessageId){
if(reaction.emoji.name == '0️⃣' ){ // ENSF 409
addUserSubscription(user, 'ENSF409')
}
if(reaction.emoji.name == '1️⃣' ){ // ENCM 369
addUserSubscription(user, 'ENCM369')
}
if(reaction.emoji.name == '2️⃣' ){ // ENEL 327
addUserSubscription(user, 'ENEL327')
}
if(reaction.emoji.name == '3️⃣' ){
addUserSubscription(user, 'MATH271')
}
if(reaction.emoji.name == '4️⃣' ){//803802935267164160
addUserSubscription(user, 'CPSC319')
}
if(reaction.emoji.name == '5️⃣' ){
addUserSubscription(user, 'BMEN309')
}
if(reaction.emoji.name == '6️⃣' ){
addUserSubscription(user, 'COMS363');
}
if(reaction.emoji.name == '7️⃣' ){
addUserSubscription(user, 'ENGG209');
}
if(reaction.emoji.name == '8️⃣' ){
addUserSubscription(user, 'ENGG481');
}
if(reaction.emoji.name == '🍺' ){
addUser(user);
}
return
}
if(reaction.message.channel == approveRemindersChannel){
if(reaction.emoji.name == '✅'){
var comps = reaction.message.content.split("\n");
sendAprovedNotice(comps);
var newReminder = new reminder(comps[0] ,comps[1], comps[2], comps[3], comps[4], comps[5], comps[6], comps[7]);
events.push(newReminder);
xpFileReminders["Reminders"] = {events}; //if not, create it
fs.writeFileSync(xpPathReminders, JSON.stringify(xpFileReminders, null, 2));
reaction.message.delete();
}
}
if(reaction.message.channel == approveRemindersChannel){
if(reaction.emoji.name == '❌'){
var comps = reaction.message.content.split("\n");
sendNotAprovedNotice(comps);
reaction.message.delete();
}
}
if(reaction.message.channel != approveRemindersChannel)
if(reaction.emoji.name == '✅'){
reaction.message.delete();
}
return
})
client.on('messageReactionRemove', (reaction, user) => { // For removing notifications.
if(reaction.message.id == signUpMessageId){
if(reaction.emoji.name == '0️⃣' ){ // ENSF 409
console.log('pass');
removeUserSubscription(user, 'ENSF409')
}
if(reaction.emoji.name == '1️⃣' ){ // ENCM 369
removeUserSubscription(user, 'ENCM369')
}
if(reaction.emoji.name == '2️⃣' ){ // ENEL 327
removeUserSubscription(user, 'ENEL327')
}
if(reaction.emoji.name == '3️⃣' ){
removeUserSubscription(user, 'MATH271')
}
if(reaction.emoji.name == '4️⃣' ){//803802935267164160
removeUserSubscription(user, 'CPSC319')
}
if(reaction.emoji.name == '5️⃣' ){
removeUserSubscription(user, 'BMEN309')
}
if(reaction.emoji.name == '6️⃣' ){
removeUserSubscription(user, 'COMS363')
}
if(reaction.emoji.name == '7️⃣' ){
removeUserSubscription(user, 'ENGG209')
}
if(reaction.emoji.name == '8️⃣' ){
removeUserSubscription(user, 'ENGG481')
}
}
return
})
client.on('message', message => {
if(message.author == client.user){
return
}
if(message.channel == submitRemindersChannel){ // submitting request channel
if(message.content.startsWith('!')){ // This will be for submitting reminders
if(message.content.substring(0,7) == '!remind'){
var event = message.content.substring(8);
var commands = event.split(" ");
commands.push(message.author.id)
notificationRequest(commands);
message.delete();
}
}
if(message.author != '301384462153809921'){
message.delete();
}
}
if(message.content == "!getReminders"){
getReminders(message.author);
}
return
})
function sendNotAprovedNotice(comps){
let deniedMessage = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Reminder Denied')
.setAuthor('CoronaTime', 'https://assets.prucenter.com/brew-images/_639x639_crop_center-center_none/corona.jpg?mtime=20180403160236&focal=none')
.setDescription('Your Reminder request for ' + comps[0] + ' ' + comps[1] + ' has been denied')
.setFooter("React with checkmark to delete");
client.users.cache.find(user => user.id == comps[8]).send(deniedMessage).then(summary => {
summary.react('✅');
})
}
function sendAprovedNotice(comps){
let approveMessage = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Reminder Approved')
.setAuthor('CoronaTime', 'https://assets.prucenter.com/brew-images/_639x639_crop_center-center_none/corona.jpg?mtime=20180403160236&focal=none')
.setDescription('Your Reminder request for ' + comps[0] + ' ' + comps[1] + ' has been approved!')
.setFooter("React with checkmark to delete");
client.users.cache.find(user => user.id == comps[7]).send(approveMessage).then(summary => {
summary.react('✅');
})
}
function notificationRequest(commands){ // should send mods a message in a mod group chat asking if this is ok and if any mod reacts with a checkmark then the reminder should be created and added to events
const requestChannel = client.channels.cache.get(approveRemindersChannel);
requestChannel.send(commands).then(sentcommands => {
sentcommands.react('✅');
sentcommands.react('❌');
})
}
function addUser(user){
for(let i = 0; i < notificationUsers.length; i++){
if(notificationUsers[i].user.id == user.id){
return
}
}
var userName = user.username //user id here
//if (!xpFileUserData[0][userName]) { //this checks if data for the user has already been created
// xpFileUserData[userName] = {userInfo : user, subscriptions: ""}; //if not, create it
// fs.writeFileSync(xpPathUserData, JSON.stringify(xpFileUserData, null, 2));
//}
let newUser = new aUser(user);
notificationUsers.push(newUser);
xpFileUserData["Users"] = {notificationUsers}; //if not, create it
fs.writeFileSync(xpPathUserData, JSON.stringify(xpFileUserData, null, 2));
console.log(notificationUsers[notificationUsers.length - 1].user)
return;
}
class aUser{
constructor(user){
this.user = user;
this.subscriptions = [];
}
}
function addUserSubscription(user, subscription){
for(let i = 0; i < notificationUsers.length; i++){
if(notificationUsers[i].user.id == user.id){
notificationUsers[i].subscriptions.push(subscription);
xpFileUserData[xpFileUserData.Users.notificationUsers[i]] = {subscriptions : notificationUsers[i].subscriptions};
fs.writeFileSync(xpPathUserData, JSON.stringify(xpFileUserData, null, 2));
return
}
}
let pleaseSignUpFirstMessage = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Please Sign Up First')
.setAuthor('CoronaTime', 'https://assets.prucenter.com/brew-images/_639x639_crop_center-center_none/corona.jpg?mtime=20180403160236&focal=none')
.setDescription('Hey ' + user.username + ", please sign up first by reacting to the signup sheet with a 🍺, then un-react and re-react to the class you want to join!")
.setFooter("React with checkmark to delete");
user.send(pleaseSignUpFirstMessage).then(summary => {
summary.react('✅');
});
}
function removeUserSubscription(user, subscription){ // Will be for removing subscriptions could also put in aUser
for(let i = 0; i < notificationUsers.length; i++){
if(notificationUsers[i].user.id == user.id){
for(let j = 0; j < notificationUsers[i].subscriptions.length; j++){
if(notificationUsers[i].subscriptions[j] == subscription){
notificationUsers[i].subscriptions.splice(j, 1);
xpFileUserData[xpFileUserData.Users.notificationUsers[i]] = {subscriptions : notificationUsers[i].subscriptions};
fs.writeFileSync(xpPathUserData, JSON.stringify(xpFileUserData, null, 2));
}
}
}
}
}
class reminder{
constructor(theClass, theReminder, month, day, hour, minutes, amOrPm, Author){
this.theAuthor = Author;
this.theMonth = month;
this.theDay = day;
this.theHour = hour;
this.theRightMonth = month - 1;
this.theMinutes = minutes;
this.theAmOrPm = amOrPm
this.theClass = theClass;
this.theReminder = theReminder;
console.log(month);
this.dueDate = new Date(2021, month - 1, day, hour, minutes, 0 ,0);
this.thedate = new Date(2021, month - 1, day, hour, minutes, 0, 0).getTime();
console.log(this.thedate);
console.log('created reminder')
}
requestReminder(index){
for(let j = 0; j < notificationUsers[index].subscriptions.length; j++){
if(notificationUsers[i].subscriptions[j] == this.theClass){
var summary = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(this.theClass + " " + this.theReminder)
.setAuthor('CoronaTime', 'https://assets.prucenter.com/brew-images/_639x639_crop_center-center_none/corona.jpg?mtime=20180403160236&focal=none')
.setDescription("Due: " + this.dueDate.toDateString() + " at " + this.theHour + ":" + this.theMinutes)
.setFooter("React with checkmark to delete");
client.users.fetch(notificationUsers[index].user.id).then(user => {
user.send(summary).then(message => message.react('✅'));
})
}
}
}
sendReminder(){
for(let i = 0; i < notificationUsers.length; i++){
for(let j = 0; j < notificationUsers[i].subscriptions.length; j++){
if(notificationUsers[i].subscriptions[j] == this.theClass){
var summary = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle(this.theClass + " " + this.theReminder)
.setAuthor('CoronaTime', 'https://assets.prucenter.com/brew-images/_639x639_crop_center-center_none/corona.jpg?mtime=20180403160236&focal=none')
.setDescription("Due: " + this.dueDate.toDateString() + " at " + this.theHour + ":" + this.theMinutes)
.setFooter("React with checkmark to delete");
client.users.fetch(notificationUsers[i].user.id).then(user => {
user.send(summary).then(message => message.react('✅'));
})
}
}
}
}
}
function getReminders(user){
for(let i = 0; i < notificationUsers.length; i++){
if(notificationUsers[i].id == user.id){
for(let j = 0; j < events.length; j++){
events[j].requestReminder(i);
}
return;
}
}
}
function checkForFinishedEvents(){ // Check if any event in the events list is over every day
var refDate = new Date().getTime();
for(let i = 0; i < events.length; i++){
if(events[i].thedate < refDate){
events.splice(i, 1);
xpFileReminders["Reminders"] = {events}; //if not, create it
fs.writeFileSync(xpPathReminders, JSON.stringify(xpFileReminders, null, 2));
console.log("reminder removed");
}
}
}
setInterval( function() { // sends a daily reminder to all reminders in the events array
checkForFinishedEvents();
console.log("Sending Messages")
for(let i = 0; i < events.length; i++){
events[i].sendReminder();
}
}, 60000) //86400000 is 1 day
|
import React from 'react'
import { StaticQuery, graphql } from 'gatsby'
const getSiteData = graphql`
query {
site {
siteMetadata {
title
}
}
}
`
const StaticQueryMethod = () => {
return (
<StaticQuery query={getSiteData} render={data => {
console.log(data)
return <div>
<h2>title: {data.site.siteMetadata.title}</h2>
</div>
}}/>
)
}
export default StaticQueryMethod
|
/*eslint func-names: 0*/
'use strict';
var assert = require('chai').assert;
// var _ = require('lodash');
// var O = require('observed');
// var sinon = require('sinon');
describe('Stock Module', function() {
});
|
import React from "react";
import "./../App.css";
export default function Menu(props) {
return (
<div>
<i className="fas fa-bars sidebarOpen" onClick={props.sideBarOpen}></i>
</div>
);
}
|
import React, { Component } from 'react';
import { Select, Table, Modal, Button, Popover, Icon, message } from 'antd';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { observer } from 'mobx-react';
import http from 'common/http';
import utils from 'common/utils';
import { extractPath } from 'common/path';
import moment from 'moment';
import styles from './CacheManager.scss';
import StandardTable from 'components/StandardTable';
import NonModalDialog from 'components/NonModalDialog';
const PREFIX = 'flow-cachemgr';
const cx = utils.classnames(PREFIX, styles);
/**
* 缓存管理(有许多无用的注释,仅此一页,做学习交流之用,其他页面不会有这么多注释的)
*/
@observer
class CacheManager extends Component {
//将表格配置参数定义在全局state域中,兼初始化state的作用
state = {
selectedKeys: [],//被选择行所记录的行索引号记录数组
selectedRows: [],//被选择行所记录的行记录数组,数组的每个对象按顺序代表选中的行数据
formValues: { "state": "1" },//查询参数对象,因为一般的查询条件放在查询表单中,所以此处是命名formValue
/**分页导航信息栏信息,具体配置可见“http://ant.design/components/pagination/” */
pagination: {
/**对象的Key加不加""都是一样的,加了更严格,加比较好*/
"showSizeChanger": true,//是否支持变更页面展示条数
"showQuickJumper": true,//是否支持快速跳页
"current": 1,//当前所在页数
"pageSize": 10,//默认页面展示行数
"total": 0 //是否当页完全展示所有项,0-否;1-是
//"pageSizeOptions": [10, 25, 50, 75, 100],//与showSizeChanger一起,可选择每页展示数量
// "size": "small",//表格底部分页导航栏大小,默认是""
// "hideOnSinglePage": true,//在单页是否隐藏寻呼机
// "itemRender": (
// (page, type, originalElement) => {
// console.log("值page:", page);
// console.log("值type:", type);
// console.log("值originalElement:", originalElement);
// return (<p>Hollow World!</p>);
// }
// ),//自定义项innerHTML
// "showTotal": ((total, range) => {
// console.log("值total:", total);
// console.log("值range:", range);
// }
// ),//是否展示表格记录总数和分页数量
// "onChange": ((current, pageSize, pagination) => { }),//一个回调函数,页码发生变化时执行,以产生的页码和页大小为参数
// "onShowSizeChange": ((current, size) => { console.log("页面展示数量发生改变") })//当页大小改变执行
},
sorter: {},//排序字段
filtersArg: {},//过滤参数,排序和过滤参考“http://design.alipay.com/develop/web/components/table/”
modalName: '',//用以弹出模态框,当此值发生改变时,会重绘页面对象,充分利用this.setStatus({})进行操作
chooesValue: '',//刷新类型选择下拉框
isloading: false, //是否正在加载中
}
/**构造器 */
constructor(props) {
super(props);
}
/** 已插入真实 DOM 之后调用*/
componentDidMount() { }
/** 已移出真实 DOM 之前*/
componentWillUnmount() { }
/**提示框弹出控制部分 */
//取消
handleOk = (e) => {
//console.log(e);
this.setState({
modalName: ''
});
}
//OK
handleCancel = (e) => {
//console.log(e);
this.setState({
modalName: ''
});
}
/**下拉选择框响应事件 */
handleChange = (value) => {
//不调用setState是不想引起重绘
this.state.chooesValue = value;
}
/**
* 刷新对话框选中下拉框的值
*/
/**展示模态对话框的函数,主要是利用了this.setStatus({})赋值页面重绘的特性 */
showModals = (modalName) => {
/**先判断是否选中了记录 */
if (this.state.selectedKeys.length == 0) {//未选中记录
console.log("执行到此处0000:", this.state.selectedKeys.length);
/**未选中记录。提示错误 */
message.warn("请至少选择一台服务器刷新缓存!");
} else {//选中记录
this.setState({
modalName
})
}
}
/**表格重绘后会触发render()函数,并调用renderModal方法*/
renderModal = () => {
if (this.state.modalName) {
console.log("执行到此处选择数组:", this.state.selectedKeys.length);
}
if (this.state.modalName == 'refreshModle') {
/**非模态框方式 */
// return (
// <NonModalDialog
// title={'刷新缓存配置'}
// visible={!this.state.modalName == ''}
// onCancel={
// //取消函数,利用了setState的重绘机制
// () => {
// this.setState({
// modalName: ''
// });
// }}>
// <div>
// <Select defaultValue="all" style={{ width: 120 }} onChange={this.handleChange}>
// <Option value="all">全部</Option>
// <Option value="refreshProcessDefineCache">流程模板缓存</Option>
// <Option value="refreshTacheDefCache">环节缓存</Option>
// <Option value="refreshReturnReasonConfigCache">退单原因缓存</Option>
// <Option value="refreshProcessParamDefCache">流程参数定义缓存</Option>
// </Select>
// </div>
// <div>
// <Button.Group style={{ 'text-align': 'center' }} >
// <Button onClick={() => {
// //相当于隐藏了模态框
// this.reFreshCache();
// }}>刷新</Button>
// <Button onClick={() => {
// //相当于隐藏了模态框
// this.setState({
// modalName: ''
// })
// }}>取消</Button>
// </Button.Group>
// </div>
// </NonModalDialog>
// );
/**模态框方式 */
return (
<Modal
title={'刷新缓存配置'}
visible={!this.state.modalName == ''}
onCancel={this.handleCancel}
onOK={this.handleOk}
footer={[
<Button type="primary" icon="reload" loading={this.state.loading} onClick={this.reFreshCache}>刷新</Button>,
<Button onClick={this.handleCancel}>取消</Button>,
]}
//style={{'text-align': 'center' }}
>
<div style={{ 'textAlign': 'center' }}>
<Select defaultValue="all" style={{ width: '30%' }} onChange={this.handleChange}>
<Option value="all">全部</Option>
<Option value="refreshProcessDefineCache">流程模板缓存</Option>
<Option value="refreshTacheDefCache">环节缓存</Option>
<Option value="refreshReturnReasonConfigCache">退单原因缓存</Option>
<Option value="refreshProcessParamDefCache">流程参数定义缓存</Option>
</Select>
</div>
{/**
//原本和非模态框配合使用
<div>
<Button.Group style={{ 'text-align': 'center' }} >
<Button onClick={() => {
//相当于隐藏了模态框
this.reFreshCache();
}}>刷新</Button>
<Button onClick={() => {
//相当于隐藏了模态框
this.setState({
modalName: ''
})
}}>取消</Button>
</Button.Group>
</div> */}
</Modal>
);
}
return null;
}
/**
* 处理表格行选中事件,将选中的行标记rowKeys存在state域中,并触发表格重绘
* @param keys 被选中的行的所有行索号数组,即rowKeys,[id0,...,idn]数组
* @param rows 被选中的行的所有对象数组,即[{rowdata0},....,{rowdatan}]
*/
handleSelectOnChange = (keys, rows) => {
this.setState({
selectedKeys: keys,
selectedRows: rows
});
};
/**页面初始化数据查询请求 */
loadData = (current, pageSize, pagination) => {
/**打印默认参数,看看是什么信息 */
// console.log("执行此处current", current);
// console.log("执行此处pageSize", pageSize);
// console.log("执行此处pagination", pagination);
//将查询请求的参数获取到
const { formValues } = this.state;//解构赋值(ES6语法),查询请求参数对象
//将forValues的内容复制到{}并表示成param做查询条件
let param = Object.assign({}, formValues);
//param = _.merge(param, pagination);
param.pageSize = pagination.pageSize;//页面展示条数,分页值
//param.pageIndex = current;//当前页
//param.sortColumn = 'id';//排序字段,与数据库字段一致
//param.sortOrder = 'desc';//排序字段方式
//param.systemCode = session.currentTendant.tenantCode;//系统代码
//【说明】--------类似于adjx对服务端的异步请求,以下是格式说明--------【说明】
// http.post(
// txcode,//请求交易码(控制器拦截路径)
// data = { bean: '服务端被调用bean', method: '被调用bean中被调用的方法名', param: '对象请求参数' },
// configparam = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }//post请求文本格式
// )
// .then(//then表示在异步请求有结果之后再执行
// successCallbackFunction(res),//异步请求成功回调函数
// errCallbackFunction(res)//异步请求失败回调函数
// )
return http.post(
'/call/call.do', //请求交易码(控制器拦截路径),此处是个总控
/** 请求参数部分*/
{
bean: 'CacheManagerServ',//服务端被调用bean
method: 'qryServerList',//被调用bean中被调用的方法名
param: param//请求参数(一般就是查询条件)
},
{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'//post请求文本格式
}
).then(//then表示在异步请求有结果之后再执行
//post成功回调函数,res=>等价于function(res){}
res => {
/**成功处理 */
const returnData = JSON.parse(res);
if (returnData) {
//console.log("执行此处0000", returnData);
///console.log(returnData);//控制台打印返回报文
return {
data: {
rows: returnData,
pagination: {
//三点表达式表示把...pagination内容putAll进外面的pagination,可查看ES6的解构赋值内容
...pagination
}
}, selectedRowKeys: []
}
} else {
/**若返回报文为空,则表格没数据 */
return { data: { rows: [], pagination }, selectedRowKeys: [] }
}
},
/**异步请求失败回调函数 */
res => res//直接返回失败报文
);
}
/**刷新缓存请求参数 */
reFreshCache = () => {
console.log("刷新缓存");
//首先要确保isloading=true,不用setState是防止页面重绘
this.state.isloading = true;
let serverAddrsArray = [];
for (let map of this.state.selectedRows) {
serverAddrsArray.push(map.serverAddress);
}
let param = {};
param.cacheType = this.state.chooesValue;
param.serverAddrs = serverAddrsArray;
//param.systemCode = session.currentTendant.tenantCode;//系统代码
//【说明】--------类似于adjx对服务端的异步请求,以下是格式说明--------【说明】
// http.post(
// txcode,//请求交易码(控制器拦截路径)
// data = { bean: '服务端被调用bean', method: '被调用bean中被调用的方法名', param: '对象请求参数' },
// configparam = { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }//post请求文本格式
// )
// .then(//then表示在异步请求有结果之后再执行
// successCallbackFunction(res),//异步请求成功回调函数
// errCallbackFunction(res)//异步请求失败回调函数
// )
return http.post(
'/call/call.do', //请求交易码(控制器拦截路径),此处是个总控
/** 请求参数部分*/
{
bean: 'CacheManagerServ',//服务端被调用bean
method: 'refreshCache',//被调用bean中被调用的方法名
param: param//请求参数(一般就是查询条件)
},
{
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'//post请求文本格式
}
).then(//then表示在异步请求有结果之后再执行
//post成功回调函数,res=>等价于function(res){}
res => {
/**成功处理 */
//解除加载,不用setState是防止页面重绘
this.state.isloading = false;
if (res == '"fail"') {
message.error('刷新失败');
} else {
message.success('刷新成功');
}
},
/**异步请求失败回调函数 */
res => {
//直接返回失败报文
message.error('刷新失败');
}
);
}
/**初始化查询数据方法loadData返回promise对象中的回调函数示例*/
/**异步获取的加载数据存放变量*/
// let LoadData = {
// data: {
// rows: returnData.rows,
// /**分页信息对象,同上*/
// pagination: {
// pageSize: 10,
// current: 1,
// total: 0,
// showQuickJumper: true,
// onChange: ((current, pageSize, pagination) => {
// })
// }
// }, selectedRowKeys: []
// };
/**返回报文数据格式(F12请求response截取) */
// var backdata = [ {
// "id" : 1,
// "serverName" : "serverj",
// "serverAddress" : "127.0.0.1:8088",
// "state" : "1",
// "comments" : ""
// }, {
// "id" : 2,
// "serverName" : "servert",
// "serverAddress" : "127.0.0.1:8080",
// "state" : "1",
// "comments" : ""
// } ];
render() {//页面调用时会调用此方法将html(包括组件的Html)添加到Dom节点中(通俗的话就是绘制)
/**状态位转义数组 */
const cacheStatusArray =
[{
value: '0',
text: '失效'
}, {
value: '1',
text: '有效'
}];
/**状态位转义方法 */
const convertStatsToDes = (arr, val) => {
const found = _.find(arr, x => x.value == val);
return found ? found.text : '';
};
/**表格标题部分 */
const tableColumnsTitle = [
{ title: '服务器标识', dataIndex: 'id', width: 120, sortable: true },
{ title: '服务器名称', dataIndex: 'serverName', width: 120 },
{ title: '服务器地址', dataIndex: 'serverAddress', width: 120 },
//{ title: '服务器状态', dataIndex: 'state', width: 120 },
{
title: '服务器状态', dataIndex: 'state', width: 100,
render(val) {
return convertStatsToDes(cacheStatusArray, val);
}
},
{ title: '备注', dataIndex: 'comments', width: 150 }
];
/**表格查询条件表单栏html部分(仅做展示,本例不实际使用) */
// let queryFormDiv = <div key={'search'} style={{ width: '800px', margin: '-17.5px 10px -17.5px 0px', position: 'relative', height: '100%', display: 'inline-block' }}>
// //使用了组件
// <DynamicSearchForm ref='instanceSearchForm'
// style={{ position: 'absolute', width: '800px', top: '-15px' }}//样式
// formConfig={formConfig}//查询输入框的相关配置,建议另起一个文件存放
// hideFooter={true}//是否隐藏下分割线
// onSubmit={this.handleSearch}//查询提交触发执行方法,与laodData异曲同工
// />
// </div>;
/**页面初始化查询请求参数(只执行一次)*/
const intiTableDefaultParam = {
rows: [],//表格行数据,没查询条件前肯定是没有数数据的
/**表格底部的分页信息栏配置对象 */
//pagination:this.state.pagination//不建议写成这样,因为this.state.pagination这个值是会变更的
pagination: {
"showSizeChanger": true,//是否支持变更页面展示条数
"showQuickJumper": true,//是否支持快速跳页
"current": 1,//当前所在页数
"pageSize": 10,//默认页面展示行数
"total": 0 //是否当页完全展示所有项,0-否;1-是
/**表格右下角箭头点击事件声明*/
//"pageSizeOptions": [10, 25, 50, 75, 100],//与showSizeChanger一起,可选择每页展示数量
// "size": "small",//表格底部分页导航栏大小,默认是""
// "hideOnSinglePage": false,//在单页是否隐藏表格下方的分页导航栏
// "itemRender": (
// (page, type, originalElement) => {
// console.log("值page:", page);
// console.log("值type:", type);
// console.log("值originalElement:", originalElement);
// if (type == 'prev') {
// return (<p>上一页</p>);
// }
// if (type == 'next') {
// return (<p>下一页</p>);
// }
// if (type == 'page') {
// return (<p>{page}</p>);
// }
// }
// ),//自定义项innerHTML
// "showTotal": ((total, range) => {
// console.log("值total:", total);
// console.log("值range:", range);
// }
// ),//是否展示表格记录总数和分页数量
// "onChange": ((current, pageSize, pagination) => { }),//一个回调函数,页码发生变化时执行,以产生的页码和页大小为参数
// "onShowSizeChange": ((current, size) => { console.log("页面展示数量发生改变") })//当页大小改变执行
}
};
//console.log("执行此处cx", cx);
/**返回组件其实就是将React组件生成的html文本appand进某个指定的元素下面,这里是<div id=app></app> */
return (
/**引入标准表格组件(标签),理解为写table标签的html */
<div style={{ 'padding': '15px' }}>
{/* 按钮栏*/}
<div style={{ 'padding': '10px' }}>
<Button.Group>
<Button type="primary" icon="reload" onClick={() => { this.showModals('refreshModle'); }}>刷新</Button>
</Button.Group>
</div>
{/* 表格栏 */}
<StandardTable
rowKey={'id'}//表格行数据的id(可以理解为数据库表的PK)
columns={tableColumnsTitle} //表格标题项,dataIndex的值为后台返回数据的Key,表格会从返回报文填充进去
data={intiTableDefaultParam} //页面初始化参数
loadData={this.loadData}//展示(绘制)表格的数据来源,this.loadData异步请求方法(查询实现请求,类似于ajax)
selectType={'multi'} //设置表格单选还是多选,值可选'multi',’single’,’radio’,false,默认为单选
allowChangeSelectType={true}//为false时不允许改单选或者多选的类型
rowSelection={{ type: 'multi' }}
clicktoSelect={true}//是否点中“行”就选择
onSelectChange={this.handleSelectOnChange}//表格元素(行)被选中事件触发选中处理动作
//extra={queryFormDiv} // 查询表单模块(仅做调用参考值)
//x轴方向自适应;y轴方向以示窗窗口高度减去300px自适应上下滚动
scroll={{ x: true, y: (document.querySelector('body').clientHeight - 300) }} />
{
//实际上只有重绘会调用
this.renderModal()
}
</div>
);
}
}
/**组件(标签)对象(实例)无强制检验属性格式 */
CacheManager.propTypes = {};
/**组件(标签)对象(实例)无强默认属性 */
CacheManager.defaultProps = {};
/**发布组件(标签),使其他组件可引用 */
export default CacheManager;
|
import React from "react";
import ReactDOM from "react-dom";
import routes from "../react-router/routers";
ReactDOM.render(
routes,document.getElementById("app")
)
|
"use strict";
angular.module('workshop.clock', [])
.component('clock', {
template: '{{$ctrl.now | date:"HH:mm:ss"}}',
controller: function($interval, $scope) {
var vm = this;
var timer = $interval(function() {
vm.now = new Date();
console.log(new Date());
}, 1000);
$scope.$on('$destroy', function() {
$interval.cancel(timer);
});
}
});
|
import { renderString } from '../../src/index';
describe(`Calculates the md5 hash of the given object`, () => {
it(`unnamed case 0`, () => {
const html = renderString(`{{ content.absolute_url|md5 }}`);
});
});
|
import { string } from 'prop-types';
import React, { Suspense } from 'react';
import { Route } from 'react-router-dom';
import { Details, Home } from 'components/pages';
import { Loader } from 'components/widgets';
import withStyle from './style';
const App = ({ className }) => (
<div className={className}>
<header>
<h2>Parfum</h2>
</header>
<main>
<Suspense fallback={<Loader />}>
<Route path="/" component={Home} exact />
<Route path="/:id" component={Details} />
</Suspense>
</main>
<footer>Lorem ipsum</footer>
</div>
);
App.propTypes = {
className: string.isRequired,
};
App.defaultProps = {};
export default withStyle(App);
|
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index'
const initialState={}; //初始状态
const middleware=[thunk]; //中间件,使用redux-thunk中间件,改造store.dispatch,使得后者可以接受函数作为参数。因此,异步操作的第一种解决方案就是,写出一个返回函数的 Action Creator,然后使用redux-thunk中间件改造store.dispatch
//redux调试工具代码
const store = createStore(rootReducer,initialState,compose(
applyMiddleware(...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
));
// 3个参数,第一个reducer(可以看做是一个方法,可以有多个,所以暂且用()=>{}箭头函数,,第二个状态,第三个appliMiddleware中间件(它是 Redux 的原生方法,作用是将所有中间件组成一个数组,依次执行。)
export default store
|
import React from "react";
import { connect } from "react-redux";
// import { mainRedcuer } from "./lib/store";
import { hot } from "react-hot-loader";
import { Normalize } from "styled-normalize";
import { Routes } from "./routes";
import { GlobalStyles } from "./global-styles";
import "antd/dist/antd.css";
import { Layout } from "antd";
// import { Link } from "react-router-dom";
// import { API_HOST } from "./lib";
import { Header } from "./features/header";
// const { SubMenu } = Menu;
const { Content } = Layout;
const _MainComp = () => {
// console.log("props", props);
return (
<>
<Normalize />
<GlobalStyles />
<Layout style={{ flex: 1, background: "#fff" }}>
<Layout style={{ background: "#fff" }}>
<Header />
</Layout>
<Layout style={{ background: "#fff" }}>
<Content style={{ padding: 30 }}>
<Routes />
</Content>
</Layout>
</Layout>
</>
);
};
const MainComp = connect(
(state) => ({
// user: state.main.user,
}),
(dispatch) => ({})
)(_MainComp);
export const App = hot(module)(() => (
<>
<MainComp />
</>
));
|
lang="pt_PT"
datatable_lang="pt_datatable.txt"
locale={
"":"",
"PENDING":"PENDENTE",
"DEPLOYING":"A INSTANCIAR",
"RUNNING":"A CORRER",
"UNDEPLOYING":"A CANCELAR INSTANCIAÇÃO",
"WARNING":"AVISO",
"DONE":"FINALIZADO",
"FAILED_UNDEPLOYING":"CANCELAMENTO_DE_INSTANCIACAO_FALHADO",
"FAILED_DEPLOYING":"INSTANCIACAO_FALHADA",
"SCALING":"A ESCALAR",
"FAILED_SCALING":"ESCALONAMENTO_FALHADO",
"COOLDOWN":"ARREFECIMENTO",
"INIT":"INIC",
"MONITORING_MONITORED":"MONITORIZAR_MONITORIZADO",
"MONITORED":"MONITORIZADO",
"ERROR":"ERRO",
"DISABLED":"DESATIVADO",
"MONITORING_ERROR":"ERRO_DE_MONITORIZAÇÃO",
"MONITORING_INIT":"MONITORIZAÇÃO_A_INICIAR",
"MONITORING_DISABLED":"MONITORIZAÇÂO_DESATIVADA",
"OFFLINE":"DESLIGADO",
"UPDATE":"ATUALIZAR",
"ON":"LIGADO",
"RETRY":"TENTAR NOVAMENTE",
"OFF":"DESLIGADA",
"READY":"PRONTO",
"LOCKED":"BLOQUEADO",
"UNKNOWN":"DESCONHECIDO",
"IMAGE":"IMAGEM",
"VMTEMPLATE":"MODELOVM",
"SERVICE_TEMPLATE":"MODELO_SERVICO",
"USED":"EM USO",
"CLONE":"CLONAR",
"DELETE":"APAGAR",
"USED_PERS":"EM_USO_PERS",
"LOCKED_USED":"BLOQUEADA_USADA",
"LOCKED_USED_PERS":"BLOQUEADA_USADA_PERS",
"OS":"SO",
"CDROM":"CDROM",
"DATABLOCK":"DATABLOCK",
"KERNEL":"KERNEL",
"RAMDISK":"RAMDISK",
"CONTEXT":"CONTEXTO",
"LCM_INIT":"LCM_INIT",
"PROLOG":"PROLOG",
"BOOT":"ARRANQUE",
"MIGRATE":"MIGRAR",
"SAVE":"GUARDAR",
"EPILOG":"EPILOG",
"SHUTDOWN":"ENCERRAR",
"FAILURE":"FALHA",
"CLEANUP":"A LIMPAR",
"HOTPLUG":"HOTPLUG",
"SNAPSHOT":"SNAPSHOT",
"DISK_RSZ":"DISK_RSZ",
"SYSTEM":"SISTEMA",
"FILE":"FICHEIRO",
"Virtual Routers":"Roteador Virtual",
"Virtual Router":"Router Virtual",
"Create Cluster":"Criar Cluster",
"Create":"Criar",
"Update Cluster":"Atualizar Cluster",
"Update":"Atualizar",
"Delete":"Apagar",
"Info":"Info",
"Attributes":"Atributos",
"VNets":"VNets",
"Hosts":"Anfitriões",
"Datastores":"Datastores",
"ID":"ID",
"Name":"Nome",
"Labels":"Rótulos",
"Please select a Cluster from the list":"Por favor selecione um Cluster da lista",
"You selected the following Cluster:":"Selecionou o seguinte Cluster:",
"Please select one or more clusters from the list":"Por favor selecione um ou mais clusters da lista",
"You selected the following clusters:":"Selecionou os seguintes clusters:",
"Cluster created":"Cluster criado",
"System":"Sistema",
"Create Datastore":"Criar Datastore",
"Please select a cluster for this datastore":"Por favor selecione um cluster para esta datastore",
"Import vCenter Datastores":"Importar datastores de vCenter",
"Import":"Importar",
"Select cluster":"Selecionar cluster",
"Change owner":"Alterar dono",
"Select the new owner":"Selecione o novo dono",
"Change group":"Alterar grupo",
"Select the new group":"Selecione o novo grupo",
"Enable":"Ativar",
"Disable":"Desativar",
"vCenter information":"Informação Vcenter",
"Clusters":"Clusters",
"Images":"Imagens",
"Owner":"Dono",
"Group":"Grupo",
"Capacity":"Capacidade",
"Cluster":"Cluster",
"Basepath":"Caminho base",
"TM MAD":"TM MAD",
"DS MAD":"DS MAD",
"Type":"Tipo",
"Status":"Estado",
"Please select a datastore from the list":"Por favor selecione uma datastore da lista",
"You selected the following datastore:":"Selecionou a seguinte datastore:",
"Please select one or more datastores from the list":"Por favor selecione uma ou mais datastores da lista",
"You selected the following datastores:":"Selecionou as seguintes datastores",
"Datastore created":"Datastore criada",
"Virtual Machines":"Máquinas Virtuais",
"There are no Virtual Machines":"Não há Máquinas Virtuais",
"ALL":"TUDO",
"GUEST STATE":"",
"VMWARETOOLS RUNNING STATUS":"",
"VMWARETOOLS VERSION":"",
"VMWARETOOLS VERSION STATUS":"",
"VM Template":"Modelo de VM",
"saved successfully":"guardado com sucesso",
"":"VM cloning in the background. The Template will appear as soon as it is ",
"SAVING IMAGE":"A GUARDAR IMAGEM",
"POWERING OFF":"A DESLIGAR",
"UNDEPLOYED":"NAO INSTANCIADO",
"DELETING":"A APAGAR",
"Templates":"Modelos",
"There are no templates available":"Não há modelos disponíveis",
"No labels defined":"Sem rótulos definidos",
"Create a template by saving a running Virtual Machine":"Criar um modelo guardando uma Máquina Virtual que esteja a correr",
"Unshare":"Não partilhar",
"SHARED":"PARTILHADO",
"Share":"Partilhar",
"Handle with care! This action will immediately destroy the template":"Lidar com precaução! Esta ação irá destruir imediatamente o modelo",
"and the image associated.":"e a imagem associada.",
"The template":"O modelo",
"":"and the image associated will be shared and all the users will be able to ",
"Share template":"Partilhar modelo",
"":"and the image associated will be unshared and the users will not be able to ",
"Unshare template":"Desativar partilha do modelo",
"Services":"Serviços",
"There are no Services":"Não há Serviços",
"Cannot connect to OneFlow server":"Impossível ligar ao servidor OneFlow",
"VMs":"VMs",
"Change Cardinality":"Alterar Cardinalidade",
"The cardinality for this role cannot be changed":"A cardinalidade para este papel não pode ser alterada",
"Dismiss Alert":"Fechar Alerta",
"Number of VMs for Role":"Número de VMs para o Role",
"Be careful, this action will immediately destroy your Service":"Seja cuidadoso, esta ação irá destruir imediatamento o seu Serviço",
"All the information will be lost!":"Toda a informação será perdida!",
"Be careful, this action will immediately shutdown your Service":"Cuidado, esta operação vai desligar o seu service immediatamente",
"Shutdown":"Desligar",
"FAILED UNDEPLOYING":"FALHA NA DESALOCAÇÃO",
"FAILED DEPLOYING":"FALHA NA INSTANCIAÇÃO",
"FAILED SCALING":"FALHA NO ESCALAMENTO",
"Instantiate Virtual Router Template":"Instanciar o Modelo de Router Virtual",
"Instantiate":"Instanciar",
"Virtual Router created":"Roteador virtual criado",
"Failed to create VMs. Virtual Router may need to be deleted manually.":"Falha ao criar VMs. O Router Virtual pode precisar de ser apagado manualmente.",
"Custom Attributes":"Atributos personalizáveis",
"Dashboard":"Página de controlo",
"Create Host":"Criar Anfitrião",
"Select the destination cluster":"Selecione o cluster de destino",
"Offline":"Off-line",
"Delete host":"Apagar anfitrião",
"ESX":"ESX",
"Zombies":"Zombies",
"PCI":"PCI",
"Graphs":"Gráficos",
"Allocated":"Alocado",
"Real":"Real",
"Total":"Total",
"Total +/- reserved":"Total +/- reservado",
"Wilds":"Wilds",
"Could not import the wild VM ":"",
"Import Wilds":"Importar Wilds",
"VM imported":"VM importada",
"Cannot contact server: is it running and reachable?":"Não é possível contactar o servidor: está em execução ou contactável?",
"RVMs":"RVMs",
"Real CPU":"CPU Real",
"Allocated CPU":"CPU Alocado",
"Real MEM":"Memória Real",
"Allocated MEM":"Memória alocada",
"IM MAD":"IM MAD",
"VM MAD":"VM MAD",
"Last monitored on":"Monitorizada pela última vez em",
"Please select a Host from the list":"Por favor selecione um Anfitrião da lista",
"You selected the following Host:":"Selecionou o seguinte Anfitrião",
"Please select one or more hosts from the list":"Por favor selecione um ou mais anfitriões da lista",
"You selected the following hosts:":"Selecionou os seguintes anfitriões:",
"Allocated Memory":"Memória alocada",
"Real Memory":"Memória real",
"Host created":"Host criado",
"Create Virtual Data Center":"Criar Datacenter Virtual",
"Update Virtual Data Center":"Atualizar Datacenter Virtual",
"Groups":"Grupos",
"Resources":"Recursos",
"Please select a VDC from the list":"Por favor selecione um VDC da lista",
"You selected the following VDC:":"Selecionou o seguinte VDC:",
"Please select one or more VDCs from the list":"Por favor selecione um ou mais VDCs da lista",
"You selected the following VDCs:":"Selecionou os seguintes VDCs:",
"All":"Tudo",
"VDC created":"VDC criado",
"Download App To OpenNebula":"Transferir Aplicação para o OpenNebula",
"Download":"Transferir",
"Create MarketPlace App":"Criar Aplicação no MarketPlace",
"Create MarketPlace App from Image":"Criar Aplicação no MarketPlace a partir de Imagem",
"Version":"Versão",
"Size":"Tamanho",
"State":"Estado",
"Registration Time":"Hora de registo",
"Marketplace":"Loja",
"Zone":"Zona",
"Please select an appliance from the list":"Por favor selecione uma aplicação da lista",
"You selected the following appliance:":"Selecionou a seguinte aplicação:",
"Please select one or more appliances from the list":"Por favor selecione uma ou mais aplicações da lista",
"You selected the following appliances:":"Selecionou as seguintes aplicações:",
"MarketPlace App created":"Aplicação MarketPlace criada",
"Image created":"Imagem criada",
"VM Template created":"Modelo de VM criado",
"Error":"Erro",
"This MarketPlace App resides in Zone ":"Esta Aplicação do MarketPlace reside na Zona",
"":". To delete it you need to switch to that Zone from the zone selector in the",
"Ok":"Ok",
"VM":"VM",
"TOTAL":"TOTAL",
"ACTIVE":"ATIVA",
"FAILED":"FALHADO",
"Create Security Group":"Criar Grupo de Segurança",
"Update Security Group":"Atualizar Grupo de Segurança",
"One or more required fields are missing or malformed.":"Um ou mais campos obrigatórios estão em falta ou mal preenchidos.",
"Clone":"Clonar",
"Commit":"Submeter",
"Please select a security group from the list":"Por favor selecione um grupo de segurança da lista",
"You selected the following security group:":"Selecionou o seguinte grupo de segurança:",
"Please select one or more security groups from the list":"Por favor selecione um ou mais grupos de segurança da lista",
"You selected the following security groups:":"Selecionou os seguintes grupos de segurança:",
"Security Group created":"Grupo de Segurança criado",
"":"Please note: each time the rules are edited, the commit operation is done ",
"TCP":"TCP",
"UDP":"UDP",
"ICMP":"ICMP",
"IPsec":"IPsec",
"Outbound":"Saída",
"Inbound":"Entrada",
"Virtual Network":"Rede virtual",
"Start":"Iniciar",
"Any":"Qualquer",
"Import vCenter Images":"Importar Imagens vCenter",
"Create Image":"Criar imagem",
"Create File":"Criar ficheiro",
"Uploading...":"A transferir...",
"Please select a datastore for this image":"Por favor seleccione a datastore para esta imagem",
"Please select a file to upload":"Por favor selecione o ficheiro para carregar",
"Registering in OpenNebula":"A registar no OpenNebula",
"MarketPlace":"MarktPlace",
"Make persistent":"Tornar persistente",
"Make non persistent":"Tornar não persistente",
"yes":"sim",
"no":"não",
"Snapshots":"Snapshots",
"This will delete all the other image snapshots":"Isto irá apagar todos os outros snapshots de imagem",
"This will delete the image snapshot ":"Isto irá apagar a imagem de snapshot",
"Active":"Ativo",
"Datastore":"Datastore",
"Registration time":"Registo de tempo",
"Persistent":"Persistente",
"#VMS":"#VMS",
"Target":"Alvo",
"Please select an image from the list":"Por favor selecione uma imagem da lista",
"You selected the following image:":"Selecionou a seguinte imagem:",
"Please select one or more images from the list":"Por favor selecione uma ou mais imagens da lista",
"You selected the following images:":"Selecionou as seguintes imagens:",
"Please select one (and just one) Image to export.":"Por favor selecione uma (e apenas uma) Imagem para exportar.",
"This Image resides in Datastore ":"Esta Imagem reside na Datastore",
". The export action is not supported for that Datastore DS_MAD driver.":". A ação de exportar não é suportada para esse controlador de Datastore DS_MAD.",
"Service Templates":"Modelos de Serviço",
"Service Template":"Modelo de Serviço",
"Instantiate VMs":"Instanciar VMs",
"Create Virtual Router":"Criar um roteador virtual",
"This will detach the nic immediately":"Isto irá desassociar o nic de imediato",
"Please select a virtual router from the list":"Por favor selecione um router virtual da lista",
"You selected the following virtual router:":"Selecionou o seguinte router virtual:",
"Please select one or more virtual routers from the list":"Por favor selecione um ou mais routers virtuais da lista",
"You selected the following virtual routers:":"Selecionou os seguintes routers virtuais:",
"Create User":"Criar Utilizador",
"To define secondary groups you need to also set the main group":"Para definir grupos secundários necessita de definir também o grupo principal",
"None":"Nenhuma",
"Password":"Palavra-passe",
"Auth":"Autenticação",
"Quotas":"Quotas",
"Change primary group":"Alterar grupo principal",
"":"This will change the primary group of the selected users. Select the new ",
"Showback":"Estatística de utilização",
"Current password":"Palavra-chave atual",
"Close":"Fechar",
"Accounting":"Contabilidade",
"ascending":"ascendente",
"descending":"descendente",
"Auth driver":"Driver de autenticação",
"Memory":"Memória",
"CPU":"CPU",
"Group ID":"ID de Grupo",
"Hidden User Data":"Dados de Utilizador ocultos",
"Please select a User from the list":"Por favor selecione um Utilizador da lista",
"You selected the following User:":"Selecionou o seguinte Utilizador:",
"Please select one or more users from the list":"Por favor selecione um ou mais utilizadores da lista",
"You selected the following users:":"Selecionou os seguintes utilizadores:",
"User created":"Utilizador criado",
"Default":"Por omissão",
"Create Service":"Criar Serviço",
"Recover":"Recuperar",
"This will delete the selected services":"Isto irá apagar os serviços selecionados",
"Scale":"Escalar",
"Hold":"Pausa",
"Release":"Libertar",
"Suspend":"Suspender",
"Stop":"Parar",
"Reboot":"Reiniciar",
"Power Off":"Encerrar",
"Undeploy":"Cancelar instanciação",
"Terminate":"Terminar",
"Roles":"Papéis",
"The VM is ready":"A VM está pronta",
"Waiting for the VM to be ready":"À espera da VM estar pronta",
"VNC Connection in progress":"Ligação VNC em progresso",
"SPICE Connection in progress":"Ligação SPICE em curso",
"Log":"Registo",
"Please select a Service from the list":"Por favor selecione um Serviço da lista",
"You selected the following Service:":"Selecionou o seguinte Serviço:",
"Please select one or more Services from the list":"Por favor selecione uma ou mais Serviços da lista",
"You selected the following Services:":"Selecionou os seguintes Serviços:",
"Service created":"Serviço criado",
"Update VM Configuration":"Atualizar Configuração de VM",
"Create Virtual Machine":"Criar Máquina Virtual VM",
"You have not selected a host":"Não selecionou um anfitrião",
"is currently running on Host":"está de momento a correr no Anfitrião",
"Cost":"Custo",
"Deploy":"Lançar",
"Migrate":"Migrar",
"live":"live",
"Keeps allocated Host resources. The resume operation happens quickly":"Mantém os recursos de anfitrião alocados. A operação de resumir é rápida",
"Frees Host resources. The resume operation may take long":"Liberta os recursos de anfitrição. A operação de resumir é mais demorada",
"hard":"hard",
" Terminate":"Terminar",
"This will remove information from non-persistent hard disks":"Isto irá remover a informação de discos não persistentes",
"Reschedule":"Recalendarizar",
"Un-Reschedule":"Cancelar Recalendarização",
"retry":"tentar novamente",
"success":"sucesso",
"failure":"falha",
"delete":"apagar",
"delete-recreate":"apagar-recriar",
"":"Recovers a stuck VM that is waiting for a driver operation.",
"VNC":"VNC",
"SPICE":"SPICE",
"Storage":"Armazenamento",
"Disk read bytes":"",
"Disk write bytes":"",
"Disk read IOPS":"",
"Disk write IOPS":"",
"Context":"Contexto",
"Save as in progress":"Guardar em progresso",
"attach/detach in progress":"anexar/desanexar em curso",
"YES":"SIM",
"NO":"NÃO",
"This will detach the disk immediately":"",
"This will delete the disk snapshot ":"Isto irá apagar o snapshot de disco",
"Network":"Rede",
"IP":"IP",
"MAC":"MAC",
"PCI address":"",
"IPv6 ULA":"ULA IPv6",
"IPv6 Global":"IPv6 Global",
"Actions":"Ações",
"Attach nic":"Anexar placa de rede",
"Network Monitoring Attributes":"Atributos de Monitorização de Rede",
"NET RX":"NET RX",
"NET TX":"NET TX",
"NET DOWNLOAD SPEED":"VELOCIDADE DE TRANSFERÊNCIA DA REDE",
"NET UPLOAD SPEED":"VELOCIDADE DE ENVIO DA REDE",
" (VRouter)":"",
"Detach":"Remover",
"Security Group":"Grupo de Segurança",
"Protocol":"Protocolo",
"Range":"Intervalo",
"ICMP Type":"Tipo ICMP",
"Network reception":"Receção de Rede",
"Network transmission":"Transmissão de Rede",
"Network reception speed":"Velocidade de receção de rede",
"Network transmission speed":"Velocidade de transmissão de rede",
"Template":"Modelo",
"Placement":"Colocação",
"#":"#",
"Host":"Anfitrião",
"Action":"Ação",
"UID":"",
"GID":"",
"ReqID":"",
"Change time":"",
"Total time":"Tempo total",
"Prolog time":"Tempo de prólogo",
"No data available in table":"Não há dados disponíveis na tabela",
"Sched Message":"Mensagem de calendarização",
"Placement - Host":"Alocamento - Anfitrião",
"Requirements":"Requisitos",
"Rank":"Posição",
"Placement - Datastore":"Alocamento - Datastore",
"DS Requirements":"Requisitos DS",
"DS Rank":"Posição DS",
"Conf":"Configuração",
"Some ad-block extensions are known to filter the '/log?id=' URL":"",
"Time":"",
"Done":"Finalizado",
"Message":"",
"Add action":"Adicionar ação",
"terminate":"",
"terminate-hard":"",
"hold":"pausar",
"release":"libertar",
"stop":"parar",
"suspend":"suspender",
"resume":"continuar",
"reboot":"desligar e reiniciar",
"reboot-hard":"forçar-reiniciar",
"poweroff":"encerrar",
"poweroff-hard":"forcar-desligar",
"undeploy":"cancelar instanciação",
"undeploy-hard":"forçar-cancelar-instanciacao",
"snapshot-create":"criar-snapshot",
"Add":"Adicionar",
"No actions to show":"Sem ações para mostrar",
"Timestamp":"Timestamp",
"Take snapshot":"Tirar snapshot",
"No snapshots to show":"Sem snapshots para mostrar",
"snapshot in progress":"snapshot em progresso",
"Revert":"Reverter",
"Please select a VM from the list":"Por favor selecione uma VM da lista",
"You selected the following VM:":"Selecionou a seguinte VM:",
"Please select one or more VMs from the list":"Por favor selecione uma ou mais VMs da lista",
"You selected the following VMs:":"Selecionou as seguintes VMs:",
"VM created":"VM criada",
"Used CPU":"CPU utilizado",
"Used Memory":"Memória utilizada",
"IPs":"IPs",
"Start Time":"Hora de Início",
"Hidden Template":"Modelo oculto",
"Virtual Networks":"Redes Virtuais",
"USED IPs":"IPs USADOS",
"MarketPlaces":"",
"Virtual Router VM Templates":"Modelos de VM Roteador Virtual",
"Virtual Router VM Template":"Modelo de VM Roteador Virtual",
"Endpoint URL for marketplace":"",
"Base URL for marketapp":"",
"Marketapp directory path":"",
"This is the document root for http server":"",
"Storage bridge list":"",
"":"Comma separated list of servers to access the image directory if not local",
"Access Key Id":"",
"Secret Access Key":"",
"S3 bucket to store marketapps":"",
"Amazon Region":"",
"Only if using public Amazon S3 service.":"",
"Total Marketplace size in MB":"",
"Signature Version":"",
"":"Leave blank for Amazon AWS S3 service. If connecting to Ceph S3 it **must** ",
"Force Path Style":"",
"":"Leave blank for Amazon AWS S3 service. If connecting to Ceph S3 it **must** ",
"Read block length in MB":"",
"":"Split marketapps into chunks of this size (in MB). You should **never** user",
"Create MarketPlace":"",
"Update MarketPlace":"",
"Apps":"",
"Driver":"Driver",
"Please select a marketplace from the list":"",
"You selected the following marketplace:":"",
"Please select one or more marketplaces from the list":"",
"You selected the following marketplaces:":"",
"MarketPlace created":"",
"Endpoint":"Ponto final",
"Please select a Zone from the list":"Por favor selecione uma Zona da lista",
"You selected the following Zone:":"Selecionou a seguinte Zona:",
"Please select one or more Zones from the list":"Por favor selecione uma ou mais Zonas da lista",
"You selected the following Zones:":"Selecionou as seguintes Zonas:",
"Zone created":"Zona criada",
"Upload a file":"Enviar um ficheiro",
"App":"",
"Instances":"",
"Please select a file from the list":"",
"You selected the following file:":"Selecionou o ficheiro seguinte:",
"Please select one or more files from the list":"Por favor selecione um ou mais ficheiros da lista",
"You selected the following files:":"Selecionou os seguintes ficheiros:",
"File created":"Ficheiro criado",
"Instantiate Service Template":"Instanciar Modelo de Serviço",
"Role":"Papel",
"Create Service Template":"Criar Modelo de Serviço",
"Update Service Template":"Atualizar Modelo de Serviço",
"Can only contain alphanumeric and underscore characters":"",
"Role ":"Papel",
"This will delete the selected templates":"Isto irá apagar os modelos selecionados",
"Please select a Template from the list":"Por favor selecione um Modelo da lista",
"You selected the following Template:":"Selecionou o seguinte Modelo:",
"Please select one or more Templates from the list":"Por favor selecione uma ou mais Modelos da lista",
"You selected the following Templates:":"Selecionou os seguintes Modelos:",
"Service Template created":"Modelo de Serviço criado",
"Cardinality":"Cardinalidade",
"COST":"CUSTO",
"HOUR":"HORA",
"mine":"",
"group":"",
"system":"",
"You must select at least a template configuration":"Deve selecionar pelo menos um modelo de configuração",
"Create Group":"Criar Grupo",
"Update Group":"Atualizar Grupo",
"default":"por omissão",
"Users":"Utilizadores",
"Please select a Group from the list":"Por favor selecione um Grupo da lista",
"You selected the following Group:":"Selecionou o seguinte Grupo:",
"Please select one or more groups from the list":"Por favor selecione um ou mais grupos da lista",
"You selected the following groups:":"Selecionou os seguintes grupos:",
"Group created":"Grupo criado",
"":"Exposes a complete view of the cloud, allowing administrators and advanced ",
"":"Simplified version of the cloud allowing group admins and cloud end-users to",
"Set of views to present valid operations over a vCenter infrastructure":"",
"Full control of the cloud, including virtual and physical resources.":"",
"":"Users are not able to manage hosts and clusters, although they will be able ",
"":"Control of all the resources belonging to a group, with the ability to ",
"":"Simplified view mainly where users can provision new Virtual Machines easily",
"":"View designed to present the valid operations over a vCenter infrastructure ",
"":"View designed to present the valid operations over a vCenter infrastructure ",
"":"View designed to present the valid operations over a vCenter infrastructure ",
"User":"Utilizador",
"Service":"Serviço",
"Files":"Ficheiros",
"File":"Ficheiro",
"Create Virtual Network":"Criar Rede Virtual",
"Update Virtual Network":"Atualizar Rede Virtual",
"Address Range":"Intervalo de Endereço",
"Import vCenter Networks":"Importar Redes vCenter",
"One or more required fields are missing.":"Um ou mais campos obrigatórios estão em falta.",
"End":"",
"Leases":"Atribuições",
"Please select an Address Range from the list":"Por favor selecione um Intervalo de Endereços da lista",
"You selected the following Address Range:":"Selecionou o seguinte Intervalo de Endereços:",
"Reserve":"Reservar",
"Reservation parent":"Reserva mãe",
"This Network is already a reservation":"Esta Rede já está reservada",
"Security":"Segurança",
"VM:":"VM:",
"NET:":"REDE:",
"VR:":"",
"Addresses":"Endereços",
"This will delete all the addresses in this range":"Isto irá apagar todos os endereços neste intervalo",
"The Address Range was not found":"",
"Global prefix":"Prefixo global",
"ULA prefix":"Prefixo ULA",
"Used leases":"Endereços usados",
"Reservation parent AR":"Reserva mãe AR",
"IPAM driver":"",
"V. Routers":"",
"Reservation":"Reserva",
"Bridge":"Ponte",
"VLAN ID":"ID VLAN",
"Please select a network from the list":"Por favor selecione uma rede da lista",
"You selected the following network:":"Selecionou uma das seguintes redes:",
"Please select one or more networks from the list":"Por favor selecione uma ou mais redes da lista",
"You selected the following networks:":"Selecionou as seguintes redes:",
"Yes":"Sim",
"No":"Não",
"Virtual Network created":"Rede Virtual criada",
"VM Templates":"Modelos de VM",
"Group Quotas":"Quotas de Grupo",
"Select group":"Selecione grupo",
"Config":"Configuração",
"Fill in a new password":"Preencha de novo a palavra-passe",
"Passwords do not match":"As palavras-chave não coincidem",
"You have to provide an SSH key":"Tem que fornecer uma chave SSH",
"Settings":"Definições",
"ACLs":"ACLs",
"Access Control Lists":"Lista de Controlo de Acesso",
"Create ACL":"Criar ACL",
"Please select a user to whom the acl applies":"Por favor selecione um utilizador ao qual se aplicam as regras acl",
"Please select a group to whom the acl applies":"Por favor selecione um grupo ao qual se aplicam as regras acl",
"Please select at least one resource":"Por favor selecione pelo menos um recurso",
"Please provide a resource ID for the resource(s) in this rule":"Por favor insira o ID de recurso para os recurso(s) nesta regra",
"Applies to":"Aplica-se a",
"Affected resources":"Recursos afetados",
"Resource ID / Owned by":"ID do recurso / Pertencente a",
"Allowed operations":"Operações permitidas",
"ACL String":"Texto LCA",
"Please select an ACL rule from the list":"Por favor selecione uma regra ACL da lista",
"You selected the following ACL rule:":"Selecionou a seguinte regra ACL:",
"Please select one or more ACL rules from the list":"Por favor selecione uma ou mais regras ACL da lista",
"You selected the following ACL rules:":"Selecionou as seguintes regras ACL:",
"Documents":"Documentos",
"Zones":"Zonas",
"Security Groups":"Grupos de Segurança",
"VDCs":"VDCs",
"Marketplaces":"Loja",
"Marketplace Apps":"Loja de Apps",
"VM Groups":"",
"Cluster ID":"ID do Cluster",
"ACL Rule created":"Regra ACL criada",
"Image":"imagem",
"Create Virtual Machine Group":"",
"Update Virtual Machine Group":"",
"The new role name contains invalid characters.":"",
"Please select a vm group from the list":"",
"You selected the following vm group:":"",
"Please select one or more vm groups from the list":"",
"You selected the following vm groups:":"",
"VM groups":"",
"You have to choose at least two roles.":"",
"Already exists a group role with these values.":"",
"Other":"Outros",
"VM Group":"",
"OS Booting":"Arranque de SO",
"Image ID":"ID de imagem",
"Volatile":"Volátil",
"Network ID":"ID de rede",
"Manual settings":"Configurações manuais",
"Disks and NICs will appear here":"Discos et NICs irão aparecer aqui",
"DISK":"DISCO",
"Disk":"Disco",
"Scheduling":"Agendamento",
"Please select":"Por favor selecione",
"Hybrid":"Híbrido",
"Remote OpenNebula":"",
"Custom":"Personalizado",
"PROVIDER":"FORNECEDOR",
"Provider":"Fornecedor",
"NIC":"NIC",
"Input/Output":"Entrada/Saída",
"General":"Geral",
"Which resource pool you want this VM to run in?":"",
"Set manually":"Definir manualmente",
"Instantiate VM Template":"Instanciar Modelo VM",
"No template selected":"Nenhum modelo selecionado",
"Import vCenter VM Templates":"Importar Templates de VM vCenter",
"Create VM Template":"Criar Modelo de VM",
"Update VM Template":"Atualizar Modelo de VM",
"Create Virtual Router VM Template":"Criar um modelo de roteador virtual",
"Update Virtual Router VM Template":"Atualizar um modelo de roteador virtual",
"":"The template, along with any image referenced by it, will be shared with the",
"":"The template, along with any image referenced by it, will be unshared with ",
"":"This will delete the Template.<br/>You can also delete any Image referenced ",
"Delete all images":"Remover todas as imagens",
"Virtual Data Centers":"Datacenters virtuais",
"Virtual Data Center":"Datacenter virtual",
"Infrastructure":"Infraestrutura",
"Collapse VMs":"",
"Open VMs":"",
"Network Topology":"",
"VNet":"VNet",
"You have to confirm this action":"Tem que confimar esta ação",
"Volatile Disk":"Disco volátil",
"Image was not found":"",
"":"Persistent image. The changes will be saved back to the datastore after the ",
"Non-persistent disk. The changes will be lost once the VM is shut down":"",
"Image state: ":"",
"There are no networks available.":"Não há redes disponíveis",
"Internal server error.":"",
"System disks":"Discos de sistema",
"Running VMs":"VMs a correr",
"Add a new quota":"Adicionar nova quota",
"Edit":"Editar",
"Cancel":"Cancelar",
"Apply":"Aplicar",
"There are no quotas defined":"Não existem quotas definidas",
"Unlimited":"Ilimitado",
"DataCenter":"DataCenter",
"No new clusters found in this DataCenter":"",
"Clear Imported DataCenters":"",
"Location":"Localização",
"Select all %1$s Clusters":"",
"All %1$s Clusters selected.":"",
"%1$s Clusters selected.":"",
"Host created successfully. ID: %1$s":"",
"No new networks found in this DataCenter":"Não foram encontradas novas redes neste Datacenter",
"Clear Imported Networks":"",
"Select all %1$s Networks":"",
"All %1$s Networks selected.":"",
"%1$s Networks selected.":"",
"Optional":"Opcional",
"IP Start":"IP Inicial",
"Global Prefix":"",
"ULA Prefix":"",
"IPv6 address":"",
"Prefix length":"",
"Virtual Network created successfully. ID: %1$s":"",
"No new images found in this datastore":"",
"Clear Imported Images":"",
"Path":"Caminho",
"Select all %1$s Images":"",
"All %1$s Images selected.":"",
"%1$s Images selected.":"",
"Image created successfully. ID: %1$s":"",
"":"Please disable DATASTORE_CAPACITY_CHECK in /etc/one/oned.conf and restart ",
"No new datastores found in this DataCenter":"",
"Clear Imported Datastores":"",
"Total MB":"",
"Free MB":"",
"OpenNebula Cluster IDs":"",
"Select all %1$s Datastores":"",
"All %1$s Datastores selected.":"",
"%1$s Datastores selected.":"",
"Datastores created successfully. IDs: %1$s":"",
"No new templates found in this DataCenter":"Não foram encontrados novos modelos neste Datacenter",
"Clear Imported Templates":"",
"Select all %1$s Templates":"",
"All %1$s Templates selected.":"",
"%1$s Templates selected.":"",
"Could not import the template due to ":"",
"Template created successfully. ID: %1$s":"",
"Importing images and vnets associated to template disks and nics...":"",
"Could not delete the template ":"",
"Not valid attribute":"",
"MB":"MB",
"GB":"GB",
"YES ":"",
"NO ":"",
"Please select a resource from the list":"Por favor selecione um recurso da lista",
"You selected the following resource:":"Selecionou um dos seguintes recursos:",
"Network is unreachable: is OpenNebula running?":"A rede está incontactável: o OpenNebula está em execução?",
"Unauthorized":"Não autorizado",
"<< me >>":"<< eu >>",
"Time range start is mandatory":"O início do intervalo de tempo é obrigatório",
"Time range start is not a valid date. It must be YYYY/MM/DD":"O início de intervalo de tempo não é uma data válida. Deve estar no formato AAAA/MM/DD",
"Time range end is not a valid date. It must be YYYY/MM/DD":"O fim do intervalo de tempo não é uma data válida. Deve estar no formato AAAA/MM/DD",
"Date UTC":"Data UTC",
"System Labels":"",
"Edit Labels":"",
"Add Label":"",
"January":"Janeiro",
"February":"Fevereiro",
"March":"Março",
"April":"Abril",
"May":"Maio",
"June":"Junho",
"July":"Julho",
"August":"Agosto",
"September":"Setembro",
"October":"Outubro",
"November":"Novembro",
"December":"Dezembro",
"Submitting...":"A submeter...",
"Loading...":"A carregar...",
"Sign Out":"",
"Views":"Vistas",
"Reset":"Reiniciar",
"Wizard":"Assistente",
"Advanced":"Avançadas",
"Information":"Informação",
"Overcommitment":"",
"Reserved CPU":"",
"Reserved Memory":"",
"Storage backend":"",
"Filesystem - shared mode":"",
"Filesystem - ssh mode":"",
"Filesystem - qcow2 mode":"",
"Ceph":"Ceph",
"vCenter":"vCenter",
"LVM":"LVM",
"Raw Device Mapping":"",
"iSCSI - Libvirt initiator ":"",
"Drivers":"Drivers",
"Filesystem":"Sistema de ficheiros",
"Devices":"Dispositivos",
"iSCSI/Libvirt":"",
"Custom DS_MAD":"DS_MAD Personalizada",
"Transfer":"Transferência",
"Shared":"Partilhado",
"SSH":"SSH",
"qcow2":"qcow2",
"FS LVM":"SF LVM",
"Custom TM_MAD":"TM_MAD Personalizada",
"Datastore Type":"",
"Disk type":"Tipo de disco",
"Block":"Bloquear",
"RBD":"RBD",
"Gluster":"Gluster",
"Restricted directories for registering Images":"",
"Safe directories for registering Images":"",
"Storage usage limit (MB)":"",
"Transfer bandwidth limit (B/s)":"",
"":"Specify the maximum transfer rate in bytes/second when downloading images ",
"Do not try to untar or decompress":"Não tente descomprimir",
"Check available capacity of the Datastore before creating a new Image":"",
"Host bridge list":"",
"":"Space separated list of servers to add new Images to the Datastore storage",
"Volume Group Name":"Nome do Grupo do Volume",
"Gluster Host":"Anfitrião Gluster",
"Host and port of one (and only one) Gluster server (host:port)":"Anfitrião e porto de um (e apenas um) servidor Gluster (anfitrião:porto)",
"Gluster Volume":"Volume Gluster",
"Gluster volume to use for the datastore":"Volume Gluster a usar com a datastore",
"Ceph pool to store Images":"",
"Ceph host":"",
"Space-separated list of Ceph monitors":"",
"Ceph user":"",
"The username to interact with the Ceph cluster":"",
"Ceph secret":"",
"A generated UUID for a LibVirt secret":"",
"iSCSI host":"",
"Example: 'host' or 'host:port'":"",
"iSCSI user for CHAP authentication":"",
"iSCSI usage for CHAP authentication":"",
"'Usage' of the registered secret with the authentication string.":"",
"vCenter cluster":"",
"The vCenter Cluster that has access to this datastore.":"",
"Staging directory for Image registration":"",
"RBD format":"",
"Ceph configuration file path":"",
"Needed if using a non-default path for the ceph configuration file.":"",
"Ceph keyfile":"",
"File containing the secret key of user.":"",
"Advanced options":"Opções avançadas",
"Write the Datastore template here":"",
"Hostname":"Nome do anfitrião",
"Get Datastores":"",
"Base path":"Caminho base",
"Limit":"Limite",
"":"This action will power off this Virtual Machine and will be undeployed from ",
"":"You can send the power off signal to the Virtual Machine (this is equivalent",
"Power off and undeploy":"",
"Power off and undeploy the VM":"",
"Send the power off signal and undeploy the VM":"",
"Open a remote console in a new window":"Abrir a consola remota numa nova janela",
"You have to boot the Virtual Machine first":"Tem que iniciar a Máquina Virtual primeiro",
"The disks of the Virtual Machine will be saved in a new Image":"",
"You have to power-off the virtual machine first":"Tem que desligar primeiro a máquina virtual",
"Power off":"Desligar",
"Power on":"Ligar",
"Net RX":"RX Rede",
"Net TX":"TX Rede",
"Net Download Speed":"Velocidade de Transfência de Rede",
"Net Upload Speed":"Velocidade de Carregamento de Rede",
"Be careful, this action will shutdown and destroy your Virtual Machine":"",
"":"You can send the shutdown signal to the Virtual Machine (this is equivalent ",
"Terminate the machine":"",
"Send the shutdown signal and terminate":"",
"Virtual Machine Name":"Nome da Máquina Virtual",
"":"Creates a private persistent copy of the template plus any image defined in ",
"This action will reboot this Virtual Machine.":"Esta ação irá reiniciar esta Máquina Virtual.",
"":"You can send the reboot signal to the Virtual Machine (this is equivalent to",
"Reboot the machine":"Reiniciar a máquina",
"Send the reboot signal":"Enviar o sinal de reiniciar",
"This Virtual Machine will be saved in a new Template.":"",
"You can then create a new Virtual Machine using this Template.":"Pode criar depois uma nova Máquina Virtual usando este Modelo",
"Template Name":"Nome do Modelo",
"Template Description":"",
"":"The new Virtual Machine's disks can be made persistent. In a persistent ",
"Non-persistent":"",
"Save Virtual Machine to Template":"Guardar Máquina Virtual em Modelo",
"Refresh":"Atualizar",
"User ID":"ID Utilizador",
"":"This action will power off this Virtual Machine. The Virtual Machine will ",
"Power off the machine":"Desligar a máquina",
"Send the power off signal":"Enviar o sinal de encerramento",
"There is no information available":"Não existe informação disponível",
"Group Virtual Machines":"Grupo de Máquinas Virtuais",
"CPU hours":"Horas de CPU",
"Memory GB hours":"Horas de GB de Memória",
"Disk MB hours":"Horas MB Disco",
"RUNNING VMS":"VMS_A_CORRER",
"MEMORY":"MEMÓRIA",
"Recover a failed service, cleaning the failed VMs":"A recuperar um serviço falhado, a limpar as VMs que falharam",
"Service Name":"Nome de Serviço",
"Description":"Descrição",
"Keepalive service ID":"",
"Keepalive password":"",
"Virtual machine name":"",
"When creating multiple VMs, %i is replaces by the VM number in the set":"",
"Number of VM instances":"",
"Start on hold":"",
"Virtualization":"Virtualização",
"Custom VMM_MAD":"VMM_MAD Personalizada",
"Custom IM_MAD":"IM_MAD Personalizada",
"EC2":"EC2",
"Region name":"",
"Access key ID":"",
"Secret access key":"",
"Key":"",
"Value":"Valor",
"Get vCenter Clusters":"Obter Clusters vCenter",
"PCI Address":"Endereço PCI",
"VM name":"Nome da VM",
"Remote ID":"ID Remoto",
"Datastore ID":"ID Datastore",
"Custom attributes":"Atributos personalizáveis",
"Write the VDC template here":"Escreva o modelo VDC aqui",
"Selects all current and future clusters":"Seleciona os clusters atuais e futuros",
"Selects all current and future hosts":"Seleciona os anfitriões atuais e futuros",
"Selects all current and future vnets":"Seleciona todas as vnets atuais e futuras",
"Selects all current and future datastores":"Seleciona todas as datastores atuais e futuras",
"Name that the resource will get for description purposes.":"",
"VM Template Name":"",
"":"The following template will be created in OpenNebula and the previous images",
"Select the Datastore to store the resource":"",
"Select the Image to create the App":"",
"Select the Marketplace where the App will be created":"",
"Templates for the App":"",
"VM template":"modelo de VM",
"":"VM Template to be created. A DISK element pointing to the App Image will be ",
"App template":"",
"Write the MarketPlace Appliance template here":"",
"":"You can provide a template for the resource that will be created in ",
"":"You can provide a VM template associated to the resource that will be ",
"Register time":"Registar tempo",
"Format":"Formatar",
"Created after":"",
"Created before":"",
"Rules":"Regras",
"Traffic direction":"",
"ICMPv6":"",
"ICMPv6 Type":"",
"Port range":"Intervalo de portos",
"Target Network":"",
"Any network":"",
"Manual network":"",
"OpenNebula Virtual Network":"",
"First IP/IPv6 address":"",
"Add rule":"",
"Port Range":"Intervalo de Portos",
"Write the Security Group template here":"Introduza o modelo de Grupo de Segurança aqui",
"Clone Security Group":"Clonar Grupo de Segurança",
"":"Several security groups are selected, please choose a prefix to name the new",
"Prefix":"Prefixo",
"Close modal":"",
"":"VMs marked with <i class='fa fa-warning'></i> are waiting to be updated with",
"VMs in error. The update to the latest rules failed:":"",
"Operating System image":"",
"Readonly CD-ROM":"",
"Generic storage datablock":"",
"Kernel":"Kernel",
"Ramdisk":"Ramdisk",
"This image is persistent":"",
"Image location":"Localização da imagem",
"Path in OpenNebula server":"",
"Upload":"Enviar",
"Empty disk image":"",
"Size in MB":"Tamanho in MB",
"Disk provisioning type":"",
"Bus adapter controller":"",
"BUS":"BUS",
"Image mapping driver":"",
"Target device":"",
"Advanced Options":"Opções Avançadas",
"Write the Image template here":"Introduza o modelo de Imagem aqui",
"Get Images":"",
"Clone Image":"Clonar Imagem",
"":"Several images are selected, please choose a prefix to name the new copies",
"You can select a different target datastore":"Pode selecionar uma datastore destino diferente",
"Flatten":"Reduzido",
"Filesystem type":"Tipo de sistema de ficheiros",
"Running VMS":"VMs a correr",
"Write the Virtual Router template here":"",
"Attach new nic":"Anexar nova placa de rede",
"Attach":"Anexar",
"Floating IP":"",
"Floating IPv6 ULA":"",
"Floating IPv6 Global":"",
"Management Interface":"",
"Attach NIC":"",
"Login Token":"",
"":"A login token acts as a password and can be used to authenticate with ",
"Valid until":"",
"Target Group":"",
"Token":"",
"Expiration, in seconds":"",
"Get a new token":"",
"Update Quota":"Atualizar Quota",
"Apply changes":"Aplicar alterações",
"Update Password":"Atualizar Palavra-passe",
"Change":"Alterar",
"Select Secondary Groups":"",
"Change authentication":"Alterar autenticação",
"Authentication":"Autenticação",
"Authentication driver":"Driver de autenticação",
"View":"Vista",
"Login token":"",
"Manage login tokens":"",
"Public SSH Key":"Chave Pública de SSH",
"You can provide a SSH Key for this User clicking on the edit button":"Pode fornecer uma chave SSH para este Utilizador clicando no botão editar",
"Primary Group":"",
"Secondary Group":"",
"Table Order":"Ordem da tabela",
"Language":"Língua",
"Username":"Nome de utilizador",
"Confirm Password":"Confirme a palavra-chave",
"core":"",
"public":"",
"custom":"",
"Main Group":"",
"Secondary Groups":"",
"Number of VMs":"",
"Force":"Forçar",
"Force the new cardinality even if it is outside the limits":"Força a nova cardinalidade mesmo que esteja fora dos limites",
"Period":"Período",
"Seconds between each group of actions":"Segundos entre grupos de ações",
"Number":"Número",
"Number of VMs to apply the action to each period":"Número de VMs a aplicar a ação em cada período",
"Parents":"Pais",
"Select a role in the table for more information":"Selecione um papel na tabela para mais informação",
"Shutdown action":"Ação de encerramento",
"Cooldown":"Arrefecimento",
"Min VMs":"Mín VMs",
"Max VMs":"Máximo VMs",
"Start time":"Hora de início",
"Recurrence":"Recorrência",
"Strategy":"Estratégia",
"Ready Status Gate":"Porta de Estado Pronto",
"Write the Virtual Machine template here":"Escreva o modelo de Máquina Virtual aqui",
"Disk Resize":"",
"Disk ID":"ID Disco",
"New size":"",
"MONTH":"",
"Resize":"Redimensionar",
"Snapshot":"Snapshot",
"Snapshot name":"Nome do snapshot",
"Deploy Virtual Machine":"Instanciar Máquina Virtual",
"Select a Host":"Selecione um Anfitrião",
"Enforce":"Forçar",
"":"If it is set to true, the host capacity will be checked. This will only ",
"Select a datastore":"Selecionar a datastore",
"Loading":"A carregar",
"Send CtrlAltDel":"",
"Open in a new window":"Abrir numa nova janela",
"Canvas not supported.":"Resolução não suportada.",
"You have to confirm this action.":"É necessário confirmar esta ação.",
"Do you want to proceed?":"Deseja continuar?",
"OK":"OK",
"Disk Snapshot":"Snapshot de disco",
"Disk Saveas":"Disco Guardar Como",
"Snapshot ID":"ID de Snapshot",
"New Image name":"Novo nome de Imagem",
"Save as":"Guardar como",
"Migrate Virtual Machine":"Migrar Máquina Virtual",
"Attach new disk":"Anexar novo disco",
"Resize VM capacity":"Redimensionar capacidade de VM",
"Save as Template":"Guardar como Modelo",
"Template name":"Nome do Modelo",
"Make the new images persistent":"",
"Save As Template":"Guardar Como Modelo",
"Image / Size-Format":"",
"Attach disk":"Anexar disco",
"Cost / MByte":"Custo /MByte",
"Update Configuration":"",
"VCPU":"VCPU",
"Cost / CPU":"Custo / CPU",
"Real memory":"",
"User template":"Modelo de utilizadores",
"LCM State":"Estado LCM",
"Deploy ID":"ID de lançamento",
"Monitoring":"A monitorizar",
"VM type":"",
"Regular VM":"",
"Configuration attributes":"",
"Write the MarketPlace template here":"",
"Create Zone":"Criar Zona",
"Zone Name":"Nome da Zona",
"Network configuration":"",
"":"Straight strategy will instantiate each role in order: parents role will be ",
"Straight":"Ordenada",
"VM shutdown action":"",
"Terminate hard":"",
"":"Wait for VMs to report that they are READY via OneGate to consider them ",
"Advanced service parameters":"",
"Write the Service template here":"Escreva o modelo do Serviço aqui",
"Service name":"",
"":"When creating several Services, the wildcard %i will be replaced with a ",
"Number of instances":"Número de instâncias",
"Clone Service Template":"",
"":"Several templates are selected, please choose prefix to name the new copies",
"Network Configuration":"Configuração de Rede",
"Percentage":"Percentagem",
"Elasticity policies":"Políticas de elasticidade",
"Type of adjustment.":"Tipo de ajustamento",
"CHANGE: Add/subtract the given number of VMs.":"",
"CARDINALITY: Set the cardinality to the given number.":"CARDINALIDADE: Alterar a cardinalidade para o número indicado.",
"":"PERCENTAGE_CHANGE: Add/subtract the given percentage to the current ",
"Positive or negative adjustment. Its meaning depends on 'type'":"Ajustamento positivo ou negativo. O seu significado depende do 'tipo'",
"CHANGE: -2, will subtract 2 VMs from the role":"",
"CARDINALITY: 8, will set cardinality to 8":"",
"PERCENTAGE_CHANGE: 20, will increment cardinality by 20%":"ALTERACAO_PERCENTAGEM: 20, irá aumentar a cardinalidade em 20%",
"Adjust":"Ajustar",
"Optional parameter for PERCENTAGE_CHANGE adjustment type.":"Parâmetro opcional para ajustamento do tipo ALTERAR_PERCENTAGEM.",
"":" If present, the policy will change the cardinality by at least the number ",
"Min":"Min",
"Expression to trigger the elasticity":"Expressão para despoletar a elasticidade",
"Example: ATT < 20":"Exemplo: ATT < 20",
"Expression":"Expressão",
"":"Number of periods that the expression must be true before the elasticity is ",
"Duration, in seconds, of each period in '# Periods'":"Duração, em segundos, de cada período em '# Periods'",
"Cooldown period duration after a scale operation, in seconds":"Duração do período de arrefecimento depois de uma operação de escalonamento, em segundos",
"Scheduled policies":"Políticas calendarizadas",
"":"Optional parameter for PERCENTAGE_CHANGE adjustment type. If present, the ",
"":"Recurrence: Time for recurring adjustments. Time is specified with the Unix ",
"Start time: Exact time for the adjustment":"",
"Time format":"Formato do tempo",
"Time expression depends on the the time format selected":"",
"Time expression":"Expressão de tempo",
"Role name":"",
"VM template to create this role's VMs":"",
"Network Interfaces":"Interfaces de Rede",
"Parent roles":"Papéis pais",
"Cooldown time after an elasticity operation (seconds)":"",
"Role elasticity":"",
"If it is not set, the one set for the Service will be used":"",
"VM template content":"",
"":"This information will be merged with the original Virtual Machine template. ",
"Advanced role parameters":"",
"New Groups are automatically added to the default VDC":"Novos Grupos são automaticamente adicionados ao VDC por omissão",
"Admin":"Admin",
"Permissions":"Permissões",
"Allow users in this group to use the following Sunstone views":"Permite que os utilizadores deste grupo usem as seguintes vistas do Sunstone",
"Not required. Defaults to the one set in sunstone-views.yaml":"",
"Default Users View":"Vista dos Utilizadores por omissão",
"Default Admin View":"Vista dos administradores por omissão",
"Group Users":"Grupo de Utilizadores",
"Group Admins":"Grupo de Administradores",
"Create an administrator user":"Criar um utilizador administrador",
"":"You can create now an administrator user. More administrators can be added ",
"Image & Datastore":"",
"Make new images persistent by default":"",
"":"Control the default value for the PERSISTENT attribute on image creation ",
"Make save-as and clone images persistent by default":"",
"":"Control the default value for the PERSISTENT attribute on image creation ",
"":"Allow users to view the VMs and Services of other users in the same group",
"":"An ACL Rule will be created to give users in this group access to all the ",
"Allow users in this group to create the following resources":"Permite que os utilizadores deste grupo criem os seguintes recursos",
"":"This will create new ACL Rules to define which virtual resources this ",
"":"Documents are a special tool used for general purposes, mainly by OneFlow. ",
"Edit administrators":"Editar administradores",
"Users marked with <i class='fa fa-star'></i> are administrators":"",
"Group Admins Views":"Vistas do Grupo de Administradores",
"Group Users Views":"Vistas do Grupo de Utilizadores",
"QoS":"",
"Name of the physical bridge in the nodes to attach VM NICs":"",
"Network mode":"Modo de rede",
"Bridged":"",
"Bridged & Security Groups":"",
"Bridged & ebtables VLAN":"",
"802.1Q":"802.1Q",
"VXLAN":"VXLAN",
"Open vSwitch":"Abrir vSwitch",
"Network Driver (VN_MAD)":"",
"":"Bridged, virtual machine traffic is directly bridged through an existing ",
"Bridged & Security Groups, bridged network with Security Group rules.":"",
"":"Bridged & ebtables VLAN, restrict network access through ebtables rules. ",
"":"802.1Q, restrict network access through VLAN tagging. Security Group rules ",
"":"VXLAN, creates a L2 network overlay, each VLAN has associated a multicast ",
"":"Open vSwitch, restrict network access with Open vSwitch Virtual Switch. ",
"":"vSphere standard switches or distributed switches with port groups. Security",
"Custom, use a custom virtual network driver.":"",
"MAC spoofing filter":"",
"IP spoofing filter":"",
"Automatic VLAN ID":"",
"No VLAN network":"",
"Manual VLAN ID":"",
"Physical device":"Dispositivo físico",
"Node NIC to send/receive virtual network traffic":"",
"":"Physical NIC names for uplinks. Use comma to separate values (e.g ",
"MTU of the interface":"",
"Switch name":"",
"Number of ports":"",
"Port group type":"",
"Port group":"",
"Distributed Port Group":"",
"OpenNebula's Host ID":"",
"":"Address Ranges need to be managed in the individual Virtual Network panel",
"":"The default Security Group 0 is automatically added to new Virtual Networks",
"Inbound traffic":"",
"Average bandwidth (KBytes/s)":"",
"Peak bandwidth (KBytes/s)":"",
"Peak burst (KBytes)":"",
"Outbound traffic":"",
"":"These values apply to each VM interface individually, they are not global ",
"Network address":"Endereço de rede",
"Network mask":"Máscara de rede",
"Gateway":"Gateway",
"IPv6 Gateway":"Gateway IPv6",
"DNS":"DNS",
"MTU of the Guest interfaces":"",
"Write the Virtual Network template here":"Introduza o modelo de rede virtual aqui",
"Get Networks":"Obter Redes",
"Edit Address Range":"Editar Intervalos de Endereços",
"New Address Range":"Novo Intervalo de Endereços",
"Reservation from Virtual Network":"Reserva da Rede Virtual",
"Number of addresses":"Número de endereços",
"Add to a new Virtual Network":"Adicionar a nova Rede Virtual",
"Add to an existing Reservation":"Adicionar a uma Reserva existente",
"Virtual Network Name":"Nome da Rede Virtual",
"You can select the addresses from an specific Address Range":"Pode selecionar os endereços de um intervalo de endereços específico",
"First address":"Primeiro endereço",
"IP or MAC":"",
"Remove":"Remover",
"IPv6 Prefix":"Prefixo IPv6",
"Select an Address Range to see more information":"Selecionar um Intervalo de Endereços para visualizar mais informação",
"First":"Primeiro",
"Last":"Último",
"IP6_GLOBAL":"IP6_GLOBAL",
"IP6":"",
"IP6_ULA":"IP6_ULA",
"Hold IP":"Suster IP",
"IPv6":"IPv6",
"IPv6 Link":"Ligação IPv6",
"Inbound QoS":"",
"Average bandwidth":"",
"KBytes/s":"",
"Peak bandwidth":"",
"Peak burst":"",
"KBytes":"",
"Outbound QoS":"",
"IPv4":"IPv4",
"IPv4/6":"IPv4/6",
"Ethernet":"Ethernet",
"First IPv4 address":"",
"First MAC address":"Endereço MAC inicial",
"SLAAC":"",
"IPv6 Global prefix":"Prefixo Global IPv6",
"IPv6 ULA prefix":"",
"IPAM":"",
"Change Language":"Alterar Língua",
"Update Language":"Atualizar Língua",
"Change Password":"Alterar palavra-passe",
"New Password":"Nova palavra-passe",
"Change view":"Alterar vista",
"Update view":"Atualizar vista",
"Add SSH Key":"Adicionar chave SSH",
"Update SSH Key":"Atualizar chave SSH",
"Add a public SSH key to your account!":"Adicione uma chave pública de SSH à sua conta!",
"You will be able to access your Virtual Machines without password":"Será capaz de aceder às suas Máquinas Virtuais sem palavra-passe",
"Update your public SSH key!":"Atualize a sua chave pública de SSH!",
"This rule applies to":"Esta regra aplica-se a",
"Zones where the rule applies":"Zonas às quais se aplica a regra",
"MarketPlace Apps":"",
"Resource subset":"Subconjunto do recurso",
"Resource ID":"ID do recurso",
"Use":"Utilização",
"Manage":"Gerir",
"Administrate":"Administrar",
"ACL String preview":"Pré-visualização do texto ACL",
"Write the Virtual Machine Group template here":"",
"Host Affined":"",
"Host Anti Affined":"",
"Affinity":"",
"Roles Affinity":"",
"VM-VM Affinity":"",
"Affined":"",
"Anti Affined":"",
"Host-VM Affinity":"",
"Role Affinity":"",
"Remote VM Template ID":"",
"AMI":"AMI",
"":"Unique ID of a machine image, returned by a call to ec2-describe-images.",
"Instance type":"Tipo de instância",
"AKI":"AKI",
"The ID of the kernel with which to launch the instance.":"O ID do kernel com o qual iniciar a instância.",
"Availability zone":"",
"Block device mapping":"",
"":"The block device mapping for the instance. More than one can be specified in",
"Client token":"",
"":"Unique, case-sensitive identifier you provide to ensure idempotency of the ",
"EBS optimized":"",
"Obtain a better I/O throughput for VMs with EBS provisioned volumes":"Obter uma melhor taxa de transferência para VMs com volumes baseados em EBS",
"Elastic IP address":"",
"":"This parameter is passed to the command ec2-associate-address -i i-0041230 ",
"OpenNebula Host":"Anfitrião OpenNebula",
"Defines which OpenNebula host will use this template":"Define qual anfitrião OpenNebula irá usar este modelo",
"Keypair name":"",
"":"The name of the key pair, later will be used to execute commands like ssh -i",
"License pool name":"",
"Placement group name":"",
"Private IP":"IP Privado",
"":"If you're using Amazon Virtual Private Cloud, you can optionally use this ",
"The ID of the RAM disk to select.":"O ID do disco RAM a selecionar.",
"Security group names":"",
"You can specify more than one security group (comma separated).":"",
"Security group IDs":"",
"Subnet ID":"ID da Subrede",
"":"If you're using Amazon Virtual Private Cloud, this specifies the ID of the ",
"Tags":"Etiquetas",
"":"Key and optional value of the tag, separated by an equals sign ( = ).You can",
"Tenancy":"Locação",
"User data":"",
"":"Specifies Base64-encoded MIME user data to be made available to the ",
"Specifies the base OS of the VM.":"Especifica o SO base da VM.",
"Specifies the capacity of the VM in terms of CPU and memory":"Especifica a capacidade da VM em termos de memória e CPU",
"":"Azure datacenter where the VM will be sent. See /etc/one/az_driver.conf for ",
"VM user name":"",
"":"If the selected IMAGE is prepared for Azure provisioning, a username can be ",
"VM user password":"",
"Password for VM User":"",
"Affinity group":"",
"":"Affinity groups allow you to group your Azure services to optimize ",
"Availability set":"",
"Cloud service":"",
"":"Specifies the name of the cloud service where this VM will be linked. ",
"SSH port":"",
"Port where the VMs ssh server will listen on":"Porto onde o servidor ssh irá escutar as VMs",
"Storage account":"",
"Subnet name":"",
"Name of the particular Subnet where this VM will be connected to":"Nome da subrede específica onde a VM irá estar ligada",
"TCP endpoints":"",
"":"Comma-separated list of TCP ports to be accessible from the public internet ",
"Virtual Network name":"",
"Win RM":"Win RM",
"Comma-separated list of possible protocols to access this Windows VM":"Lista separada por vírgulas de possíveis protocolos para aceder a esta VM Windows",
"Volatile disk":"Disco volátil",
"Image name":"Nome Imagem",
"Image owner's user ID":"",
"Image owner's user name":"",
"Size in GB":"",
"FS":"SF",
"Swap":"Substituir",
"Filesystem format":"",
"":"Device to map image disk. If set, it will overwrite the default device ",
"Read-only":"",
"Cache":"Cache",
"IO policy":"",
"Discard":"Descartar",
"ignore":"ignorar",
"unmap":"desmapear",
"Size on instantiate (MB)":"",
"":"The size of the disk will be modified to match this size when the template ",
"IO throttling (bytes/s)":"",
"Total (read+write) bytes/s":"",
"Read bytes/s":"",
"Write bytes/s":"",
"IO throttling (IOPS)":"",
"Total (read+write) IOPS":"",
"Read IOPS":"",
"Write IOPS Sec":"Escrita IOPS Seg",
"RAW data":"Dados RAW",
"kvm":"kvm",
"Data":"Dados",
"Raw data to be passed directly to the hypervisor":"Dados raw a serem passados diretamente ao hipervisor",
"PCI Devices":"Dispositivos PCI",
"":"PCI passthrough of network devices is configured per NIC, in the \"Network\"",
"Device name":"",
"Vendor":"Fabricante",
"Device":"Dispositivo",
"Class":"Classe",
"Custom Tags":"Etiquetas personalizadas",
"Graphics":"Gráficos",
"Listen on IP":"",
"Server port":"",
"Port for the VNC/SPICE server":"Porto para o servidor VNC/SPICE",
"Keymap":"Mapeamento do teclado",
"Generate random password":"",
"Inputs":"entradas",
"Mouse":"Rato",
"Tablet":"Tablet",
"Bus":"Bus",
"USB":"USB",
"PS2":"PS2",
"Boot":"Arranque",
"Features":"Funcionalidades",
"CPU Architecture":"",
"libvirt machine type":"",
"Root device":"",
"Boot order":"",
"Select the devices to boot from, and their order":"",
"Kernel boot parameters":"",
"Path to the bootloader executable":"Caminho para o executável bootloader",
"Registered Image":"Imagem Registada",
"Remote path":"",
"KERNEL_DS":"DS_KERNEL",
"Path to the OS kernel to boot the image":"Caminho para o kernel do SO para arrancar a imagem",
"Registered Image ":"Imagem Registada",
"INITRD_DS":"DS_INITRD",
"Path to the initrd image":"Caminho para a imagem initrd",
"ACPI":"ACPI",
"":"Add support in the VM for Advanced Configuration and Power Interface (ACPI)",
"PAE":"PAE",
"Add support in the VM for Physical Address Extension (PAE)":"Adicionar suporte na VM para Extensão Física de Endereço (PAE)",
"APIC":"APIC",
"Enables the advanced programmable IRQ management.":"Ativa a gestão de programação avançada de IRQ.",
"HYPERV":"HYPERV",
"Add support in the VM for hyper-v features (HYPERV)":"Adiciona suporte na VM para funcionalidades hyper-v (HYPERV)",
"Localtime":"Hora local",
"":"The guest clock will be synchronized to the hosts configured timezone when ",
"QEMU Guest Agent":"",
"":"Enables the QEMU Guest Agent communication. This does not start the Guest ",
"virtio-scsi Queues":"",
"":"Number of vCPU queues to use in the virtio-scsi controller. Leave blank to ",
"Amount of RAM required for the VM, in Megabytes.":"Quantidade de RAM necessária para a VM, em Megabytes.",
"Memory modification":"",
"Allow users to modify this template's default memory on instantiate":"",
"fixed":"",
"any value":"",
"range":"",
"list":"",
"Max":"",
"":"Percentage of CPU divided by 100 required for the Virtual Machine. Half a ",
"CPU modification":"",
"Allow users to modify this template's default CPU on instantiate":"",
"":"Number of virtual cpus. This value is optional, the default hypervisor ",
"VCPU modification":"",
"Allow users to modify this template's default VCPU on instantiate":"",
"Hypervisor":"Hipervisor",
"KVM":"KVM",
"Logo":"Logo",
"vCenter Template Ref":"",
"vCenter Cluster Ref":"",
"vCenter Instance ID":"",
"Default Resource Pool":"",
"Fixed":"",
"Provide on instantiation":"",
"Available Resource Pools":"",
"vCenter VM Folder":"",
"":"If specified, the the VMs and Template folder path where the VM will be ",
"Cost of each MB or GB per hour":"",
"month":"",
"Cost of each CPU per hour":"Custo de cada CPU por hora",
"Cost of each GB per hour":"",
"Do not allow to modify network configuration":"Não permitir alterar a configuração de rede",
"Users will not be able to remove or add new NICs":"",
"Make this template available for Virtual Router machines only":"",
"":"Virtual Routers create Virtual Machines from a source Template. This ",
"Contextualization type":"",
"OpenNebula":"OpenNebula",
"vCenter customizations":"",
"Configuration":"Configuração",
"Custom vars":"Variáveis personalizadas",
" Add SSH contextualization":"Adicionar contextualização SSH",
"":"Add an ssh public key to the context. If the Public Key textarea is empty ",
"SSH public key":"",
" Add Network contextualization":"Adicionar contextualização de rede",
"":"Add network contextualization parameters. For each NIC defined in the ",
" Add OneGate token":"Adicionar token OneGate",
"":"Add a file (token.txt) to the context containing the token to push custom ",
" Report Ready to OneGate":"",
"Sends READY=YES to OneGate, useful for OneFlow":"",
"Start script":"",
"":"Text of the script executed when the machine starts up. It can contain ",
"Encode script in Base64":"",
"User Inputs":"Entradas de Utilizador",
"":"These attributes must be provided by the user when a new VM is instantiated.",
"FILES_DS":"DS_FICHEIROS",
"Init scripts":"Scripts iniciais",
"":"The contextualization package executes an init.sh file if it exists. If more",
"Policy":"Política",
"Host Requirements":"Requisitos do anfitrião",
"Select Hosts ":"Selecionar Anfitriões",
"Select Clusters ":"Selecionar Clusters",
"":"Boolean expression that rules out provisioning hosts from list of machines ",
"Datastore Requirements":"Requisitos da Datastore",
"":"Boolean expression that rules out entries from the pool of datastores ",
"Host Rank":"Ranking de Anfitriões",
"Packing":"Agrupamento",
"Pack the VMs in the Hosts to reduce VM fragmentation":"",
"Stripping":"Corte",
"Spread the VMs in the Hosts":"",
"Load-aware":"Controlo de carga",
"Maximize the resources available to VMs in a Host":"",
"":"This field sets which attribute will be used to sort the suitable hosts for ",
"Datastore Rank":"Ranking de Datastores",
"":"Tries to optimize storage usage by selecting the DS with less free space",
"":"Striping. Tries to optimize I/O by distributing the VMs across datastores.",
"":"This field sets which attribute will be used to sort the suitable datastores",
"VM Templates for Virtual Routers cannot define NICs":"",
"Default hardware model to emulate for all NICs":"",
"Choose Network":"Escolher Rede",
"Virtual Network ID":"",
"Virtual Network owner's user ID":"",
"Virtual Network owner's user Name":"",
"OPEN NEBULA MANAGEMENT":"",
"Override Network Values IPv4":"Sobrepor Valores de Rede IPv4",
"Search domain for DNS resolution":"",
"Override Network Values IPv6":"Sobrepor valores de rede IPv6",
"Force IPv4 context":"",
"Override force IPv4 for this IPv6 network. Values: Yes or No.":"Sobrepor e forçar IPv4 para esta rede IPv6. Valores: Sim ou Não.",
"Override Network Inbound Traffic QoS":"",
"Override Network Outbound Traffic QoS":"",
"Hardware":"",
"PCI passthrough":"",
"Hardware model to emulate":"",
"Get VM Templates":"Obter Modelos de VM",
"Instantiate as persistent":"",
"":"Defaults to 'template name-<vmid>' when empty. When creating several VMs, ",
"":"Sets the new VM to hold state, instead of pending. The scheduler will not ",
"Clone Template":"Clonar Modelo",
"":"You can also clone any Image referenced inside this Template. They will be ",
"Clone with Images":"",
"Host Overcommitment":"",
"":"Prior to assigning a VM to a Host, the available capacity is checked to ",
"":"Cluster-wise. All the hosts of the cluster will reserve the same amount of ",
"Host-wise. This value will override those defined at cluster level.":"",
"":"These values can be negative, in that case you'll be actually increasing the",
"Reserved Memory in KB":"",
"":"The values will overwrite the monitoring values in the next monitorization ",
"Confirm":"Confirmar",
"You need to select something.":"É necessário seleccionar alguma opção.",
"End time":"Tempo final",
"Group by":"Agrupar por",
"Filter":"Filtrar",
"Get accounting":"",
"There are no accounting records":"Não existem registos de contabilidade",
"Date":"Data",
"Accounting Tables":"Tabelas de Contabilidade",
"Clear selection":"",
"Toggle advanced sections":"",
"EC2 Access":"",
"EC2 Secret":"",
"Ownership":"Dono",
"text":"texto",
"text (base64)":"",
"password":"palavra-chave",
"number":"",
"number (float)":"",
"range (float)":"",
"boolean":"",
"Default value":"",
"Options":"",
"Comma-separated list of options for the drop-down select input":"",
"Mandatory":"",
"vCenter Deployment":"",
"":"If specified, the VMs and Template folder path where the VM will be created ",
"Search":"Procurar",
"Label filter:":"",
"Clear search":"",
"There is no data available":"Não existem dados disponíveis",
"PCI interface":"",
"Interface":"Interface",
"Select a Network":"Selecione uma Rede",
"Force IPv4:":"",
"Optionally, you can force the IP assigned to the network interface.":"",
"":"If checked, each Virtual Machine will have a floating IP added to its ",
"":"If checked, this network interface will be a Virtual Router management ",
"Force IPv6:":"",
"":"You can add Security Groups to this network interface. These IDs do not ",
"Network Interface":"",
"Disks":"Discos",
"Clear":"",
"Filter by user":"Filtrar por utilizador",
"Filter by group":"Filtrar por grupo",
"Get showback":"",
"There are no showback records":"Não há registo de estatística de utilização",
"Year":"Ano",
"Month":"Mês",
"Select a row to get detailed information of the month":"Selecione uma linha para obter uma informação detalhada do mês",
"Hours":"Horas"
}
|
function abracaFunction(yourFunc) {
console.log(
"I am abracaFunction! Watch as I mutate an array of strings to your heart's content!"
);
const abracaArray = [
"James",
"Elamin",
"Ismael",
"Sanyia",
"Chris",
"Antigoni",
];
const abracaOutput = yourFunc(abracaArray);
return abracaOutput;
};
function upper(str) {
return str.toUpperCase();
};
function abracamayus(arr) {
return arr.map(upper)
};
console.log(abracaFunction(abracamayus));
|
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux'
import { currentUser, signOut } from '../actions/authActions'
import AppBar from '@material-ui/core/AppBar'
import Toolbar from '@material-ui/core/Toolbar'
import Typography from '@material-ui/core/Typography'
import IconButton from '@material-ui/core/IconButton'
import MenuIcon from '@material-ui/icons/Menu'
import AccountCircle from '@material-ui/icons/AccountCircle'
import Switch from '@material-ui/core/Switch'
import MenuItem from '@material-ui/core/MenuItem'
import Menu from '@material-ui/core/Menu'
import Drawer from '@material-ui/core/Drawer'
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Divider from '@material-ui/core/Divider';
import InboxIcon from '@material-ui/icons/Inbox';
import DraftsIcon from '@material-ui/icons/Drafts';
const styles = {
root: {
flexGrow: 1,
},
flex: {
flex: 1,
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
list: {
width: 250,
}
};
class Header extends Component {
constructor(props) {
super(props)
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false,
showHeader: true,
auth: true,
anchorEl: null,
open: false,
drawerOpen: false
}
this.notRequiredOn = ['/sign_in', '/sign_up']
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
})
}
componentWillMount () {
this.mountHeader(this.props)
this.props.currentUser()
}
componentWillReceiveProps (nextProps) {
this.mountHeader(nextProps)
}
mountHeader = (props) => {
if (this.notRequiredOn.includes(props.location.pathname)) {
this.setState({showHeader: false})
} else {
this.setState({showHeader: true})
}
}
handleChange = (event, checked) => {
this.setState({ auth: checked });
};
handleMenu = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ anchorEl: null, open: false });
};
render () {
const { signedIn } = this.props
const { auth, anchorEl, open } = this.state
const sideList = (
<div style={styles.list}>
<List component="nav">
<ListItem button>
<ListItemIcon>
<InboxIcon />
</ListItemIcon>
<ListItemText primary="Inbox" />
</ListItem>
<ListItem button>
<ListItemIcon>
<DraftsIcon />
</ListItemIcon>
<ListItemText primary="Drafts" />
</ListItem>
</List>
<Divider />
<List component="nav">
<ListItem button>
<ListItemText primary="Trash" />
</ListItem>
<ListItem button component="a" href="#simple-list">
<ListItemText primary="Spam" />
</ListItem>
</List>
</div>
);
return (
// <div>
// {this.state.showHeader && <nav style="navbar navbar-light bg-light justify-content-between">
// <Link to='/' style='navbar-brand'>Home</Link>
// {!signedIn && <Link to='/sign_in'>
// <button style="btn btn-outline-success my-2 my-sm-0" type="submit">Sign In</button>
// </Link>}
// {signedIn && <button style="btn btn-outline-danger my-2 my-sm-0" onClick={() => this.props.signOut()}>Sign Out</button>}
// </nav>}
// </div>
<div style={styles.root}>
<Drawer style={{zIndex: '-1'}} open={this.state.drawerOpen} onClose={() => this.setState({drawerOpen: false})}>
<Toolbar />
<div
tabIndex={0}
role="button"
onClick={() => this.setState({drawerOpen: false})}
onKeyDown={() => this.setState({drawerOpen: false})}
>
{sideList}
</div>
</Drawer>
<AppBar position="static">
<Toolbar>
<IconButton style={styles.menuButton} color="inherit" aria-label="Menu" onClick={() => this.setState({drawerOpen: !this.state.drawerOpen})}>
<MenuIcon />
</IconButton>
<Typography variant="title" color="inherit" style={styles.flex}>
Title
</Typography>
{auth && (
<div>
<IconButton
aria-owns={open ? 'menu-appbar' : null}
aria-haspopup="true"
onClick={() => this.setState({open: !open})}
color="inherit"
>
<AccountCircle />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={open}
onClose={this.handleClose}
>
<MenuItem onClick={this.handleClose}>Profile</MenuItem>
<MenuItem onClick={this.handleClose}>My account</MenuItem>
</Menu>
</div>
)}
</Toolbar>
</AppBar>
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
currentUser: () => dispatch(currentUser()),
signOut: () => dispatch(signOut())
}
}
export default connect(
state => ({
auth: state.auth,
signedIn: localStorage.getItem('token') ? true : false
}), mapDispatchToProps
) (Header)
|
var gamejs = require('gamejs')
var Thing = require('./Thing')
var Images = require('./Images')
var state = require('./state')
BankBox = function() {
Thing.TextBox.apply(this, ["To spend: ???XP", [120,40]])
this.font = new gamejs.font.Font("24px sans-serif")
this.centered = true
}
gamejs.utils.objects.extend(BankBox, Thing.TextBox)
BankBox.prototype.think = function (dt) {
this.update("To spend: " + state.xp + "XP")
TextBox.prototype.think.call(this, dt)
}
Greeting = function() {
Thing.TextBox.apply(this, ["Please select an adventurer to upgrade", [427,240]])
this.font = new gamejs.font.Font("24px sans-serif")
this.update("Please select an adventurer to upgrade")
this.centered = true
}
gamejs.utils.objects.extend(Greeting, Thing.TextBox)
UpgradeMenu = function(player, pstates, index) {
Thing.Thing.apply(this)
this.player = player
this.index = index
this.pstates = pstates
this.pstate = pstates[index]
this.font = new gamejs.font.Font("24px sans-serif")
this.centered = true
this.image = null
}
gamejs.utils.objects.extend(UpgradeMenu, Thing.Thing)
UpgradeMenu.prototype.build = function () {
this.image = new gamejs.Surface([300, 240])
this.image.fill("#000044")
while (this.children.length) this.children[0].die()
this.setpos([427, 200])
var namebox = new Thing.TextBox("Adventurer: " + this.pstate.name)
namebox.attachto(this).setpos([-130, -110])
var s = new Thing.TextBox("Skill: " + this.pstate.skill)
s.attachto(this).setpos([-120, -80]);
(new Thing.TextBox("" + this.pstate.xpspent, [0, 0], "12px sans-serif", "blue")).attachto(this).setpos([120, 80]);
(new Thing.TextBox(this.pstate.hp0 + "HP")).attachto(this).setpos([-30, -44]);
(new Thing.TextBox(this.pstate.mp0 + "MP")).attachto(this).setpos([-30, -12]);
(new Thing.TextBox(this.pstate.strength + " strength")).attachto(this).setpos([-30, 20]);
(new Thing.TextBox(Math.floor(this.pstate.speed/10) + " speed")).attachto(this).setpos([-30, 52]);
(new Thing.TextBox(Math.floor(this.pstate.range/20) + " range")).attachto(this).setpos([-30, 84]);
var i = this.index;
(new Thing.Button("-" + state.upgradeamt(0, i) + "XP", null, function () { state.upgrade(0, i) })).attachto(this).setpos([-80,-32]);
(new Thing.Button("-" + state.upgradeamt(1, i) + "XP", null, function () { state.upgrade(1, i) })).attachto(this).setpos([-80,0]);
(new Thing.Button("-" + state.upgradeamt(2, i) + "XP", null, function () { state.upgrade(2, i) })).attachto(this).setpos([-80,32]);
(new Thing.Button("-" + state.upgradeamt(3, i) + "XP", null, function () { state.upgrade(3, i) })).attachto(this).setpos([-80,64]);
(new Thing.Button("-" + state.upgradeamt(4, i) + "XP", null, function () { state.upgrade(4, i) })).attachto(this).setpos([-80,96]);
/* hp0: 200,
mp0: 200,
speed: 100,
range: 100,
xpspent: 0,
deserted: 0,*/
}
UpgradeMenu.prototype.think = function (dt) {
if (!this.image) this.build()
Thing.Thing.prototype.think(dt)
}
exports.BankBox = BankBox
exports.Greeting = Greeting
exports.UpgradeMenu = UpgradeMenu
|
// Let's start Algorithms Javascript
function addNumbers(num1, num2) {
return num1 + num2;
}
console.log(addNumbers(2, 3));
console.log(addNumbers(3, 3));
console.log(addNumbers(4, 5));
|
const _compareDate = (string) => {
try {
let date = new Date(string);
return date.getTime() > Date.now();
} catch(e) {
return false;
}
};
export default _compareDate;
|
const gulp = require('gulp')
, http = require('http')
, sass = require('gulp-sass')
, pug = require('gulp-pug')
, minify = require('gulp-cssnano')
, liveReload = require('gulp-livereload')
, st = require('st')
, path = require('path')
, plumber = require('gulp-plumber')
gulp.task('sass', () => {
gulp.src('./dev/scss/*.scss')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.toString());
this.emit('end');
}
})
)
.pipe(sass())
.pipe(minify())
.pipe(gulp.dest('./dist/main/css'))
.pipe(liveReload())
});
gulp.task('pug', () => {
gulp.src('./dev/*.pug')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.toString());
this.emit('end');
}
})
)
.pipe(pug({pretty: true}))
.pipe(gulp.dest( path.join(__dirname, '/')));
})
gulp.task('watch-sass', () => {
liveReload.listen();
gulp.watch([
'./dev/scss/**/*.scss',
'./dev/scss/*.scss'
],
['sass']);
})
gulp.task('watch-pug', () => {
liveReload.listen();
gulp.watch([
'./dev/**/*.pug'],
['pug']);
})
gulp.task('server', function(done) {
http.createServer(
st({ path: __dirname + '/', index: 'index.html', cache: false })
).listen(8080, done);
gulp.run(['watch-sass', 'watch-pug'])
});
|
const db = require('../db');
const constant = require('../constant/constant')
const util = require('../js/util');
const validator = require('validator');
class Api4 {
/**
* コンストラクタ
*/
constructor (data) {
this.data = data;
}
/**
* メソッド
*/
async method () {
let t = this;
try {
//トランザクション開始 (トランザクションを使うときに記述する)
await db.connection.beginTransaction();
// 部屋に入っているか
const c1 = await db.doSql (
constant.SQL_ID_0005S,
t.data,
0
).catch(err => {
throw new Error('go this error');
});
//部屋に入っていたら
if (c1 != constant.EMPTY) {
throw new Error('go this error');
}
//部屋があるか
const c111 = await db.doSql (
constant.SQL_ID_0008S,
t.data,
0
).catch(err => {
throw new Error('go this error');
});
//部屋がなかったら
if (c111 == constant.EMPTY) {
throw new Error('go this error');
}
//入室できるか
const c2 = await db.doSql (
constant.SQL_ID_0002S,
t.data,
0
).catch(err => {
throw new Error('go this error');
});
//出入り禁止なら
if (c2 != constant.EMPTY) {
throw new Error('go this error');
}
//入室
const c3 = await db.doSql (
constant.SQL_ID_1002I,
t.data,
1
).catch(err => {
throw new Error('go this error');
});
//部屋人数確認
const c4 = await db.doSql (
constant.SQL_ID_0003S,
t.data,
0
).catch(err => {
throw new Error('go this error');
});
// 定員オーバーなら
if (c4[0][constant.ROOM_UPPER] - 0 < c4[0]['COUNT'] - 0) {
throw new Error('go this error');
}
t.data[constant.SEND_SYSTEM] = '1';
t.data[constant.MESSAGE] = '--' + t.data[constant.NAME] + 'さんが入室しました';
//入室しました
const c5 = await db.doSql (
constant.SQL_ID_1003I,
t.data,
1
).catch(err => {
throw new Error('go this error');
});
//コミット (コミットする時に記述する)
await db.commitDo();
return t.data[constant.DEAR];
} catch (e) {
//ロールバック (ロールバックする時に記述する)
db.roleBack();
return constant.ERROR;
}
}
}
module.exports = Api4;
|
const Command = require('../Command');
const defaults = { uses: 1, validity: 0, channel: '345898350333263882' };
const idRegex = /[0-9]{17,19}/;
class Invite extends Command {
constructor(bot) {
super('invite', bot);
}
async exec(msg, args) {
if (msg.author.id !== '128392910574977024') {
return msg.channel.createMessage('no u');
}
let uses = defaults.uses;
let validity = defaults.validity;
let channel = defaults.channel;
if (args.length === 1) {
uses = args[0];
} else if (args.length > 1) {
uses = Invite._parseUses(args[0]);
validity = Invite._parseValidity(args[1]);
channel = Invite._parseChannel(args[2], msg);
}
let invite;
try {
invite = await this.bot.createChannelInvite(channel, {
maxAge: validity,
maxUses: uses,
unique: true,
}, `Invite created by ${msg.author.username}#${msg.author.discriminator}`);
} catch (e) {
return msg.channel.createMessage('<a:ablobcatmegasip:446624772244373504> Missing Permissions to create invite');
}
const dmChannel = await msg.author.getDMChannel();
await dmChannel.createMessage(`https://discord.gg/${invite.code}`);
return msg.channel.createMessage(Invite._createResponseMessage(channel, validity, uses));
}
static _createResponseMessage(channel, validity, uses) {
const pluralTimes = uses === 1 ? 'once' : `up to ${uses} times`;
const pluralValidity = validity === 0 ? 'forever' : `for ${validity} days`;
return `Created an invite for channel <#${channel}> that is valid ${pluralValidity} and can be used ${pluralTimes}`;
}
static _parseUses(uses) {
if (typeof uses === 'number') {
return uses;
}
switch (uses) {
case 'single':
return 1;
case 'double':
return 2;
case 'tripple':
return 3;
case 'ten':
return 10;
default:
break;
}
return defaults.uses;
}
static _parseValidity(validity) {
if (typeof validity === 'number') {
return validity;
}
switch (validity) {
case 'unlimited':
return 0;
case '1day':
return 86400;
case '1week':
return 86400 * 7;
default:
break;
}
return defaults.validity;
}
static _parseChannel(channel, msg) {
if (!channel) {
return defaults.channel;
}
if (channel.startsWith('<#') && channel.endsWith('>')) {
channel = channel.substring(2, channel.length - 1);
}
if (idRegex.test(channel)) {
if (msg.channel.guild.channels.has(channel)) {
return channel;
}
}
return defaults.channel;
}
}
module.exports = Invite;
|
$(document).ready(function() {
var session = [25, 0];//initial work time [minutes, seconds]
var brkTime = [5, 0]; // initial break time
var sessionTimer, breakTimer;
var session_is_on = 0;// on/off signal for timer. 0: off, 1: on
var break_is_on = 0;
//initial work clock time display
$("#session-minutes").text(session[0]);
$("#session-seconds").text("0" + session[1]);
//initial break clock time display
$("#break-minutes").text(brkTime[0]);
$("#break-seconds").text("0" + brkTime[1]);
//Initializes work timer
function initSession() {
sessionTimer = setInterval(function() {
timer("session", session)
}, 1000);
}
//initializes break timer
function initBreak() {
breakTimer = setInterval(function() {
timer("break", brkTime)
}, 1000);
}
$("#session").click(function() {
clearTimeout(breakTimer);//pauses any running break timer
break_is_on = 0;//time off
if (!session_is_on) {//if work timer is off, begin timer, signal to on
session_is_on = 1;
initSession();
}
$("#reset").text("Reset Break Time");
$("#break").removeClass("btn-success active").addClass("btn-primary");//unhighlight previously deactivated timer button
$(this).removeClass("btn-primary").addClass("btn-success active");//highlight active timer button
$("#break-clock").removeClass("running");//unhighlights previously active timer
$("#session-clock").addClass("running");//highlights active timer
});
$("#break").click(function() {
clearTimeout(sessionTimer);
session_is_on = 0;
if (!break_is_on) {
break_is_on = 1;
initBreak();
}
$("#reset").text("Reset Work Time")
$("#session").removeClass("btn-success active").addClass("btn-primary");
$(this).removeClass("btn-primary").addClass("btn-success active");
$("#session-clock").removeClass("running");
$("#break-clock").addClass("running");
});
$("#reset").click(function() {//function will reset whichever timer is currently idle
if (session_is_on === 0) {
clearInterval(sessionTimer); //resets idle timer
session[0] = 25;
session[1] = 0;
$("#session-minutes").text(session[0]);
$("#session-seconds").text("0" + session[1]);
} else if (break_is_on === 0) {
clearInterval(breakTimer);
brkTime[0] = 5;
brkTime[1] = 0;
$("#break-minutes").text(brkTime[0]);
$("#break-seconds").text("0" + brkTime[1]);
}
})
$("#session-plus").click(function() {//adds time to work clock in minutes
session[0]++;
$("#session-minutes").text(session[0]);
});
$("#break-plus").click(function() {//adds time to break clock in minutes
brkTime[0]++;
$("#break-minutes").text(brkTime[0]);
});
$("#session-minus").click(function() {//subtracts time from work clock in minutes
/*add("session");*/
if(session[0] > 0){
session[0]--;
$("#session-minutes").text(session[0]);
} else {
session[0] = 25;
$("#session-minutes").text(session[0]);
}
});
$("#break-minus").click(function() {//subtracts time from break clock in minutes
if(brkTime[0] > 0) {
brkTime[0]--;
$("#break-minutes").text(brkTime[0]);
} else {
brkTime[0] = 5;
$("#break-minutes").text(brkTime[0]);
}
});
function reset() {//resets a timer when a timer has expired
if (session_is_on === 1) {
clearInterval(sessionTimer);
session_is_on = 0;
session[0] = 25;
session[1] = 0;
$("#session-minutes").text(session[0]);
$("#session-seconds").text("0" + session[1]);
$("#session-clock").removeClass("running");
$("#session").removeClass("btn-success active").addClass("btn-primary");
} else if (break_is_on === 1) {
clearInterval(breakTimer);
break_is_on = 0;
brkTime[0] = 5;
brkTime[1] = 0;
$("#break-minutes").text(brkTime[0]);
$("#break-seconds").text("0" + brkTime[1]);
$("#break-clock").removeClass("running");
$("#break").removeClass("btn-success active").addClass("btn-primary");
}
}
function timer(name, arr) {
var minutes = "#" + name + "-minutes";
var seconds = "#" + name + "-seconds";
arr[1]--;
if (arr[1] === -1 && arr[0] >= 1) {
arr[1] = 59;
arr[0]--;
$(minutes).text(arr[0]);
$(seconds).text(arr[1]);
} else if (arr[1] <= -1 && arr[0] === 0) {
arr[1] = 0;
$(minutes).text(arr[0]);
$(seconds).text("0" + arr[1]);
reset();
if (name === "session") {
alert("take a break!");
} else {
alert("back to work");
}
} else if (arr[1] < 10) {
$(seconds).text("0" + arr[1]);
} else {
$(seconds).text(arr[1]);
}
}
});
|
import punycode from 'punycode';
import {trim, unprefix} from './strings';
export function formatURL(s) {
s = trim(s, '/');
s = unprefix(s, 'http://');
s = unprefix(s, 'https://');
return punycode.toUnicode(s);
}
export function formatPriceRange(lower, upper, currency) {
if (lower == null && upper == null) {
return '—';
} else if (lower == 0 && upper == 0){
return 'бесплатно';
} else if (lower == upper) {
return formatCurrency(lower, currency);
} else if (upper && !lower) {
return `до ${formatCurrency(upper, currency)}`;
} else if (!upper && lower) {
return `от ${formatCurrency(lower, currency)}`;
} else {
return formatCurrency(
`${formatNumber(lower)}–${formatNumber(upper)}`,
currency
);
}
}
export function formatCurrency(value, currency, useGrouping=false) {
const format = getCurrencyFormat(currency);
if (typeof value == 'number') value = formatNumber(value, useGrouping);
return format.replace('{value}', value);
}
export function getCurrencyFormat(currency) {
const sentinel = 1234;
const localized = sentinel.toLocaleString('ru', {
currency,
useGrouping: false,
style: 'currency',
minimumFractionDigits: 0,
});
return localized.replace(String(sentinel), '{value}');
}
export function formatNumber(n, useGrouping=false) {
return n.toLocaleString('ru', {
useGrouping,
style: 'decimal',
minimumFractionDigits: 0,
});
}
export function formatPhoneNumber(number, region) {
return number
.replace(/\+7 (\d\d\d) (\d\d\d-\d\d-\d\d)/, '+7 ($1) $2')
.replace(/-/g, '‒');
}
export function formatDuration(duration) {
const days = Math.floor(duration.asDays());
const hours = duration.hours();
const minutes = duration.minutes();
const parts = [];
if (days) parts.push(pluralize.days(days));
if (hours) parts.push(pluralize.hours(hours));
if (minutes) parts.push(pluralize.minutes(minutes));
return parts.join(' ');
}
export function pluralize(forms, n) {
// this is a pluralization function for Russian language
const form = (
(n % 10 === 1 && n % 100 !== 11)
? forms[0]
: (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20))
? forms[1]
: forms[2]
);
return `${n} ${form}`;
}
pluralize.days = n => pluralize(['день', 'дня', 'дней'], n);
pluralize.hours = n => pluralize(['час', 'часа', 'часов'], n);
pluralize.minutes = n => pluralize(['минута', 'минуты', 'минут'], n);
|
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var projectSchema = new Schema({
project_name: { type: String, trim: true, unique: true, required: true },
project_description: { type: String, trim: true, required: true },
addedDate: { type: Date }
}, { collection: "project_data" });
module.exports = mongoose.model('project', projectSchema);
|
import Vue from 'vue'
import Vuex from 'vuex'
import actions from './actions'
import getters from './getters'
import mutations from './mutations'
Vue.use(Vuex)
const createStore = new Vuex.Store({
state: {
userMsg: {
Role: null,
UnionId: null,
SessionKey: null,
UserOpenId: null,
Token: null
},
shareControl: true
},
getters,
actions,
mutations
})
export default createStore
|
import React, { Component } from 'react';
import StoryTile from './StoryTile';
import StoryFormContainer from './StoryFormContainer'
class StoryIndexContainer extends Component {
constructor(props) {
super(props);
this.state = {
stories: [],
}
this.addNewStory = this.addNewStory.bind(this)
}
componentDidMount() {
fetch(`/api/v1/stories`)
.then(response => {
if (response.ok) {
return response;
} else {
let errorMessage = `${response.status}(${response.statusText})` ,
error = new Error(errorMessage);
throw(error);
}
})
.then(response => response.json())
.then(response => {
let stories = response
this.setState( {
stories: stories
} )
})
.catch(error => console.error(`Error in fetch: ${error.message}`));
}
addNewStory(formPayload) {
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
fetch('/api/v1/stories', {
method: 'POST',
body: JSON.stringify(formPayload),
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken
},
credentials: 'same-origin'
})
.then(response => {
if (response.ok) {
return response;
} else {
let errorMessage = `${response.status} (${response.statusText})`,
error = new Error(errorMessage);
throw(error);
}
})
.then(response => response.json())
.then(body => {
let newStory = body
this.setState( { stories: this.state.stories.concat(newStory)} )
})
.catch(error => console.error(`Error in fetch: ${error.message}`));
}
render(){
let stories = this.state.stories.map((story) => {
return(
<StoryTile
name={story.name}
id={story.id}
key={story.id}
/>
)
})
return(
<div className="show-container">
<h2 className="story-header">Choose Your Story</h2>
<div className="story-index">{stories}
<StoryFormContainer
addNewStory={this.addNewStory}
/>
</div>
</div>
)
}
}
export default StoryIndexContainer
|
import React, { Component } from 'react';
import './../styles/UserInput.css';
import AddLocation from './AddLocation.js';
export default class UserInput extends Component {
constructor() {
super();
this.state = {
initialTime: 8,
duration: 1,
timeZone: {},
numLocation: 1,
errMsg: "",
}
}
timeDropDownLoop = (start, end) => {
let meetingTimeArr = [];
for (let i = start; i < end; i++) {
let time = i;
meetingTimeArr.push(<option value={i} key={i}> {time}:00</option>)
}
return meetingTimeArr;
}
etcDropDownLoop = () => {
const etcArr = this.props.etcList.map(el => {
let displayText = "GMT ";
if (el >= 0) displayText += "+";
return (
<option value={el} key={el}>{displayText + el}</option>
)
})
etcArr.unshift(<option value={""} key="a" disabled> {""} </option>);
return etcArr;
}
addOrSubtract = (change) => {
const duration = this.state.duration + change;
if (duration < 5 && duration > 0) {
this.setState(prevState => ({
duration: prevState.duration + change
}), () => {
if (this.state.timeZone.hasOwnProperty("location1")) this.updateResults();
})
}
}
addNewLocation = () => {
let locationArr = [];
for (let i = 0; i < this.state.numLocation; i++) {
locationArr.push(
<AddLocation
id={i + 1}
key={i + 1}
timeZoneList={this.etcDropDownLoop()}
onSelect={this.saveTimeZone} />
)
}
return locationArr;
}
saveStartTime = (e) => {
let time = parseInt(e.target.value);
this.setState({
initialTime: time
}, () => {
if (this.state.timeZone.hasOwnProperty("location1")) this.updateResults();
})
}
saveTimeZone = (e) => {
const copyTimeZone = { ...this.state.timeZone };
const keyName = "location" + e.target.name;
copyTimeZone[keyName] = e.target.value;
if (e.target.value !== '') {
this.setState({
timeZone: copyTimeZone
}, this.updateResults);
}
}
updateResults = () => {
const { initialTime, duration, timeZone } = this.state;
this.props.getUserInput(initialTime, duration, timeZone);
}
handleClick = (e) => {
e.preventDefault();
if (this.state.duration === 0) this.setState({
errMsg: "Meeting duration cannot be 0"
})
else if (this.state.numLocation < 3) {
this.setState(prevState => ({
numLocation: prevState.numLocation + 1,
errMsg: ""
}))
this.addNewLocation();
} else this.setState({
errMsg: "Max. number of locations reached"
})
}
render() {
return (
<form className="inputForm" action="">
<fieldset className="meetingStart">
<label htmlFor="initialMeetingTime">Meeting Start</label>
<select value={this.state.initialTime} onChange={this.saveStartTime} name="selectMeetingTime" id="initialMeetingTime">
{this.timeDropDownLoop(8, 19)}
</select>
</fieldset>
<label htmlFor="meetingDuration">Meeting Duration</label>
<fieldset className="addSubtract" id="meetingDuration">
<span className="srOnly">subtract meeting time</span>
<i className="fas fa-minus" aria-hidden="true" tabIndex={0} onClick={() => this.addOrSubtract(-1)}></i>
<span>{this.state.duration}</span>
<span className="srOnly">add meeting time</span>
<i className="fas fa-plus" aria-hidden="true" tabIndex={0} onClick={() => this.addOrSubtract(+1)}></i>
</fieldset>
{this.addNewLocation()}
<button type="submit" value="Submit" onClick={this.handleClick}>Add New Location</button>
<p className="errMsg">{this.state.errMsg}</p>
<p className="errMsg">{this.props.meetingMsg}</p>
</form>
);
}
}
|
import React, { Component } from 'react'
import { Dimensions,ScrollView,View,Text ,TouchableOpacity} from 'react-native';
import StyleSheet from './ContactStyle';
import AutoHeightImage from 'react-native-auto-height-image' ;
import Footer from '../../Footer/Footer'
import { Actions } from 'react-native-router-flux';
export default class Contact extends Component {
// state = {
// search: '',
// };
// updateSearch = search => {
// this.setState({ search });
// };
render() {
// const { search } = this.state.search
const Contact = this.props.contact
return (
<ScrollView>
<TouchableOpacity activeOpacity={0.7} onPress={() => Actions.detail()}>
<View style={StyleSheet.container}>
<View style={StyleSheet.userImageView}>
<AutoHeightImage style={StyleSheet.userImage}
width={Dimensions.get('window').width}
source={require('../../../images/image-1.png')}
/>
</View>
<View style={StyleSheet.content}>
<View style={StyleSheet.header}>
<View>
<Text style={StyleSheet.title}>{Contact.title}</Text>
</View>
</View>
</View>
<View style={StyleSheet.detail}>
<AutoHeightImage
width={Dimensions.get('window').width/25}
source={require('../../../images/next_more.png')}
/>
</View>
</View>
</TouchableOpacity>
</ScrollView>
)
}
}
|
var pageSize = 25;
////表名數據
//var tableNameStore = Ext.create('Ext.data.Store', {
// fields: ['table_name'],
// data: [{ 'table_name': 'comment_detail' },
// { 'table_name': 'comment_num' }
// ]
//});
var tableNameStore = Ext.create('Ext.data.Store', {
fields: [
{ name: 'table_name', type: 'string' },
{ name: 'table_function', type: 'string' },
],
data: [{ 'table_name': 'comment_detail', 'table_function': '評價回覆' },
{ 'table_name': 'comment_num', 'table_function': '商品評價' },
]
});
//表名數據
//var tableNameStore = Ext.create('Ext.data.Store', {
// fields: ['table_name'],
// autoLoad: true,
// proxy: {
// type: 'ajax',
// url: "/ProductComment/GetTableName",
// noCache: false,
// actionMethods: 'post',
// reader: {
// type: 'json',
// root: 'data'
// }
// }
//});
//歷史記錄列表grid
var listStore = Ext.create('Ext.data.Store', {
fields: ['pk_id','comment_id', 'user_name', 'create_time'],
pageSize: pageSize,
//autoLoad: true,
proxy: {
type: 'ajax',
url: '/ProductComment/GetChangeLogList',
actionMethods: 'post',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
});
//歷史詳情
var historyDetailStore = Ext.create('Ext.data.Store', {
fields: ['pk_id', 'comment_id_display', 'change_table', 'change_table_function', 'tclModel'], //'change_field', 'field_ch_name', 'old_value', 'new_value'],
proxy: {
type: 'ajax',
url: "/ProductComment/GetChangeLogDetailList",
noCache: false,
actionMethods: 'post',
reader: {
type: 'json',
root: 'data'
}
}
});
listStore.on("beforeload", function ()
{
Ext.apply(listStore.proxy.extraParams, {
table_name: Ext.getCmp('table_name').getValue(),
comment_id: Ext.getCmp('comment_id').getValue(),
start_time: Ext.getCmp('date_one').getValue(),
end_time: Ext.getCmp('date_two').getValue()
})
})
var searchfrm = Ext.create('Ext.form.Panel', {
id: 'searchfrm',
layout: 'column',
border: false,
defaults: { margin: '5 5 5 5' },
items: [
{
fieldLabel: '功能',
id: 'table_name',
name: 'table_name',
labelWidth: 43,
width: 230,
xtype: 'combobox',
editable: false,
allowBlank: false,
displayField: 'table_function',
valueField: 'table_name',
store: tableNameStore,
listeners: {
beforerender: function ()
{
tableNameStore.load({
callback: function ()
{
Ext.getCmp("table_name").setValue(tableNameStore.data.items[0].data.table_name);
}
});
}
}
},
{
xtype: 'numberfield',
allowBlank: true,
id: 'comment_id',
name: 'comment_id',
fieldLabel: '評價編號',
labelWidth: 60,
minValue: 1,
listeners: {
specialkey: function (field, e)
{
if (e.getKey() == Ext.EventObject.ENTER)
{
Search();
}
}
}
},
{
xtype: 'displayfield',
margin: '5 0 5 30',
value: "創建時間:"
},
{
xtype: "datetimefield",
width: 150,
margin: '5 0 0 0',
id: 'date_one',
name: 'date_one',
editable: false,
format: 'Y-m-d H:i:s',
time: { hour: 00, min: 00, sec: 00 },//開始時間00:00:00
submitValue: true,
value: new Date(Tomorrow().setMonth(Tomorrow().getMonth() - 1)),
listeners: {
select: function (a, b, c)
{
var start = Ext.getCmp("date_one");
var end = Ext.getCmp("date_two");
if (end.getValue() == null)
{
end.setValue(setNextMonth(start.getValue(), 1));
} else if (start.getValue()>end.getValue())
{
Ext.Msg.alert(INFORMATION, DATA_TIP);
end.setValue(setNextMonth(start.getValue(), 1));
}
}
}
},
{
xtype: 'displayfield',
margin: '5 0 0 0',
value: "~"
},
{
xtype: "datetimefield",
format: 'Y-m-d H:i:s',
editable: false,
time: { hour: 23, min: 59, sec: 59 },//開始時間00:00:00
id: 'date_two',
name: 'date_two',
margin: '5 0 0 0',
width: 150,
value: setNextMonth(Tomorrow(), 0),
listeners: {
select: function (a, b, c)
{
var start = Ext.getCmp("date_one");
var end = Ext.getCmp("date_two");
if (start.getValue() != "" && start.getValue() != null)
{
if (end.getValue() < start.getValue())
{
Ext.Msg.alert(INFORMATION, DATA_TIP);
start.setValue(setNextMonth(end.getValue(), -1));
}
}
else
{
start.setValue(setNextMonth(end.getValue(), -1));
}
}
}
},
{
xtype: 'splitter',
width: 36
},
{
xtype: 'button',
text: '查 詢',
iconCls: 'icon-search',
width: 60,
border: true,
handler: Search
},
{
xtype: 'button',
text: '重置',
iconCls: 'ui-icon ui-icon-reset',
width: 60,
border: true,
handler: function ()
{
Ext.getCmp('comment_id').setValue(null);
Ext.getCmp('date_one').reset();
Ext.getCmp('date_two').reset();
}
},
{
icon: '../../../Content/img/icons/excel.gif',
xtype: 'button',
text: '匯出',
width: 60,
border: true,
handler: ExportCSV
},
]
})
var gridlist = Ext.create('Ext.grid.Panel', {
id: 'gridlist',
layout: 'anchor',
autoScroll: true,
border: false,
hidden: true,
frame: true,
store: listStore,
height: document.documentElement.clientHeight - 42,
columns: [
{ header: '評價編號', dataIndex: 'comment_id', align: 'left', width: 166, menuDisabled: true, sortable: false, flex: 1 },
{
header: '主鍵值', dataIndex: 'pk_id', align: 'left', width: 166, menuDisabled: true, sortable: false, flex: 1,
colName: 'col_pkid', hidden: true
},
{ header: '創建人', dataIndex: 'user_name', align: 'left', width: 65, menuDisabled: true, sortable: false, flex: 1 },
{ header: '創建時間', dataIndex: 'create_time', align: 'left', width: 166, menuDisabled: true, sortable: false }
],
bbar: Ext.create('Ext.PagingToolbar', {
store: listStore,
dock: 'bottom',
pageSize: pageSize,
displayInfo: true
}),
listeners: {
itemclick: function (grid, record)
{
historyDetailStore.removeAll();
historyDetailStore.load({
params: {
pk_id: record.data.pk_id,
create_time: record.data.create_time,
comment_id_display: record.data.comment_id
}
})
},
viewready: function ()
{
setShow(gridlist, 'colName');
}
}
})
var AuthView = Ext.create('Ext.view.View', {
deferInitialRefresh: false,
autoScroll: true,
frame: false,
store: historyDetailStore,//{change_table}+ GetTableFunction(+'+Ext.getCmp("comment_id_display").getValue() +'
tpl: Ext.create('Ext.XTemplate',
'<div id="div_historyDetail" class="View">',
'<ul class="ul-detail">',
'<tpl for=".">',
'<li>',
'<h2>評價編號:{comment_id_display} 功能:{change_table_function} </h2>',
'<table class="tbl-cls" style="width:800px">',
'<tr><th style="width:200px">欄位</th><th style="width:200px">欄位中文名稱</th><th style="width:200px">修改前</th><th style="200px">修改后</th></tr>',
'<tpl for="tclModel">',
'<tr ><td>{change_field}</td><td>{field_ch_name}</td><td>{old_value}</td><td>{new_value}</td>',
'</tr>',
'</tpl>',
'</table>',
'</li>',
'</tpl>',
'</ul>',
'</div>'
),
itemSelector: 'li-detail'
});
Ext.onReady(function ()
{
Ext.create('Ext.Viewport', {
id: "index",
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
layout: 'border',
items: [{
region: 'north',//上北
xtype: 'panel',
height: 30,
split: false,
items: searchfrm,
margins: '3 3 0 3'
}, {
region: 'west',//左西
xtype: 'panel',
margins: '3 0 3 3',
width: 400,
autoScroll: true,
frame: false,
layout: 'anchor',
items: gridlist
}, {
region: 'center',//中間
xtype: 'panel',
//width: 1000,
//height: 1000,
layout: 'fit',
margins: '3 3 3 3',
items: AuthView
}],
renderTo: Ext.getBody(),
listeners: {
resize: function ()
{
Ext.getCmp("index").width = document.documentElement.clientWidth;
Ext.getCmp("index").height = document.documentElement.clientHeight;
this.doLayout();
},
afterrender: function ()
{
ToolAuthorityQuery(function () { })
}
}
});
ToolAuthority();
});
//查詢
function Search()
{
comment_id=Ext.getCmp('comment_id').getValue(),
start_time=Ext.getCmp('date_one').getValue(),
end_time=Ext.getCmp('date_two').getValue()
if (comment_id == ("" || null) && start_time == ("" || null) && end_time == ("" || null))
{
Ext.Msg.alert(INFORMATION, "請輸入查詢條件");
return;
}
Ext.getCmp("gridlist").show();
//tableNameStore.removeAll();
Ext.getCmp("gridlist").store.loadPage(1, {
params: {
table_name: Ext.getCmp('table_name').getValue(),
comment_id: Ext.getCmp('comment_id').getValue(),
start_time: Ext.getCmp('date_one').getValue(),
end_time: Ext.getCmp('date_two').getValue()
}
});
}
//匯出
function ExportCSV()
{
comment_id = Ext.getCmp('comment_id').getValue(),
start_time = Ext.getCmp('date_one').getValue(),
end_time = Ext.getCmp('date_two').getValue()
if (comment_id == ("" || null) && start_time == ("" || null) && end_time == ("" || null))
{
Ext.Msg.alert(INFORMATION, "請輸入查詢條件");
return;
}
Ext.Ajax.request({
url: "/ProductComment/ProductCommentLogExport",
params: {
table_name: Ext.getCmp('table_name').getValue(),
comment_id: Ext.getCmp('comment_id').getValue(),
start_time: Ext.getCmp('date_one').getValue(),
end_time: Ext.getCmp('date_two').getValue()
},
success: function (response)
{
if (response.responseText.split(',')[0] == "true")
{
window.location.href = '../..' + response.responseText.split(',')[2] + response.responseText.split(',')[1];
}
}
});
}
setNextMonth = function (source, n)
{
var s = new Date(source);
s.setMonth(s.getMonth() + n);
if (n < 0)
{
s.setHours(0, 0, 0);
}
else if (n > 0)
{
s.setHours(23, 59, 59);
}
return s;
}
/******************************************************************************************************************************************************************************************/
function Tomorrow() {
var d;
var dt;
var s = "";
d = new Date(); // 创建 Date 对象。
s += d.getFullYear() + "/"; // 获取年份。
s += (d.getMonth() + 1) + "/"; // 获取月份。
s += d.getDate();
dt = new Date(s);
dt.setDate(dt.getDate() + 1);
return dt; // 返回日期。
}
function setNextMonth(source, n) {
var s = new Date(source);
s.setMonth(s.getMonth() + n);
if (n < 0) {
s.setHours(0, 0, 0);
}
else if (n >= 0) {
s.setHours(23, 59, 59);
}
return s;
}
|
import React, { PropTypes } from 'react'
import marked from 'marked'
import hljs from 'highlight.js'
// require('github-markdown-css')
function rawHTML(html) {
marked.setOptions({
sanitize: true,
gfm: true,
highlight: function (code) {
return hljs.highlightAuto(code).value
}
})
return {
__html: marked(html)
}
}
export default function Preview(props) {
return (
<div
className='markdown-body'
dangerouslySetInnerHTML={rawHTML(props.text)}
/>
)
}
Preview.propTypes = {
text: PropTypes.string.isRequired
}
|
import Link from 'next/link';
import Nav from './nav';
import { Logo } from '../qin/Logo';
function QinHeader() {
return (
<header className='text-gray-600 body-font'>
<div className='container mx-auto flex flex-wrap p-2 flex-col md:flex-row items-center'>
<Link href='/'>
<a className='flex title-font font-medium items-center text-gray-900 mb-2 md:mb-0'>
<Logo />
</a>
</Link>
<Nav />
</div>
</header>
);
}
export default QinHeader;
|
import Hisotry from "./history";
export default Hisotry;
|
// Convert 1.Y.Z components to their individual counterpart
module.exports = {
Accordion: {
isChild: true,
package: "core-expand-collapse",
combineWith: ["ExpandCollapse"]
},
Box: "core-box",
Button: "core-button",
ButtonLink: "core-button-link",
Card: "core-card",
Checkbox: "core-checkbox",
ChevronLink: "core-chevron-link",
DecorativeIcon: "core-decorative-icon",
DimpleDivider: "core-dimple-divider",
DisplayHeading: "core-display-heading",
ExpandCollapse: {
isChild: true,
package: "core-expand-collapse",
combineWith: ["Accordion"]
},
FlexGrid: "core-flex-grid",
HairlineDivider: "core-hairline-divider",
Heading: "core-heading",
Image: "core-image",
Input: "core-input",
InputFeedback: "core-input-feedback",
Link: "core-link",
Notification: "core-notification",
OrderedList: "core-ordered-list",
Paragraph: "core-paragraph",
Radio: "core-radio",
Responsive: "core-responsive",
Select: "core-select",
SelectorCounter: "core-selector-counter",
Small: "core-small",
Spinner: "core-spinner",
StandaloneIcon: "core-standalone-icon",
StepTracker: "core-step-tracker",
Strong: "core-strong",
Text: "core-text",
TextArea: "core-text-area",
Tooltip: "core-tooltip",
UnorderedList: "core-unordered-list",
WaveDivider: "core-wave-divider"
};
|
const serializeError = require('serialize-error').serializeError;
const core = require('../drivers/core_driver');
function _handleError(error) {
this.set('Content-Type', 'application/json; charset=utf-8');
this.statusCode = error.code || error.statusCode || 500;
this.send(serializeError(error));
}
let socketAPI;
module.exports = {
setSocket(socket) {
socketAPI = socket;
},
routes: {
get: {
all: async (req, res) => {
try {
const temp = await core.getTemp();
const frequency = await core.getFrequency();
res.json({
temp,
frequency
});
} catch (error) {
_handleError.bind(res)(error);
}
},
temperature: async (req, res) => {
try {
const temp = await core.getTemp();
res.json({ temp });
} catch (error) {
_handleError.bind(res)(error);
}
},
frequency: async (req, res) => {
try {
const frequency = await core.getFrequency();
res.json({ frequency });
} catch (error) {
_handleError.bind(res)(error);
}
},
coreFrequency: async (req, res) => {
try {
const coreFrequency = await core.getCoreFrequency();
res.json({ coreFrequency });
} catch (error) {
_handleError.bind(res)(error);
}
},
usage: async (req, res) => {
try {
const usage = await core.getUsage();
res.json({ usage });
} catch (error) {
_handleError.bind(res)(error);
}
}
}
}
}
|
import React from "react";
import { Link, useParams } from "react-router-dom";
import Container from "react-bootstrap/Container";
import Jumbotron from "react-bootstrap/Jumbotron";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faEnvelope,
faImage,
faExternalLinkAlt,
} from "@fortawesome/free-solid-svg-icons";
const AuthorDetail = ({ authors }) => {
let { slug } = useParams();
return (
<div>
<Jumbotron id="authorsJumbotron" fluid>
<Container>
<h1>The people behind</h1>
<p>Cheese is our life</p>
</Container>
</Jumbotron>
{authors.length >= 1 &&
authors
.filter((author) => author.slug === slug)
.map((author) => (
<Container>
<div className="authorCard">
<img
src={`${author.imageurl}`}
alt={`${author.slug}`}
/>
<h1>{author.name}</h1>
<p className="title">{author.title}</p>
<p>{author.shortBio}</p>
<a
href={`https://www.linkedin.com/in/${author.linkedIn}`}
target="_blank"
>
<FontAwesomeIcon
icon={faImage}
size="3x"
id="socialbutton"
/>
</a>
<a
href={`https://github.com/${author.github}`}
target="_blank"
>
<FontAwesomeIcon
icon={faExternalLinkAlt}
size="3x"
id="socialbutton"
/>
</a>
<a href={`mailto:${author.email}`}>
<FontAwesomeIcon
icon={faEnvelope}
size="3x"
id="socialbutton"
/>
</a>
</div>
</Container>
))}
</div>
);
};
export default AuthorDetail;
|
$(document).ready(function () {
$('#hello_div').click(function () {
let login_form = `ID<input id="id"><br>`;
login_form += `PW<input id="pw" type="password"><br>`
login_form += `<input id="login_button" type="button" value="login">`
$('#login_div').html(login_form);
});
$(document).on('click', '#login_button', function () {
const id = $('#id').val();
const pw = $('#pw').val();
const send_param = {
id,
pw
};
//alert(id + ":" + pw);
$.post('login', send_param, function (returnData) {
alert(returnData.message);
});
});
});
|
"use strict";
var controlPanel = function (){
var socket = null,
settings = {
host: 'ws://192.168.1.21:9000',
logID: 'span_log'
},
open_socket = function( ){
socket = comm.connect(settings);
}, // function open_socket
sendCommand = function( command ){
if ( socket ){
console.log("Enviando commando " + command);
socket.send(JSON.stringify( {cmd: command} ) );
}
else{
console.log("Error. No hay socket abierto para enviar commando " + command);
}
},
/*
Asigns events to buttons
*/
init_buttons = function(){
document.getElementById("btn_read_usb").onclick=function(){
sendCommand("usb");
};
document.getElementById("btn_read_local").onclick=function(){
sendCommand("local");
};
document.getElementById("btn_get_segonahora").onclick=function(){
sendCommand("lasegonahora");
};
document.getElementById("btn_get_lacompetencia").onclick=function(){
sendCommand('lacompetencia');
};
document.getElementById("btn_video").onclick=function(){
//return_videoPlayer();
window.location.assign("/videoplayerc.html");
};
document.getElementById("btn_mp3").onclick=function(){
window.location.assign("/mp3playerc.html");
};
$("#video_title").click( function(){
$.mobile.pageContainer.pagecontainer("change", "#videos");
});
$("#subtitles_title").click( function(){
$.mobile.pageContainer.pagecontainer("change", "#subtitles");
});
$("#mp3_title").click( function(){
$.mobile.pageContainer.pagecontainer("change", "#mp3");
});
$("[name='select_fixed_mp3']").change( function(){
localStorage.setItem('mp3', this.value);
});
},
init = function(){
$( document ).on( "click", ".show-page-loading-msg", function() {
$(this).attr('disabled','');
var $this = $( this ),
theme = $this.jqmData( "theme" ) || $.mobile.loader.prototype.options.theme,
msgText = $this.jqmData( "msgtext" ) || $.mobile.loader.prototype.options.text,
textVisible = $this.jqmData( "textvisible" ) || $.mobile.loader.prototype.options.textVisible,
textonly = !!$this.jqmData( "textonly" ),
html = $this.jqmData( "html" ) || "";
$.mobile.loading( "show", {
text: msgText,
textVisible: textVisible,
theme: theme,
textonly: textonly,
html: html
});
})
.on( "click", ".hide-page-loading-msg", function() {
$.mobile.loading( "hide" );
});
reload_media();
init_buttons();
open_socket();
};
return {
init: init
};
}(); // controlPanel
/*******************************************************************************
********************************************************************************
********************************************************************************
*******************************************************************************/
function reload_media()
{
var video = localStorage.getItem("video");
var subtitles = localStorage.getItem("subtitles");
if( video !== null && video !== '' ){
$('#video_title').text(video.slice( video.lastIndexOf("/") +1 ) );
}
if( subtitles !== null && subtitles !== '' ){
$('#subtitles_title').text(subtitles.slice( subtitles.lastIndexOf("/") +1 ) );
}
get_fixed_mp3()
get_videos();
get_subtitles();
get_mp3();
}
function get_fixed_mp3()
{
var radioInput="";
var spanText;
var radioParent = document.getElementById("fixed_mp3");
var fixed_mp3 = localStorage.getItem("mp3");
var option=""
radioParent.innerHTML="";
// segonahora
option = "/home/pi/multimedia/musica/segonahora.mp3";
radioInput = document.createElement("input")
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', "select_fixed_mp3");
radioInput.setAttribute('value', option);
if( option.localeCompare( fixed_mp3 ) == 0 )
radioInput.setAttribute('checked', 'checked');
radioParent.appendChild(radioInput);
spanText = document.createElement("span")
spanText.innerHTML = option.slice( option.lastIndexOf("/") +1 ) + " ";
radioParent.appendChild(spanText);
// la competencia
option = "/home/pi/multimedia/musica/lacompetencia.mp3";
radioInput = document.createElement("input")
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', "select_fixed_mp3");
radioInput.setAttribute('value', option);
if( option.localeCompare( fixed_mp3 ) == 0 )
radioInput.setAttribute('checked', 'checked');
radioParent.appendChild(radioInput);
spanText = document.createElement("span")
spanText.innerHTML = option.slice( option.lastIndexOf("/") +1 ) + "<br />";
radioParent.appendChild(spanText);
}
function get_videos( )
{
var xhr = new XMLHttpRequest();
if ( typeof xhr.withCredentials === undefined ){
return false;
}
xhr.onerror = function(e){
alert( "Error getting media data." );
}
xhr.onprogress = function(e){
var ratio = e.loaded / e.total;
//debug( ratio + "% descargado." );
}
// Data received
xhr.onload = function(e){
received_videos(e, xhr);
}
xhr.open("GET", "videos.json", true);
//param_post = "tipo=1";
xhr.setRequestHeader ('Content-type','application/x-www-form-urlencoded')
//xhr.send( param_post );
xhr.send( );
}
function received_videos(e, xhr){
var li;
var ul = $('#ul_videos');
var video = localStorage.getItem("video");
ul.find("li").remove();
ul.append('<li><a href="javascript:selected_video(\'\')">No video</a></li>');
var aVideos = JSON.parse(xhr.responseText);
for( var n=0;n<aVideos.length;n++){
li = '<li><a href="javascript:selected_video(\'' + aVideos[n] + '\')">';
li += aVideos[n].slice( aVideos[n].lastIndexOf("/") +1 );
li += '</a></li>';
ul.append(li);
}
if ( ul.hasClass('ui-listview')) {
ul.listview('refresh');
}
else {
ul.trigger('create');
}
}
function selected_video(sel_video){
localStorage.setItem('video',sel_video);
if( sel_video != '' )
$('#video_title').text(sel_video.slice( sel_video.lastIndexOf("/") +1 ) );
else
$('#video_title').text('No video');
$.mobile.pageContainer.pagecontainer("change", "#mediam");
}
function get_subtitles( )
{
var xhr = new XMLHttpRequest();
if ( typeof xhr.withCredentials === undefined ){
return false;
}
xhr.onerror = function(e){
alert( "Error getting media data." );
}
xhr.onprogress = function(e){
var ratio = e.loaded / e.total;
//debug( ratio + "% descargado." );
}
// Data received
xhr.onload = function(e){
received_subtitles(e, xhr);
}
xhr.open("GET", "subtitles.json", true);
xhr.setRequestHeader ('Content-type','application/x-www-form-urlencoded')
xhr.send( );
}
function received_subtitles(e, xhr){
var li;
var ul = $('#ul_subtitles');
var subtitles = localStorage.getItem("subtitles");
ul.find("li").remove();
ul.append('<li><a href="javascript:selected_subtitles(\'\')">No subtitles</a></li>');
var aSubtitles = JSON.parse(xhr.responseText);
for( var n=0;n<aSubtitles.length;n++){
li = '<li><a href="javascript:selected_subtitles(\'' + aSubtitles[n] + '\')">';
li += aSubtitles[n].slice( aSubtitles[n].lastIndexOf("/") +1 );
li += '</a></li>';
ul.append(li);
}
if ( ul.hasClass('ui-listview')) {
ul.listview('refresh');
}
else {
ul.trigger('create');
}
}
function selected_subtitles(sel_subtitles){
localStorage.setItem('subtitles',sel_subtitles);
if( sel_subtitles != '' )
$('#subtitles_title').text(sel_subtitles.slice( sel_subtitles.lastIndexOf("/") +1 ) );
else
$('#subtitles_title').text('----' );
$.mobile.pageContainer.pagecontainer("change", "#mediam");
}
function get_mp3( )
{
var xhr = new XMLHttpRequest();
if ( typeof xhr.withCredentials === undefined ){
return false;
}
xhr.onerror = function(e){
alert( "Error getting media data." );
}
xhr.onprogress = function(e){
var ratio = e.loaded / e.total;
//debug( ratio + "% descargado." );
}
// Data received
xhr.onload = function(e){
received_mp3(e, xhr);
}
xhr.open("GET", "mp3.json", true);
xhr.setRequestHeader ('Content-type','application/x-www-form-urlencoded')
xhr.send( );
}
function received_mp3(e, xhr){
var input, name,id;
var fs = $('#fieldset_mp3');
//var video = localStorage.getItem("video");
fs.find('input').remove();
fs.find('label').remove();
//ul.append('<li><a href="javascript:selected_mp3(\'\')">Clear list</a></li>');
var aMP3 = JSON.parse(xhr.responseText);
for( var n=0;n<aMP3.length;n++){
name = aMP3[n];
id = aMP3[n].slice( aMP3[n].lastIndexOf("/") +1 );
/*
if( aVideos[n].localeCompare( video ) == 0 )
li += ' data-icon="check"';
*/
input = '<input type="checkbox" name="' + name + '"';
input += ' id="' + id + '">';
input += '<label for="' + id + '">' + id + '</label>';
fs.append(input);
}
if ( fs.hasClass('ui-listview')) {
fs.listview('refresh');
}
else {
fs.trigger('create');
}
}
// Funcion inservible
function return_videoPlayer(){
var n;
var videos = document.getElementsByName("select_video");
var subtitles = document.getElementsByName("select_subtitles");
n=0;
while( n < videos.length ){
if( videos[n].checked ){
localStorage.setItem( "video", videos[n].value );
break;
}
n++;
}
n=0;
while( n < subtitles.length ){
if( subtitles[n].checked ){
localStorage.setItem( "subtitles", subtitles[n].value );
break;
}
n++;
}
window.location.assign("/videoplayerm.html");
}
function sendXhr( signal )
{
var post_data = "";
var xhr = new XMLHttpRequest();
var video,subtitles;
if ( signal == null )
return;
post_data = "c=" + signal;
if( signal === "start" ){
video = localStorage.getItem("video");
subtitles = localStorage.getItem("subtitles");
post_data += "&video=" + video;
post_data += "&subtitles=" + subtitles;
}
xhr.onerror = function(e){
alert( "Error creating xhr signal." );
}
xhr.onprogress = function(e){
var ratio = e.loaded / e.total;
//debug( ratio + "% descargado." );
}
xhr.onreadystatechange=function()
{
if (xhr.readyState == 4 && xhr.status == 200){
// noop
}
}
xhr.open("POST", "omx_command", true);
// Envia el formulario
xhr.setRequestHeader ('Content-type','application/x-www-form-urlencoded');
xhr.send( post_data );
}
|
define(
['jQuery', 'Underscore', 'Backbone',
'collections/projects',
'text!templates/project/list.html'],
function($, _, Backbone, projectsCollection, projectListTemplate) {
var projectListView = Backbone.View.extend({
el: '#content',
initialize: function() {
this.collection = new projectsCollection;
this.collection.add([{ name: 'BackOff' }, { name: 'Moip'}]);
this.collection.add({ name: 'Big Ben' });
var compiledTemplate = _.template(projectListTemplate, { projects: this.collection.models });
$(this.el).html(compiledTemplate);
}
});
return new projectListView;
}
);
|
import {Dimensions} from 'react-native';
const DESIGN_SCREEN_WIDTH = 375;
const DESIGN_SCREEN_HEIGHT = 812;
const {width: DEVICE_SCREEN_WIDTH, height: DEVICE_SCREEN_HEIGHT} =
Dimensions.get('screen');
const widthPercent = DEVICE_SCREEN_WIDTH / DESIGN_SCREEN_WIDTH;
const heightPercent = DEVICE_SCREEN_HEIGHT / DESIGN_SCREEN_HEIGHT;
function getWidth(designWidth: number) {
const result = designWidth * widthPercent;
return Number(result.toFixed(1));
}
function getHeight(designHeight: number) {
const result = designHeight * heightPercent;
return Number(result.toFixed(1));
}
function getFontSize(designWidth: number) {
return getWidth(designWidth);
}
export const responsive = {
getWidth,
getHeight,
getFontSize,
WIDTH: DEVICE_SCREEN_WIDTH,
HEIGHT: DEVICE_SCREEN_HEIGHT,
};
|
const mongoose = require('mongoose');
//mongoose.connect('mongodb://localhost:27017/Todo', { useMongoClient: true });
mongoose.connect('mongodb://key:keyrdp@ds163745.mlab.com:63745/rdp-key', { useMongoClient: true });
module.exports = mongoose.connection;
|
// https://developers.ringcentral.com/my-account.html#/applications
// Find your credentials at the above url, set them as environment variables, or enter them below
// PATH PARAMETERS
const accountId = '<ENTER VALUE>';
const extensionId = '<ENTER VALUE>';
const ruleId = '<ENTER VALUE>';
// POST BODY
const body = {
forwarding: {
notifyMySoftPhones: true,
notifyAdminSoftPhones: true,
softPhonesRingCount: 1,
ringingMode: 'Sequentially',
rules: [
{
index: 000,
ringCount: 000,
enabled: true,
forwardingNumbers: [
{
id: '<ENTER VALUE>',
type: 'Home'
},
]
},
],
mobileTimeout: true
},
enabled: true,
name: '<ENTER VALUE>',
callers: [
{
callerId: '<ENTER VALUE>',
name: '<ENTER VALUE>'
},
],
calledNumbers: [
{
phoneNumber: '<ENTER VALUE>'
},
],
schedule: {
weeklyRanges: {
monday: [
{
from: '<ENTER VALUE>',
to: '<ENTER VALUE>'
},
],
tuesday: [
{
from: '<ENTER VALUE>',
to: '<ENTER VALUE>'
},
],
wednesday: [
{
from: '<ENTER VALUE>',
to: '<ENTER VALUE>'
},
],
thursday: [
{
from: '<ENTER VALUE>',
to: '<ENTER VALUE>'
},
],
friday: [
{
from: '<ENTER VALUE>',
to: '<ENTER VALUE>'
},
],
saturday: [
{
from: '<ENTER VALUE>',
to: '<ENTER VALUE>'
},
],
sunday: [
{
from: '<ENTER VALUE>',
to: '<ENTER VALUE>'
},
]
},
ranges: [
{
from: '<ENTER VALUE>',
to: '<ENTER VALUE>'
},
],
ref: 'BusinessHours'
},
callHandlingAction: 'ForwardCalls',
unconditionalForwarding: {
phoneNumber: '<ENTER VALUE>'
},
queue: {
transferMode: 'Rotating',
fixedOrderAgents: [
{
extension: {
id: '<ENTER VALUE>',
uri: '<ENTER VALUE>',
extensionNumber: '<ENTER VALUE>',
partnerId: '<ENTER VALUE>'
},
index: 000
},
],
holdAudioInterruptionMode: 'Never',
holdAudioInterruptionPeriod: 000,
agentTimeout: 000,
wrapUpTime: 000,
holdTime: 000,
maxCallers: 000,
maxCallersAction: 'Voicemail'
},
voicemail: {
enabled: true,
recipient: {
uri: '<ENTER VALUE>',
id: '<ENTER VALUE>'
}
},
greetings: [
{
type: 'Introductory',
usageType: 'UserExtensionAnsweringRule',
preset: {
uri: '<ENTER VALUE>',
id: '<ENTER VALUE>',
name: '<ENTER VALUE>'
}
},
],
screening: 'Off',
showInactiveNumbers: true
};
const SDK = require('ringcentral');
const rcsdk = new SDK({server: process.env.serverURL, appKey: process.env.clientId, appSecret: process.env.clientSecret});
const platform = rcsdk.platform();
platform.login({ username: process.env.username, extension: process.env.extension, password: process.env.password }).then(() => {
platform.put(`/restapi/v1.0/account/${accountId}/extension/${extensionId}/answering-rule/${ruleId}`, body).then((r) => {
// PROCESS RESPONSE
});
});
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
const currencies = [
{
name: 'AUD',
symbol: '$'
},
{
name: 'CAD',
symbol: '$'
},
{
name: 'CHF',
symbol: 'Fr.'
},
{
name: 'CNY',
symbol: '¥'
},
{
name: 'EUR',
symbol: '€'
},
{
name: 'GBP',
symbol: '£'
},
{
name: 'JPY',
symbol: '¥'
},
{
name: 'NZD',
symbol: '$'
},
{
name: 'SEK',
symbol: 'kr'
},
{
name: 'USD',
symbol: '$'
},
]
const useStyles = makeStyles((theme) => ({
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
}));
export default function CurrencyPicker(props) {
const classes = useStyles();
const handleChange = (event, onChange) => {
let currency = currencies.find(cur => cur.name === event.target.value);
onChange(currency);
};
return (
<FormControl className={classes.formControl}>
<InputLabel id="demo-simple-select-label">Select Currency</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={props.currency}
onChange={(e) => handleChange(e, props.onChange)}
>
{currencies.map(cur => (
<MenuItem key={cur.name} value={cur.name}>{cur.name}</MenuItem>
))}
</Select>
</FormControl>
);
}
|
for(var i = 0; i < 58; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u27'] = 'center';gv_vAlignTable['u17'] = 'center';gv_vAlignTable['u29'] = 'center';gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u35'] = 'center';gv_vAlignTable['u15'] = 'center';gv_vAlignTable['u44'] = 'center';gv_vAlignTable['u1'] = 'center';
u57.style.cursor = 'pointer';
$axure.eventManager.click('u57', function(e) {
if (true) {
self.location.href=$axure.globalVariableProvider.getLinkUrl('Config_Manager.html');
}
});
gv_vAlignTable['u39'] = 'center';gv_vAlignTable['u11'] = 'center';gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u3'] = 'center';gv_vAlignTable['u23'] = 'center';gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u47'] = 'center';
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
self.location.href=$axure.globalVariableProvider.getLinkUrl('Interface_Manager.html');
}
});
gv_vAlignTable['u18'] = 'top';
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
self.location.href=$axure.globalVariableProvider.getLinkUrl('User_Manager.html');
}
});
gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u5'] = 'center';gv_vAlignTable['u49'] = 'center';gv_vAlignTable['u50'] = 'top';gv_vAlignTable['u21'] = 'center';
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
self.location.href=$axure.globalVariableProvider.getLinkUrl('Algorithm_Manager.html');
}
});
u53.style.cursor = 'pointer';
$axure.eventManager.click('u53', function(e) {
if (true) {
self.location.href="resources/reload.html#" + encodeURI($axure.globalVariableProvider.getLinkUrl($axure.pageData.url));
}
});
gv_vAlignTable['u33'] = 'center';
u55.style.cursor = 'pointer';
$axure.eventManager.click('u55', function(e) {
if (true) {
self.location.href=$axure.globalVariableProvider.getLinkUrl('ScheduleManager.html');
}
});
|
/*global use */
"ODSA strict";
// Search slideshow
$(document).ready(function () {
var av_name = "BSTsearchCON";
var config = ODSA.UTILS.loadConfig({"av_name": av_name}),
interpret = config.interpreter, // get the interpreter
code = config.code; // get the code object
var av = new JSAV(av_name);
var pseudo = av.code(code[0]);
var bstTop = 45;
var bt = av.ds.binarytree({top: bstTop, left: 10, visible: true, nodegap: 15});
bt.root(37);
var rt = bt.root();
rt.left(24);
rt.left().left(7);
rt.left().left().left(2);
rt.left().right(32);
rt.right(42);
rt.right().left(42);
rt.right().left().left(40);
rt.right().right(120);
bt.layout();
var rt1 = av.pointer("rt", bt.root(), {anchor: "right top"});
// Slide 1
av.umsg(interpret("sc1"));
pseudo.setCurrentLine("sig");
av.displayInit();
// Slide 2
av.umsg(interpret("sc2"));
pseudo.setCurrentLine("checknull");
av.step();
// Slide 3
av.umsg(interpret("sc3"));
pseudo.setCurrentLine("checkgreater");
av.step();
// Slide 4
av.umsg(interpret("sc4"));
pseudo.setCurrentLine("visitleft");
av.step();
// Slide 5
av.umsg(interpret("sc5"));
pseudo.setCurrentLine("sig");
bt.root().addClass("processing");
rt1.target(bt.root().left(), {anchor: "left top"});
av.step();
// Slide 6
av.umsg(interpret("sc2"));
pseudo.setCurrentLine("checknull");
av.step();
// Slide 7
av.umsg(interpret("sc16"));
pseudo.setCurrentLine("checkgreater");
av.step();
// Slide 8
av.umsg(interpret("sc17"));
pseudo.setCurrentLine("checkequal");
av.step();
// Slide 9
av.umsg(interpret("sc7"));
pseudo.setCurrentLine("visitright");
av.step();
// Slide 10
av.umsg(interpret("sc9"));
pseudo.setCurrentLine("sig");
bt.root().left().addClass("processing");
rt1.target(bt.root().left().right(), {anchor: "right top"});
av.step();
// Slide 11
av.umsg(interpret("sc2"));
pseudo.setCurrentLine("checknull");
av.step();
// Slide 12
av.umsg(interpret("sc16"));
pseudo.setCurrentLine("checkgreater");
av.step();
// Slide 13
av.umsg(interpret("sc11"));
pseudo.setCurrentLine("checkequal");
av.step();
// Slide 14
av.umsg(interpret("sc12"));
pseudo.setCurrentLine("found");
av.step();
// Slide 15
av.umsg(interpret("sc13"));
bt.root().left().removeClass("processing");
rt1.target(bt.root().left(), {anchor: "left top"});
pseudo.setCurrentLine("visitright");
av.step();
// Slide 16
av.umsg(interpret("sc14"));
bt.root().removeClass("processing");
rt1.target(bt.root(), {anchor: "right top"});
pseudo.setCurrentLine("visitleft");
av.step();
// Slide 17
av.umsg(interpret("sc15"));
pseudo.setCurrentLine("end");
av.recorded();
});
|
define(['handlebars'], function(Handlebars) {
this["template"] = this["template"] || {};
this["template"]["AdmissionGridTemplate"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;
buffer += "<td style=\"width=25%\">";
if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.name); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ " </td\n<td style=\"width=25%\">";
if (stack1 = helpers.email) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.email); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ "</td>\n<td style=\"width=50%\">";
if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.description); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ " </td>\n<td><a href=\"javascript:return void(0);\" class=\"removeLink\"> Remove </a></td>\n";
return buffer;
});
this["template"]["AdmissionTemplate"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;
buffer += " <div class=\"well\">\n <div class=\"alert alert-danger fade in\" style=\"display:none;\"></div>\n <div class=\"form-group\">\n <label>Name:</label>\n <input type=\"text\" name=\"name\" value=\"";
if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.name); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ "\" />\n </div>\n <div class=\"form-group\">\n <label>Email:</label>\n <input type=\"text\" name=\"email\" value=\"";
if (stack1 = helpers.email) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.email); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ "\" />\n </div>\n <div class=\"form-group\">\n <label>Description:</label>\n <input type=\"text\" name=\"description\" value=\"";
if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.description); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ "\" />\n </div>\n <button class=\"save btn btn-large btn-info\" >Save</button>\n <a href=\"#\" class=\"btn btn-large btn-default\">Cancel</a>\n </div>\n\n <div id=\"grid\">\n <table style=\"width:400px\">\n <tr >\n <th style=\"width=25%\">Name</th>\n <th style=\"width=25%\">Email</th>\n <th style=\"width=40%\">Description</th>\n <th style=\"width=10%\"></th>\n </tr>\n \n </table>\n <table style=\"width:400px\" id=\"gridData\">\n\n </table>\n </div>\n\n";
return buffer;
});
this["template"]["ApplyTemplate"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;
buffer += "<div> <span>Name: ";
if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.name); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ " </span></div>";
return buffer;
});
this["template"]["HomeCompositeTemplate"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
return "<div> <p> Welcome to AAAA kjdfnjg kjrdghre kjrgr</p></div>\n<input type=\"text\" id=\"inpTxt\" /> <br/>\n<label id=\"txtValue\" />\n<div id=\"content\">\n</div>\n<div> For Admission Click link <a href='#admission' >Admission </a> </p> </div";
});
this["template"]["HomeItemTemplate"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;
buffer += "<p>";
if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.title); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ "</p>\n<div> ";
if (stack1 = helpers.desc) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.desc); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ "</div>";
return buffer;
});
this["template"]["HomeLayoutTemplate"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;
buffer += "<p>Welcome to ";
if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.name); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ " 111 334</p>\n<div id=\"compPlaceHolder\" ></div>\n";
return buffer;
});
this["template"]["StudentViewerTemplate"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression;
buffer += "<div> <span>Name: ";
if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = (depth0 && depth0.name); stack1 = typeof stack1 === functionType ? stack1.call(depth0, {hash:{},data:data}) : stack1; }
buffer += escapeExpression(stack1)
+ " </span></div>";
return buffer;
});
return this["template"];
});
|
import React, { useEffect, useContext } from 'react';
import UrlItem from './UrlItem';
import Spinner from './layout/Spinner';
import UrlContext from '../context/url/urlContext';
export const UrlsList = () => {
const urlContext = useContext(UrlContext);
const { loading, getUrls, urls } = urlContext;
useEffect(() => {
getUrls();
// eslint-disable-next-line
}, []);
if (loading) {
return <Spinner />;
} else {
return (
<table className='url-list'>
<thead>
<tr>
<th>Shortened Url</th>
<th>Slug</th>
<th>Original Url</th>
</tr>
</thead>
<tbody>
{urls.map((url, index) => (
<tr className='url-item'>
<UrlItem key={index + url.slug} url={url} />
</tr>
))}
</tbody>
</table>
);
}
};
export default UrlsList;
|
/**
* Created by Ethan on 4/18/2015.
*/
//
//Program : Collapse
//Author : Ethan Shimooka
//
var background_load = false;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
canvas.width = 600;
canvas.height = 800;
document.body.appendChild(canvas);
//load assets
var background_asset = new Image();
background_asset.onload = function () {
background_load = true;
};
background_asset.src = "assets/bg.png";
//taken Grid constructor of arbitrary size
Array.matrix = function (m, n) {
var a, i, j, mat = [];
for (i = 0; i < m; i++) {
a = [];
for (j = 0; j < n; j++) {
a[j] = 0;
}
mat[i] = a;
}
return mat;
};
//Game Object container.
//
var popStack = [];
var Game = {};
Game.CELL_SIZE = 30; //size of grid
Game.X = 600; //size of board (x)
Game.Y = 600; //size of board (y)
Game.WIDTH = Game.X / Game.CELL_SIZE; // number of blocks wide
Game.HEIGHT = Game.Y / Game.CELL_SIZE; //number of blocks high
Game.RED = 0;
Game.BLUE = 1;
Game.YELLOW = 2;
Game.POPPED = 9;
// All tile positions and color information are stored in a 2d array object, with each entry containing
// an integer representing a game color.
Game.grid = Array.matrix(Game.HEIGHT, Game.WIDTH);
// grid_populate()
// : populates grid with random integers (0,1,2) representing colors.
function grid_populate(){
for (var h = 0; h < Game.HEIGHT; h++) {
for (var w = 0; w < Game.WIDTH; w++) {
Game.grid[h][w] = Math.floor(Math.random() * 3);
}
}
}
//draw_rect ()
// Draws the Game.grid object when called.
function draw_rect(){
var color;
var grd;
for (var h = 0; h < Game.HEIGHT; h++) {
for (var w = 0; w < Game.WIDTH; w++) {
color = Game.grid[h][w];
ctx.beginPath();
if (color === 0) {
ctx.fillStyle = "red";
grd=ctx.createRadialGradient(0,0,2,90,70,1000);
grd.addColorStop(0," #D0FF00");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
} else if (color === 1) {
grd=ctx.createRadialGradient(300,300,2,90,70,1000);
grd.addColorStop(0," #FF00BB");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
}else if (color === 9){
ctx.fillStyle = "black";
} else {
grd=ctx.createRadialGradient(600,600,2,90,70,1000);
grd.addColorStop(0,"#4400FF");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
}
ctx.fillRect(w * Game.CELL_SIZE + 1, h * Game.CELL_SIZE + 1, Game.CELL_SIZE - 1, Game.CELL_SIZE - 1);
}
}
}
function draw_score(){
ctx.beginPath();
var my_grad=ctx.createLinearGradient(0,0,0,900);
my_grad.addColorStop(0,"#0073FF");
my_grad.addColorStop(1,"white");
ctx.fillStyle=my_grad;
ctx.fillRect(10, 610, 580, 180);
}
//function canvasOnClickHandler()
//generic clickhandaler I took from my old webGL assignments
function canvasOnClickHandler(event) {
var block = cursor_Position(event);
match_check(block, popStack);
// console.log("selected block is :" + block);
for (var h = 0; h < popStack.length; ++h) {
var y = popStack[h][0];
var x = popStack[h][1];
Game.grid[y][x] = 9;
console.log("the value of popStack is :" + popStack[h]);
}
popStack = []; //clear stack
var aud = new Audio("assets/chime.mp3"); // buffers automatically when created
aud.play();
render();
}
//function canvasOnClickHandler()
//Canvas position function
function cursor_Position(event) {
var x; var y; var block;
if (event.pageX || event.pageY) {
x = event.pageX;
y = event.pageY;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
block = [Math.floor((y - 4) / Game.CELL_SIZE),
Math.floor((x - 2) / Game.CELL_SIZE)];
return block;
}
//match_check()
// The algorithm for detecting a given selected area
//
// <from my whiteboard>
//
//For block b,
// add b to the stack.
// For each block c adjacent to b,
// if c is b's color and is not in the stack,
// recursive call on c
//
// *at least that's what I had going on in my head
function match_check(block) {
var recFlag;
var blockcurr = [0,0];
if ( Game.grid[block[0]][block[1]]) { //check that block exists
popStack.push([block[0],block[1]]); //add block b to stack
if (Game.grid[block[0]][block[1]] === Game.grid[block[0]][(block[1] + 1)]) { //check if right block matches
blockcurr = [block[0], (block[1] + 1)];
recFlag = coord_search(blockcurr);
console.log("the right value is: " + blockcurr);
console.log("the flag is: " + recFlag);
if (recFlag < 0) {
match_check(blockcurr);
}
}
if (Game.grid[block[0]][block[1]] === Game.grid[block[0]][(block[1] - 1)]) { //check if left block matches
blockcurr = [block[0] ,(block[1] - 1)];
recFlag = coord_search(blockcurr);
console.log("the left value is: " + blockcurr);
if (recFlag < 0) {
match_check(blockcurr);
}
}
if (Game.grid[block[0]][block[1]] === Game.grid[(block[0] + 1)][block[1]]) { //check if top block matches
blockcurr = [(block[0] + 1), block[1]];
recFlag = coord_search(blockcurr);
console.log("the top value is: " + blockcurr);
if (recFlag < 0) {
match_check(blockcurr);
}
}
if (Game.grid[block[0]][block[1]] === Game.grid[(block[0] - 1)][block[1]]) { //check if bottom block matches
blockcurr = [(block[0] - 1), block[1]];
recFlag = coord_search(blockcurr);
console.log("the bottom value is: " + blockcurr);
if (recFlag < 0) {
match_check(blockcurr);
}
}
}
}
function coord_search(block){
for (var i = 0;i < popStack.length;++i){
if ((block[0] === popStack[i][0]) && (block[1] === popStack[i][1]))
console.log("the popstack value is: " + popStack[i][0]);
return 1;
}
return -1
}
//update()
//Function to observe what squares have been marked for removal and adjust rows.
//brings down and inserts new random colored block.
function update() {
for (var h = 0; h < Game.HEIGHT; h++) {
for (var w = 0; w < Game.WIDTH; w++) {
if (Game.grid[h][w] === 9) {
for (var i = h;i > 0;i--){
Game.grid[i][w] = Game.grid[i - 1][w];
}
Game.grid[0][w] = Math.floor(Math.random() * 3);
}
}
}
}
//load ()
//any onetime operations can be put here
function load () {
grid_populate();
canvas.addEventListener("click", canvasOnClickHandler, false);
}
// main()
// main game loop
function main (){
update();
render();
requestAnimationFrame(main);
}
//render()
function render () {
if (background_load) {
ctx.drawImage(background_asset, 0, 0);
}
draw_rect();
draw_score();
}
load();
main();
|
$(function () {
$(".detalhes").click(function () {
//Recuperar o valor do campo
var cod_cip = $("input[type=hidden][name=cod_cip]").val();
//console.log('this', this)
var cod_cip = $(this).attr('data-cip');
console.log("cod cip", cod_cip);
//Verificar se há algo digitado
if (cod_cip != '') {
var dados = {
cod_cip: cod_cip
}
$.post('../controle/detalhes_cip.php', dados, function (retorna) {
//Mostra dentro da ul os resultado obtidos
//http://localhost/poticorp/Sistema-Corporativo/src/controle/detalhes_funcionario.php
$(".modal-body").html(retorna);
});
}else{
alert('veio vazio');
}
});
});
|
var SlideBase = require('./lib/slideBase');
SlideBase.startSlide();
process.on('uncaughtException', function(err){
console.log("uncoughtException: " + err);
});
|
class APIFilters{
constructor(query,queryStr){
this.query = query;
this.queryStr = queryStr;
}
filter(){
const queryCopy = {...this.queryStr};
//Remove fields from the query
const removeFields = ['sort','fields','q','limit','page'];
removeFields.forEach(el=> delete queryCopy[el]);
//Advance filter using lt,lte,gt,gte
let queryStr = JSON.stringify(queryCopy);
queryStr = queryStr.replace(/\b(gt|gte|lt|lte|in)\b/g,match => `$${match}`);
this.query = this.query.find(JSON.parse(queryStr));
return this;
}
sort(){
if(this.queryStr.sort){
const sortBy = this.queryStr.sort.split(',').join(' ');
this.query = this.query.sort(sortBy);
}else{
this.query=this.query.sort('-postingDate');
}
return this;
}
limitFields(){
if(this.queryStr.fields){
const fields = this.queryStr.fields.split(',').join(' ');
this.query = this.query.select(fields);
}else{
this.query=this.query.select('-__v');
}
return this;
}
searchByQuery(){
if(this.queryStr.q){
const qu = this.queryStr.q.split('-').join(' ');
this.query= this.query.find({$text: {$search: "\""+ qu +"\""}});
}
return this;
}
pagination(){
const page = parseInt(this.queryStr.page,10)||1;
const limit = parseInt(this.queryStr.limit,10) || 10;
const skipResults = (page-1)*limit;
this.query=this.query.skip(skipResults).limit(limit);
return this;
}
}
module.exports = APIFilters;
|
import { makeStyles } from '@material-ui/core/styles';
export default makeStyles((theme) => ({
container: {
display: 'flex',
flexDirection: 'column',
},
title: {
marginBottom: 20,
},
tools: {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
margin: 40,
marginBottom: 10,
marginLeft: 85,
width: 370,
[theme.breakpoints.down('md')]: {
width: 350,
},
[theme.breakpoints.down('sm')]: {
margin: 'auto',
marginTop: 20,
marginBottom: 20,
width: '100%',
justifyContent: 'space-evenly',
},
},
paper: {
width: '70%',
padding: 20,
margin: 'auto',
[theme.breakpoints.down('sm')]: {
width: '100vw',
marginLeft: -15,
},
},
progress: {
margin: 'auto',
zIndex: theme.zIndex.drawer + 1,
},
}));
|
var app;
(() => {
'use strict';
app = angular.module('app.weather', ['ngAnimate', 'chart.js']);
})();
|
var http = require("https");
var addr = process.argv[2];
http.get(addr, function(res) {
res.pipe(new MyStream(function(data) {
console.log(data.length);
console.log(data);
}));
});
function MyStream(callback) {
var data = "";
var stream = new require("stream").Writable();
stream._write = function(chunk, encoding, cb) {
data += chunk.toString();
if (cb) {
cb();
}
};
stream.on("finish", function() {
if (callback) {
callback(data);
}
});
return stream;
}
|
import Http from "./http.js";
import {ServerLink} from "./serverLink.js";
export default class RenderQuestionList {
renderQuestionList(user){
const serverLink = new ServerLink();
const http = new Http(serverLink.link);
const innerQuestionList = document.querySelector('#innerForQuestions');
innerQuestionList.innerHTML = '';
let questionList = user.support;
for (const questionListElement of questionList) {
let responseText = '';
if (questionListElement.status === 'false'){
responseText = `
<span class="h5 text-muted"><span class="badge-danger badge" style="border-radius: 50%; height: 1rem; width: 1rem"> </span> На ваш вопрос ответят в течение 8 часов. Пожалуйста, проверьте ответ позже</span>
`
} else
{
responseText = `
<span class="h5"><span class="badge-success badge" style="border-radius: 50%; height: 1rem; width: 1rem"> </span> ${questionListElement.status}</span>
`
}
const questionItem = document.createElement('div');
questionItem.innerHTML = `
<div class="row fadeIn wow animated" >
<div class="col-12 ">
<hr>
</div>
<label class="col-sm-4 h6 text-muted account-label">Тема обращения</label>
<div class="col-sm-8">
<label class="h5 text-uppercase">${questionListElement.theme}</label>
</div>
<label class="col-sm-4 h6 text-muted account-label">Описание проблемы</label>
<div class="col-sm-8">
<label class="h5">${questionListElement.question}</label>
</div>
<label class="col-sm-4 h6 text-muted account-label">Ответ от поддержки:</label>
<div class="col-sm-8">
<label class="h5">${responseText}</label>
</div>
<div class="col-sm-4 h6 text-muted account-label"><button class="btn-outline-dark btn btn-sm" id="deleteQuestion" type="button">Удалить обращение</button></div>
</div>
`;
const deleteButtonEl = questionItem.querySelector('#deleteQuestion');
const deleteButtonListener = async () => {
for (const question of questionList) {
if (question.theme === questionListElement.theme && question.question === questionListElement.question && question.status === questionListElement.status){
user.support.splice(questionList.indexOf(question), 1);
let timetableUpdate = await http.timetableUpdate(user);
let _resultUpdateFlag = '';
await timetableUpdate.json().then(async (data) => {
_resultUpdateFlag = data;
await console.log(data);
this.renderQuestionList(user);
});
}
}
console.log(questionList);
};
deleteButtonEl.addEventListener('click', deleteButtonListener);
innerQuestionList.appendChild(questionItem);
}
}
}
|
export const scrollById = (id) => {
document.getElementById(id).scrollIntoView(true);
};
|
$('document').ready(function(){
var BASE_URL = $('#baseurl').val();
$('#btnRsubmit').on('click', function(){
var operationregis = $("#operationregis").val();
if($('#frm_register').valid()){
swal({
title: "Are you sure?",
text: "Save this as new user?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, save it!",
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
$.ajax({
"url" : BASE_URL + '/admin/insertuser',
type : 'post',
data : {
_token : $('[name="_token"]').val(),
idregis : $("#idregis").val(), // id if Edit : no id if add
firstname : $("#firstname").val(),
lastname : $("#lastname").val(),
email : $("#email").val(),
contact : $("#contact").val(),
address : $("#address").val(),
user_type : $("#user_type").val(),
password : $("#password").val(),
operation : operationregis
},
success : function(data){
var message = operationregis == 1 ? "Updated" : "Saved";
swal("Success!", "Successfully " + message + "!", "success");
$('button.confirm').on('click',function(){
$('#registerModal').modal('hide');
location.reload();
});
}
});
} else {
swal("Cancelled", "Not saved", "error");
}
});
}else{
// alert('invalid');
console.log('form invalid');
}
});
$('#frm_register').validate({
rules : {
'firstname' : 'required',
'lastname' : 'required',
'contact' : {
number: true,
required : true
},
'address' : 'required',
'email' : 'required',
'password' : 'required',
'confpassword' : {
equalTo : '#password'
}
}
});
$('.close_modal').on('click',function(){
clearFormRegister();
});
$(".modal").on("hidden.bs.modal", function () {
clearFormRegister();
});
});
function clearFormRegister(){
$('label.error').css('display','none');
var form = $('.clear_form');
form[0].reset();
}
|
import React from 'react';
import styled, { keyframes } from 'styled-components';
import CoverVideo from '../CoverVideo';
import TypeWriterText from '../TypeWriterText';
import RoundTextBlack from '../../assets/Rounded-Text-Black.png';
const Section = styled.section`
min-height: ${props => `calc(100vh - ${props.theme.navHeight})` };
width: 100vw;
position: relative;
background-color: ${props => props.theme.body};
`
const Container = styled.div`
width: 75%;
min-height: 80vh;
margin: 0 auto;
/* background-color: lightblue; */
display: flex;
justify-content: center;
align-items: center;
@media (max-width: 64em) {
width: 85%;
}
@media (max-width: 48em) {
flex-direction: column-reverse;
width: 100%;
&>*:first-child{
width: 100%;
margin-top: 2rem;
}
}
`
const Box = styled.div`
width: 50%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`
const rotate = keyframes`
100%{
transform: rotate(1turn);
}
`
const Round = styled.div`
position: absolute;
bottom: 2rem;
right: 90%;
width: 6rem;
height: 6rem;
border: 1px solid ${props => props.theme.text};
border-radius: 50%;
img{
width: 100%;
height: auto;
animation: ${rotate} 6s linear infinite reverse ;
}
@media (max-width: 64em) {
width: 4rem;
height: 4rem;
left: none;
right: 2rem;
bottom: 100%;
}
@media (max-width: 48em) {
right: 1rem;
}
`
const Circle = styled.span`
width: 3rem;
height: 3rem;
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: ${props => props.theme.text};
color: ${props => props.theme.body};
font-size:${props => props.theme.fontxl};
@media (max-width: 64em) {
width: 2rem;
height: 2rem;
font-size:${props => props.theme.fontlg};
}
`
const Home = () => {
return (
<Section>
<Container>
<Box> <TypeWriterText /> </Box>
<Box><CoverVideo /></Box>
<Round>
<Circle>
↓
</Circle>
<img src={RoundTextBlack} alt="NFT" />
</Round>
</Container>
</Section>
)
}
export default Home;
|
export const AUTH_USER_SIGN_IN_SUCCESSFUL = "AUTH_USER_SIGN_IN_SUCCESSFUL";
export const AUTH_USER_LOGOUT = "AUTH_USER_LOGOUT";
|
import React from 'react';
import { shallow } from 'enzyme';
import '../../../../configurations/setupTests';
import TodoItem from './TodoItem';
it('renders TodoItem without crashing', () => {
shallow(<TodoItem />);
});
|
//import { API_URL } from './config.js';
import { TIMEOUT_SEC } from './config.js';
const timeout = function (sec) {
return new Promise(function (_, reject) {
setTimeout(function () {
reject(new Error(`Request took too long! Timeout after ${sec} second`));
}, sec * 1000);
});
};
export const getJSON = async function(url){
try {
const response = await Promise.race([ timeout(TIMEOUT_SEC), fetch(url)]) ;
const data = await response.json();
if (!response.ok) throw new Error(`${data.message} (${response.status})`);
return data;
} catch (error) {
console.error(`x*X*X*x ${error} x*X*X*x`);
throw error;
}
}
|
var searchData=
[
['framestructtok4a',['FrameStructToK4A',['../namespacemoetsi_1_1ssp.html#aa91f7040cdd17f24ad6760aa1bdb428d',1,'moetsi::ssp']]],
['framestructtomat',['FrameStructToMat',['../namespacemoetsi_1_1ssp.html#ac87377cef5da79f1a9cf7a4acdc42af6',1,'moetsi::ssp']]]
];
|
(function() {
'use strict';
angular
.module('EmailApp')
.controller('EmailCtrl', EmailCtrl)
function EmailCtrl() {
var vm = this;
this.title = "Loading...";
}
})();
|
import _ from 'underscore';
import * as types from 'robScoreCleanup/constants';
import { deepCopy } from 'shared/utils';
const defaultState = {
isFetching: false,
isLoaded: false,
items: [],
visibleItemIds: [],
updateIds: [],
editMetric: {
key: 'metric',
values:[
{
id: 0,
riskofbias_id: 0,
score: 10,
score_description: 'Probably high risk of bias',
score_shade: '#FFCC00',
score_symbol: '-',
notes: 'This will change to reflect the first selected metric.',
metric: {
id: 0,
name: '',
description: '',
},
author: {
full_name: '',
},
},
],
},
};
function items(state=defaultState, action) {
let list, list2, list3, intersection, index;
switch(action.type){
case types.REQUEST_STUDY_SCORES:
return Object.assign({}, state, {
isFetching: true,
isLoaded: false,
});
case types.RECEIVE_STUDY_SCORES:
return Object.assign({}, state, {
isFetching: false,
isLoaded: true,
items: action.items,
updateIds: [],
});
case types.CLEAR_STUDY_SCORES:
return Object.assign({}, state, {
isLoaded: false,
items: [],
updateIds: [],
});
case types.CHECK_SCORE_FOR_UPDATE:
index = state.updateIds.indexOf(action.id);
if (index >= 0){
list = [
...state.updateIds.slice(0, index),
...state.updateIds.slice(index + 1),
];
} else {
list = [
...state.updateIds,
action.id,
];
}
return Object.assign({}, state, {
updateIds: list,
});
case types.UPDATE_VISIBLE_ITEMS:
// when the items, selected scores, or select study type change, we need to make sure
// the following:
// 1) `visibleItems` is the intersection of `items`, `selectedScores`, and 'selectedStudyTypes'
// 2) `updateIds` is subset of `visibleItems`
// visibleItems: selectedScores
list = (action.selectedScores === null || action.selectedScores.length === 0)?
_.pluck(state.items, 'id'):
state.items.filter((d) => _.contains(action.selectedScores, d.score))
.map((d)=>d.id);
// visibleItems: selectedStudyTypes
list2 = (action.selectedStudyTypes === null || action.selectedStudyTypes.length === 0)?
_.pluck(state.items, 'id'):
state.items.filter((d) => _.intersection(action.selectedStudyTypes, d.study_types).length !== 0)
.map((d)=>d.id);
intersection = _.intersection(list, list2);
// updateIds
list3 = state.updateIds.filter((d) => _.contains(intersection, d));
return Object.assign({}, state, {
visibleItemIds: intersection,
updateIds: list3,
});
case types.TOGGLE_CHECK_VISIBLE_SCORES:
list = (state.updateIds.length === state.visibleItemIds.length)?
[]:
deepCopy(state.visibleItemIds);
return Object.assign({}, state, {
updateIds: list,
});
case types.UPDATE_EDIT_METRIC:
return Object.assign({}, state, {
editMetric: action.editMetric,
});
case types.PATCH_ITEMS:
let ids = action.patch.ids,
patch = _.omit(action.patch, 'ids'),
items = state.items;
_.map(ids, (id) => {
let index = state.items.indexOf(
_.findWhere(state.items, {id})
);
if (index >= 0){
items = [
...items.slice(0, index),
Object.assign({}, items[index], {...patch, id}),
...items.slice(index + 1),
];
} else {
items = [
...items,
Object.assign({}, items[index], patch),
];
}
});
return Object.assign({}, state, { items, });
default:
return state;
}
}
export default items;
|
(function () {
'use strict';
angular
.module('StationCreator')
.directive('inputCodeConfig', InputCodeEditor);
InputCodeEditor.$inject = [
'$log', '$translate',
'RallyService', 'UtilityService'
];
function InputCodeEditor(
$log, $translate,
RallyService, util
){
return {
restrict: 'E',
template:
'<div>' +
'<mbl-input-code data-verifier="{{verifier}}" data-success="say:{{success}}" data-error="say:{{error}}"></mbl-input-code>' +
'<div class="config-part">' +
'<md-input-container>' +
'<input type="text" data-ng-model="verifier" placeholder="{{ \'VERIFIER\' | translate}}">' +
'</md-input-container>' +
'<action-selector data-opts="ctrl.actionOpts" data-selection="success" data-name="SUCCESS_ACTION"></action-selector>' +
'<action-selector data-opts="ctrl.actionOpts" data-selection="error" data-name="ERROR_ACTION"></action-selector>' +
'</div>' +
'</div>',
scope: {
verifier: '=',
success: '=',
error: '=',
id: '='
},
link: function($scope, $element, $attrs, ctrl){
if ( ! $scope.id ) {
$scope.id = util.getGUID();
}
},
controller: InputCodeEditorController,
controllerAs: 'ctrl'
};
function InputCodeEditorController($scope, $element, $attrs){
var ctrl = this;
ctrl.actionOpts = RallyService.getActions();
}
}
})();
|
const { h } = require('hyperapp')
import FormInput from './FormInput.js'
import FormDateInput from './FormDateInput.js'
const PersonForm = module.exports = ({ person, actions }) => {
return <form>
<FormInput label={'Όνομα'} value={person.name} action={(x)=>actions.updateForm({object: 'person', field: 'name', value: x})} />
<FormInput label={'Φύλο'} value={person.gender} action={(x)=>actions.updateForm({object: 'person', field: 'gender', value: x})} />
<FormInput label={'Έτος γέννησης'} value={person.birth_year} action={(x)=>actions.updateForm({object: 'person', field: 'birth_year', value: x})} />
<FormDateInput label={'Έτος γέννησης'} value={person.created} action={(x)=>actions.updateForm({object: 'person', field: 'birth_year', value: x})} />
<td><button type='button' class='btn btn-block' onclick={()=>{
//console.log(person.url)
let id = person.url.match(/\/(\d+)\/$/)[1]
//console.log(id)
actions.savePerson(id)
}
}
>Save</button></td>
<td><button type='button' class='btn btn-block btn-primary' onclick={()=>actions.hideModal()}>Cancel</button></td>
</form>
}
|
const common = require('./webpack.common.js');
const merge = require('webpack-merge');
module.exports = merge(common, {
devServer: {
openPage: 'index.html',
host: 'localhost',
port: 4407,
publicPath: '/',
hot: true
}
});
|
import React, {useState} from 'react';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import axios from 'axios';
import moment from 'moment';
import { useAlert } from 'react-alert'
const TimePreferences = ({timesAvailable, email, handleShowAlert}) => {
const alert = useAlert()
const [state, setState] = useState({
"01": false, "02": false, "03": false, "04": false,
"05": false, "06": false, "07": false, "08": false,
"09": false, "10": false, "11": false, "12": false,
"13": false, "14": false, "15": false, "16": false,
"17": false, "18": false, "19": false, "20": false,
"21": false, "22": false, "23": false, "24": false
});
const handleChange = name => e => {
let newTimesAvailable = timesAvailable;
if (e.target.checked === true) {
newTimesAvailable.push(name)
} else {
let index = timesAvailable.indexOf(name)
newTimesAvailable.splice(index, 1)
}
saveTimes(newTimesAvailable)
setState({ ...state, [name]: e.target.checked });
};
const saveTimes = async (timesAvailable) => {
const response = await axios.put('api/account/timesAvailable', {
timesAvailable, email
})
const msg = response.data
alert.show(msg)
}
const renderCheckboxes = () => {
let newState = state;
const sortedCheckboxes = Object.keys(state).sort((a, b) => {
return parseInt(a) - parseInt(b);
});
const checkBoxes = sortedCheckboxes.map((key, i) => {
if (timesAvailable && timesAvailable.includes(key)) {
newState[key] = true
} else {
newState[key] = false
}
return <FormControlLabel
key={i}
style={{ margin: 0, textAlign: 'center' }}
control={
<Checkbox checked={state[key]} onChange={handleChange(key)} value={key} color="primary" />
}
label={moment(`${key}:00`, 'HH:mm').format('h:mma')}
/>
})
return checkBoxes;
}
return (
<div style={{ textAlign: 'center', margin: 10, border: '2px solid black'}}>
<h6>Times Available</h6>
<FormGroup style={{ alignItems: 'center' }} row>
{renderCheckboxes()}
</FormGroup>
</div >
)
}
export default TimePreferences;
|
var mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose"),
bcrypt = require("bcrypt-nodejs");
var UserSchema = new mongoose.Schema({
username: { type: String, unique: true, required:true },
email: { type: String, unique: true, required:true },
password: String,
bio: { type: String, deafult: ""},
avatar: {type: String, default:"https://s3-eu-west-1.amazonaws.com/al-tech-avatars/picture-default.png"},
createdAt: {type: Date, default: Date.now},
resetPasswordToken: String,
resetPasswordExpires: Date,
verificationToken: String,
verified: {type: Boolean, default: false},
isAdmin: {type: Boolean, default: false},
isModerator: {type: Boolean, default: false}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User",UserSchema);
|
import background from '../map.png'
export default function Home() {
return (
<>
<div class="container">
<img src={background} alt="bg" class="bg"></img>
</div>
</>
)
}
|
const socket = io();
const titulo = document.getElementById('titulo');
const circulo = document.getElementById('circulo');
const textoTurno = document.getElementById('textoTurno');
// Para usuario
const botonEnviar = document.getElementById('botonEnviar');
const inputUsuario = document.getElementById('inputUsuario');
const nombreJugador = document.getElementById('nombreJugador');
const esperaUsuario = document.getElementById('esperaUsuario');
// Esperar Usuario
socket.on('usuarioConectado', msg => {
inputUsuario.style.pointerEvents = "auto";
botonEnviar.style.pointerEvents = "auto";
esperaUsuario.style.color = "green";
esperaUsuario.innerText = "Usuario encontrado!";
})
botonEnviar.addEventListener('click', function clicks(){
jugadorLocal.nombre = inputUsuario.value;
inputUsuario.value = "";
jugadores.push(jugadorLocal);
socket.emit('recibirUsuario', JSON.stringify(jugadorLocal));
circulo.style.display = "block";
textoTurno.style.display = "block";
if(jugadorLocal.nombre == jugadores[0].nombre)
{
textoTurno.innerText = `Es tu turno ${jugadorLocal.nombre}`;
}
else
{
textoTurno.innerText = `Espera a que juegue ${jugadorOnline.nombre}`;
circulo.style.pointerEvents = "none";
}
nombreJugador.style.display = "none";
botonEnviar.removeEventListener('click', clicks);
})
// si [0] entonces jugador 1, si [1] entonces jugador 2
let jugadores = [];
let jugadorLocal = {
nombre: ""
};
let jugadorOnline = {
nombre: ""
};
// Recibe usuario
socket.on('enviarUsuarios', msg => {
//console.log(msg);
jugadorOnline = JSON.parse(msg);
jugadores.push(jugadorOnline);
inputUsuario.style.pointerEvents = "auto";
botonEnviar.style.pointerEvents = "auto";
esperaUsuario.style.color = "green";
esperaUsuario.innerText = "Usuario encontrado!";
})
let turno = true;
circulo.addEventListener('click', function cambioColor(){
if(turno){
circulo.style.backgroundColor = "red";
turno = false;
}else{
circulo.style.backgroundColor = "blue";
turno = true;
}
socket.emit('clickCirculo', "true")
textoTurno.innerText = `Espera a que juegue ${jugadorOnline.nombre}`;
circulo.style.pointerEvents = "none";
})
socket.on('datoTurno', msg => {
if(turno){
circulo.style.backgroundColor = "red";
turno = false;
}else{
circulo.style.backgroundColor = "blue";
turno = true;
}
textoTurno.innerText = `Es tu turno ${jugadorLocal.nombre}`
circulo.style.pointerEvents = "auto";
})
|
export const isPollVoted = (optionOne, optionTwo, username) =>
optionOne?.votes?.includes(username) || optionTwo?.votes?.includes(username);
export const calcPercentage = (optionOne, optionTwo, isOptionOne = true) => {
const optionOneVotesCont = optionOne?.votes?.length || 0;
const optionTwoVotesCont = optionTwo?.votes?.length || 0;
const totalVotesCount = optionOneVotesCont + optionTwoVotesCont;
const optionToCalc = isOptionOne ? optionOneVotesCont : optionTwoVotesCont;
return `${(Math.ceil((optionToCalc / totalVotesCount) * 10000) / 100).toFixed(
0
)}%`;
};
|
newGameButton = document.getElementById('newGame2');
newGameButton.addEventListener('click', newGame2);
newGameButton = document.getElementById('newGame3');
newGameButton.addEventListener('click', newGame3);
newGameButton = document.getElementById('newGame4');
newGameButton.addEventListener('click', newGame4);
function resetHandPile() {
const hands = document.getElementById('hands');
const pile = document.getElementById('pile');
hands.innerHTML = '';
pile.innerHTML = '';
}
function newGame2() {
resetHandPile();
const game = new Game ( [new Player('Player1', 100000), new Player('Player2', 100000)] );
// return game.playRound();
}
function newGame3() {
resetHandPile();
const game = new Game ( [new Player('Player1', 100000), new Player('Player2', 100000), new Player('Player3', 100000)] );
// return game.playRound();
}
function newGame4() {
resetHandPile();
const game = new Game ( [new Player('Player1', 100000), new Player('Player2', 100000), new Player('Player3', 100000), new Player('Player4', 100000)] );
// return game.playRound();
}
|
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const path = require("path");
const userDatabase = require("../db/modal");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mongoose.connect("mongodb://localhost/users", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", (error) => console.error(error));
db.once("open", () => console.log("Connected to database"));
const client_home = "http://localhost:5500/public";
app.get("/users", async (req, res) => {
try {
const users = await userDatabase.find();
res.json(users);
} catch (error) {
res.status(500);
res.json({ message: error.message });
}
});
app.post("/login-user", async (req, res) => {
let user;
try {
user = await userDatabase.findOne({ username: req.body.name }).exec();
console.log(user.buckets);
if (user === null) {
return res.status(400).send("Cannot find user.");
}
try {
const password = req.body.password;
if (password !== user.password) {
throw new Error();
} else {
// set cookies.
res.cookie("username", user.username);
res.status(500).redirect(client_home);
}
} catch (error) {
res
.status(400)
.send("Sorry wrong password !\n{message:" + error.message + "}");
}
} catch (error) {
return res.status(500).json({ message: error.message });
}
});
app.post("/register-user", async (req, res) => {
const user = new userDatabase({
username: req.body.name,
password: req.body.password,
});
try {
const newUser = await user.save();
res.status(201);
res.json(newUser);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
app.post("/logout", (req, res) => {
try {
const cookie_array = req.headers.cookie.split("; ");
cookie_array.forEach((element) => {
if (element.split("=")[0] === "username") {
res.clearCookie("username");
res.status(500).redirect(client_home);
return;
}
});
} catch (error) {
res.status(400).json({ message: error.message }).send("Unable to logout");
}
});
app.post("/submit-bucket", async (req, res) => {
const bucket = {
bucketname: req.body.bucketname,
bucketdata: req.body.bucketdata,
};
try {
const cookie_array = req.headers.cookie.split("; ");
console.log(cookie_array);
let user;
cookie_array.forEach(async (element) => {
if (element.split("=")[0] === "username") {
user = await userDatabase.findOne({ username: element.split("=")[1] }).exec();
var current_buckets = await user.buckets;
current_buckets.push(bucket)
console.log(user);
try {
userDatabase.findOneAndUpdate(
{ username: element.split("=")[1] },
{ buckets: current_buckets },
(err) => {
if (err) {
throw err;
} else {
res.status(500).send("Bucket updated");
}
}
);
} catch (error) {
res.status(400).json({ message: error.message });
}
}
});
} catch (error) {
res.status(400).json({ message: error.message });
}
});
app.listen(3000, () => {
console.log("Running");
});
|
// embedded
//import CodeMirror from 'codemirror';
jQuery(function ($) {
$('.sql-editor').each(function (i, area) {
CodeMirror.fromTextArea(area, {
lineNumbers: true,
mode: "text/x-plsql",
indentUnit: 4,
smartIndent: true,
// closebrackets addon
autoCloseBrackets: true,
// matchbrackets addon
matchBrackets: true
});
});
});
|
import styled from 'styled-components';
export const HeaderWrapper = styled.div`
background-color: rgb(80, 80, 80);
color: white;
padding: 15px;
`
export const HeaderContainer = styled.div`
align-items: center;
display: flex;
`
export const HeaderLogo = styled.img`
height: 4em;
`
export const HeaderNavItems = styled.div`
margin-left: 1.5em;
& > a {
color: white;
opacity: 0.8;
text-decoration: none;
&.active {
opacity: 0.99;
}
&:hover {
opacity: 0.99;
}
}
`
|
import React from 'react';
import {
View,
StatusBar,
Text,
StyleSheet,
} from 'react-native';
import WelcomeScreen from './app/screens/WelcomeScreen';
import ViewImageScreen from './app/screens/ViewImageScreen';
import Card from './app/components/Card';
import ListingDetailsScreen from './app/screens/ListingDetailsScreen';
export default function App() {
return (
<>
<StatusBar hidden />
<ListingDetailsScreen />
</>
);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.