text
stringlengths 7
3.69M
|
|---|
import React from 'react';
import './PositionSelector.scss';
export default function PositionSelector({ transform, hoverClass }) {
return (
<svg className={`position-selector ${hoverClass}`}>
<g>
<rect width="8" height="8" transform={transform} />
</g>
</svg>
);
}
|
//index.js
//获取应用实例
const app = getApp()
const {
connect
} = require('../../libs/wechat-weapp-redux.js')
import {
getFlightsBanner,
changeCabin,
changeTabs,
changeCalendarTime,
changePersonnel,
exchangeDeparture,
addFlight,
deleteFlight,
getFlightPollingSession,
getFlightSearchData,
getCityByCode
} from '../../actions/flights.js'
import {
changeCity,
getHotCitys
} from '../../actions/flightCitys.js'
import {
getAddressByLocation,
getCurrentCity
} from '../../actions/myInfo.js'
import {
passengerCalculation,
getLocation,
convertTimeToStr,
getTimeStamp
} from '../../utils/util.js'
import {
getflightsCalendar
} from '../../actions/flightCalendar.js'
const pageConfig = {
data: {
showPersonnel: false
},
onShow() {
},
onLoad() {
//获取机票banner
const {
flightsHome,
myInfo,
flightCitys
} = this.data;
if (flightsHome.banner.length <= 0) {
this.dispatch(getFlightsBanner())
}
//获取热门城市 (搜索机票需要先掉取热门城市接口)
console.dir(flightCitys.hot)
if (flightCitys.hot.length <= 0) {
this.dispatch(getHotCitys({
lang: myInfo.lang,
timestamp: getTimeStamp()
}))
}
//获取用户当前地址
if (!myInfo.cityInfo.d) {
getLocation(res => {
getAddressByLocation({
lang: 'ZH',
largeCityOnly: true,
lat: res.latitude,
lgt: res.longitude,
timestamp: getTimeStamp(),
type: "AIRPORT"
}).then(res => {
const {
ct
} = flightsHome.strokes[0].departure
// 如果定位城市没变不需要在请求城市详情
if (res.resultCode === 200 && res.name !== ct) {
getCityByCode({
code: res.code,
lang: myInfo.lang
}).then(res => {
this.dispatch(getCurrentCity(res))
let data = Object.assign({}, res.result[0], {
type: 'departure',
index: 0
})
this.dispatch(changeCity(data))
})
}
})
})
}
},
carouselClick(item) {
const {
detail
} = item
wx.navigateTo({
url: `/pages/webView/index?src=${detail.link}`,
})
},
//出发城市
clickCity(e) {
const {
index,
type
} = e.currentTarget.dataset;
wx.navigateTo({
url: `/pages/flightCitys/index?index=${index}&type=${type}`
})
},
listCalenderClick(e) {
const {
index
} = e.currentTarget.dataset;
const {
strokes,
selectIndex,
cabin
} = this.data.flightsHome;
const {
myInfo
} = this.data;
wx.navigateTo({
url: `/pages/flightCalendar/index?calendarIndex=${index}`
})
this.dispatch(getflightsCalendar({
currency: myInfo.currency.code,
current: convertTimeToStr(new Date(), 'yyyyMMdd'),
depDate: convertTimeToStr(strokes[index].departureTime.begin, 'yyyyMMdd'),
from: strokes[index].departure.c,
fromType: strokes[index].departure.t,
isDirectOnly: false,
lang: myInfo.lang,
seatClass: cabin.type,
showPrice: true,
to: strokes[index].destination.c,
toType: strokes[index].destination.t,
tripType: selectIndex === 1 ? "RT" : "OW"
}))
},
//
bindChange(e) {
const {
value
} = e.detail;
console.dir(value)
},
//点击tabs事件
onTabsClick(e) {
const {
value
} = e.detail;
this.dispatch(changeTabs(value))
},
//点击舱位
pickerCabin(e) {
const {
value
} = e.detail;
this.dispatch(changeCabin(value))
},
//机票搜索
searh() {
const {
flightsHome,
myInfo
} = this.data;
const {
strokes,
selectIndex
} = flightsHome;
let flage = false;
let v = '';
strokes.map((item, index) => {
if (selectIndex === 1) {
v = `${item.departure.c}-${item.destination.c}_${convertTimeToStr(item.departureTime.begin, 'yyyy-MM-dd')}_${convertTimeToStr(item.destinationTime.end, 'yyyy-MM-dd')}`
} else {
if (index == 0) {
v += `${item.departure.c}-${item.destination.c}_${convertTimeToStr(item.departureTime.begin, 'yyyy-MM-dd')}`
} else {
v += `;${item.departure.c}-${item.destination.c}_${convertTimeToStr(item.departureTime.begin, 'yyyy-MM-dd')}`
}
}
if (!item.departure.c || !item.destination.c) {
flage = true
}
})
if (flage) {
wx.showToast({
icon: 'none',
title: '请完善出行信息'
})
return;
}
const tripType = selectIndex === 0 ? 'OW' : selectIndex === 1 ? 'RT' : 'CT';
wx.navigateTo({
url: `/pages/timeLine/index?c=${flightsHome.cabin.type}&l=${myInfo.lang}&t=${tripType}&v=${v}&s=1`,
})
},
//显示
showPersonnelPop() {
this.setData({
showPersonnel: true
})
},
enter() {
this.setData({
showPersonnel: false
})
},
exchangeCity(e) {
const {
index
} = e.currentTarget.dataset;
this.dispatch(exchangeDeparture(index))
},
//成人
clickPerson(e) {
const {
type,
action
} = e.currentTarget.dataset;
this.dispatch(changePersonnel({
type,
action
}))
},
//增加航班
addFlight() {
this.dispatch(addFlight())
},
deleteFlight() {
this.dispatch(deleteFlight())
}
}
function mapStateToProps(state) {
const {
flightsHome
} = state;
let childMax = passengerCalculation(flightsHome.personnel.adult)
const newFlights = Object.assign({}, flightsHome, {
strokes: [flightsHome.strokes[0]]
})
return {
flightsHome: flightsHome.selectIndex === 2 ? flightsHome : newFlights,
childMax: childMax,
myInfo: state.myInfo,
flightCitys: state.flightCitys,
flightCalendar: state.flightCalendar
}
}
Page(connect(mapStateToProps)(pageConfig))
|
import _ from 'lodash';
import {isIntegerOrDecimal} from './tool';
/**
* 验证账号
* @param rule
* @param val
* @param callback
*/
const validateAccount = function (rule, val, callback) {
if (/^[a-zA-Z][a-zA-Z0-9_]{4,17}$/.test(val)) {
callback();
} else {
callback(new Error('5~18个字符,可使用大小写字母、数字、下划线,需以字母开头'));
}
};
/**
* 验证密码
* @param rule
* @param val
* @param callback
*/
const validatePassword = function (rule, val, callback) {
if (/^[a-zA-Z0-9]{6,30}$/.test(val)) {
callback();
} else {
callback(new Error('6~30个字符,可使用大小写字母、数字'));
}
};
/**
* 验证手机号码
* @param rule
* @param val
* @param callback
*/
const validatePhone = function (rule, val, callback) {
if (/^1[0-9]{10}$/.test(val)) {
callback();
} else {
callback(new Error('请输入如正确的手机号码'));
}
};
/**
* 验证手机验证码
* @param rule
* @param val
* @param callback
*/
const validatePhoneCode = function (rule, val, callback) {
if (/^\d{,6}$/.test(val)) {
callback();
} else {
callback(new Error('请输入6个数字的验证码'));
}
};
/**
* 验证只能输入数字
* @param rule
* @param val
* @param callback
*/
const validateNumber = function (rule, val, callback) {
if (/^[0-9]+$/.test(val)) {
callback();
} else {
callback(new Error('只能输入数字'));
}
};
/**
* 验证数组的是整数或者小数
* @param rule
* @param val
* @param callback
*/
const validateIntegerOrDecimal = function (rule, val, callback) {
if (isIntegerOrDecimal(val)) {
callback();
} else {
callback(new Error('只能输入整数或者小数'));
}
};
/**
* 验证只能输入字母数字
* @param rule
* @param val
* @param callback
*/
const validateLetterNumber = function (rule, val, callback) {
if (/^[A-Za-z0-9]+$/.test(val)) {
callback();
} else {
callback(new Error('只能输入字母、数字'));
}
};
/**
* 验证只能输入字母、数字、中文
* @param rule
* @param val
* @param callback
*/
const validateLetterNumberChinese = function (rule, val, callback) {
if (/^[A-Za-z0-9\u4e00-\u9fa5]+$/.test(val)) {
callback();
} else {
callback(new Error('只能输入字母、数字、中文'));
}
};
/**
* 验证只能输入_、字母、数字、中文
* @param rule
* @param val
* @param callback
*/
const validateUnderlineLetterNumberChinese = function (rule, val, callback) {
if (/^[_A-Za-z0-9\u4e00-\u9fa5]+$/.test(val)) {
callback();
} else {
callback(new Error('只能输入_、字母、数字、中文'));
}
};
/**
* 验证只能输入:中英文、数字、-、_
* @param rule
* @param val
* @param callback
*/
const validateChineseLetterNumberHrUnderline = function (rule, val, callback) {
if (/^[-_A-Za-z0-9\u4e00-\u9fa5]+$/.test(val)) {
callback();
} else {
callback(new Error('只能输入:中英文、数字、-、_'));
}
};
/**
* 验证只能输入:中文、英文、-、_
* @param rule
* @param val
* @param callback
*/
const validateChineseLetterHrUnderline = function (rule, val, callback) {
if (/^[-_A-Za-z\u4e00-\u9fa5]+$/.test(val)) {
callback();
} else {
callback(new Error('只能输入:中文、英文、-、_'));
}
};
/**
* 验证只能输入:中英文、横线和空格,需以中英文开头和结尾
* @param rule
* @param val
* @param callback
*/
const validateChineseLetterHrSpace = function (rule, val, callback) {
if (/^[A-Za-z\u4e00-\u9fa5]+[-\sA-Za-z\u4e00-\u9fa5]*[A-Za-z\u4e00-\u9fa5]+$/.test(val)) {
callback();
} else {
callback(new Error('只能输入:中英文、横线和空格,需以中英文开头和结尾'));
}
};
/**
* 验证身份证号码
* @param rule
* @param value
* @param callback
* @return {*}
*/
const validateIdentityCard = function (rule, value, callback) {
if (value === '') {
return callback();
}
if (!/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
return callback(new Error('格式错误'));
}
callback();
};
//功能:判断IPv4地址的正则表达式:
const IPV4_REGEX = /^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/;
//功能:判断标准IPv6地址的正则表达式
const IPV6_STD_REGEX = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
//功能:判断一般情况压缩的IPv6正则表达式
const IPV6_COMPRESS_REGEX = /^((?:[0-9A-Fa-f]{1,4}(:[0-9A-Fa-f]{1,4})*)?)::((?:([0-9A-Fa-f]{1,4}:)*[0-9A-Fa-f]{1,4})?)$/;
/*由于IPv6压缩规则是必须要大于等于2个全0块才能压缩
不合法压缩 : fe80:0000:8030:49ec:1fc6:57fa:ab52:fe69
-> fe80::8030:49ec:1fc6:57fa:ab52:fe69
该不合法压缩地址直接压缩了处于第二个块的单独的一个全0块,
上述不合法地址不能通过一般情况的压缩正则表达式IPV6_COMPRESS_REGEX判断出其不合法
所以定义了如下专用于判断边界特殊压缩的正则表达式
(边界特殊压缩:开头或末尾为两个全0块,该压缩由于处于边界,且只压缩了2个全0块,不会导致':'数量变少)*/
//功能:抽取特殊的边界压缩情况
const IPV6_COMPRESS_REGEX_BORDER = /^(::(?:[0-9A-Fa-f]{1,4})(?::[0-9A-Fa-f]{1,4}){5})|((?:[0-9A-Fa-f]{1,4})(?::[0-9A-Fa-f]{1,4}){5}::)$/;
//判断是否为合法IPv4地址
const isIPv4Address = function (val) {
return IPV4_REGEX.test(val);
};
//判断是否为合法IPv6地址
const isIPv6Address = function (val) {
let NUM = 0;
for (let i = 0; i < val.length; i++) {
if (val.charAt(i) == ':') NUM++;
}
if (NUM > 7) return false;
if (IPV6_STD_REGEX.test(val)) {
return true;
}
if (NUM == 7) {
return IPV6_COMPRESS_REGEX_BORDER.test(val);
} else {
return IPV6_COMPRESS_REGEX.test(val);
}
};
/**
* 验证IP地址
* @param rule
* @param val
* @param callback
*/
const validateIp = function (rule, val, callback) {
if (isIPv4Address(val) || isIPv6Address(val)) {
callback();
} else {
callback(new Error('请输入正确的IP地址'));
}
};
/**
* vue
* 清除表单错误信息
*/
const clearError = function (filed = 'validateError') {
if (this.$data && this.$data[filed]) {
for (const key in this.$data[filed]) {
this.$data[filed][key].message = '';
}
}
};
/**
* 显示错误信息
* @param codes 错误代码
* @param filed 验证器错误对象域。默认:validateError
* 示例:
*
* validateError: {
account: {
'message':'', // 存放消息的字段
'60008': '账户名称已存在' // 60008的错误代码的错误提示消息
}
}
*
* this.showError('60008');
* this.showError([{code:'60008'}]]);
*/
const showError = function (codes = [], filed = 'validateError') {
if (this.$data && this.$data[filed]) {
const validateError = this.$data[filed];
const codeList = _.isArray(codes) ? codes : [{code: codes}];
for (const codeItem of codeList.values()) {
const {code} = codeItem;
for (const [key, value] of Object.entries(validateError)) {
if (Object.keys(value).includes(code)) {
this.$data[filed][key].message = value[code];
break;
}
}
}
}
};
/**
* 安装到 Vue 的原型
* 用时可直接:this.validate.account
* @param Vue
*/
const install = function (Vue) {
Vue.prototype.validate = {
account: validateAccount,
password: validatePassword,
phone: validatePhone,
phoneCode: validatePhoneCode,
number: validateNumber,
integerOrDecimal: validateIntegerOrDecimal,
letterNumber: validateLetterNumber,
letterNumberChinese: validateLetterNumberChinese,
underlineLetterNumberChinese: validateUnderlineLetterNumberChinese,
chineseLetterNumberHrUnderline: validateChineseLetterNumberHrUnderline,
chineseLetterHrUnderline: validateChineseLetterHrUnderline,
chineseLetterHrSpace: validateChineseLetterHrSpace,
identityCard: validateIdentityCard,
ip: validateIp
};
Vue.prototype.clearError = clearError;
Vue.prototype.showError = showError;
};
export {
validateAccount,
validatePassword,
validatePhone,
validatePhoneCode,
validateNumber,
validateIntegerOrDecimal,
validateLetterNumber,
validateLetterNumberChinese,
validateUnderlineLetterNumberChinese,
validateChineseLetterNumberHrUnderline,
validateChineseLetterHrUnderline,
validateChineseLetterHrSpace,
validateIdentityCard,
validateIp,
clearError,
showError,
install
};
export default function (Vue) {
install(Vue);
}
|
const User = require('../models/User');
const { generateError, success, asyncErrorHandler } = require('./utils/utils');
const consts = require('../const/const');
module.exports = {
follow: asyncErrorHandler(async (req, res, next) => {
const { tag } = req.params;
const { userId } = req.session;
if (tag.length > consts.TAGS_MAX_LENGTH) {
generateError(`The tag can't be longer than${consts.TAGS_MAX_LENGTH}`, 422, next);
} else {
try {
await User.findByIdAndUpdate(userId, {
$addToSet: {
tagsFollowed: tag,
},
});
success(req, res);
} catch (e) {
generateError(e, 500, next);
}
}
}),
unfollow: asyncErrorHandler(async (req, res, next) => {
const { tag } = req.params;
const { userId } = req.session;
if (tag.length > consts.TAGS_MAX_LENGTH) {
generateError(`The tag can't be longer than${consts.TAGS_MAX_LENGTH}`, 422, next);
} else {
try {
await User.findByIdAndUpdate(userId, {
$pull: {
tagsFollowed: tag,
},
});
success(req, res);
} catch (e) {
generateError(e, 500, next);
}
}
}),
};
|
function updateHits(){
httpObject = getHTTPObject();
if (httpObject != null) {
alert("HI");
//httpObject.open("GET", "http://fast.crasxit.net/hits/hits.php?echo=1", true);
httpObject.send(null);
httpObject.onreadystatechange = doHitsUpdate;
setTimeout("updateHits()",5000);
}
}
function doHitsUpdate(){
if(httpObject.readyState == 4){
document.getElementById('counter').innerHTML = httpObject.responseText;
}
}
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else return null;
}
var httpObject;
|
export const dateToExpireCard = date => {
const dateSplited = new Date(date).toDateString().split(' ');
return `${dateSplited[2]}/${dateSplited[3]}`
}
export const toMinuteAndSeconds = date => `${date.getMinutes()}:${date.getSeconds()}`;
export const toDateAndTime = date => `${new Date(date).toLocaleDateString()} ${new Date(date).toLocaleTimeString()}`;
|
import React from 'react';
import Card from './Card.js'
const CardList = (props) => {
const cardArray = props.robots.map((robot) => {
return <Card key={robot.id} {...robot} />
})
return (
<div>
{cardArray}
</div>
)
}
export default CardList;
|
const inquirer = require('inquirer')
const clear = require('clear')
const Todo = require('bindings')('db')
const colors = require('colors')
let createTaskMenu = require('./lib/new')
let editTaskMenu = require('./lib/edit')
let markTaskAsCompletedMenu = require('./lib/mark')
const taskMenuEntries = () => Todo.list().sort(t => t.completed).map(task => {
let name = task.name
let value = task
name = (task.completed)?`${name}`.strikethrough:name
disabled = task.completed
return {name, value, disabled}
})
const mainMenuView = function() {
clear()
const ACTIONS = {
'task': createTaskMenu,
'mark': markTaskAsCompletedMenu,
'exit': () => { clear(); console.log('Good Bye!') },
}
const mainMenu = () => {
let list = taskMenuEntries()
list.push(new inquirer.Separator())
list.push({value:'task', name:'New task'})
list.push({value:'mark', name:'Complete Task'})
list.push({value:'exit', name:'Exit'})
return list
}
inquirer.prompt([
{
type: 'list',
name: 'todo',
message: 'Your Tasks For Today',
pageSize: 15,
choices: mainMenu()
}
]).then(function(answers) {
let choice = answers['todo']
if(ACTIONS[ choice ] !== undefined){
ACTIONS[ choice ]()
} else {
editTaskMenu(choice)
}
})
}
markTaskAsCompletedMenu = markTaskAsCompletedMenu.bind(undefined, Todo, taskMenuEntries, mainMenuView)
createTaskMenu = createTaskMenu.bind(undefined, Todo, mainMenuView)
editTaskMenu = editTaskMenu.bind(undefined, mainMenuView)
if(Todo.list().length > 0 ) {
mainMenuView()
}else {
editTaskMenu()
}
|
// DotNetNuke® - http://www.dnnsoftware.com
//
// Copyright (c) 2002-2015, DNN Corp.
// All rights reserved.
'use strict';
define(['jquery', 'knockout', 'd3'],
function($, ko) {
var utility = null;
var viewModel = {
pageName: ko.observable(''),
moduleName: ko.observable(''),
viewCount: ko.observable('0'),
viewCountDetail: ko.observable('0'),
timeCount: ko.observable(0.0),
bounceRate: ko.observable('N/A'),
bounceRateUnits: ko.observable(''),
engageAnalyticsVisible: ko.observable(false),
engagementPercentProgress: ko.observable(''),
engagementPercent: ko.observable(0),
period: ko.observable(''),
comparativeTerm: ko.observable(''),
startDate: ko.observable(''),
endDate: ko.observable(''),
loadPageAnalytics: function (d, e) {
e.preventDefault();
$('.incontext-analytics').hide();
utility.loadPageAnalytics();
},
loadEngageModuleDashboard: function (d, e) {
e.preventDefault();
$('.incontext-analytics').hide();
utility.loadModuleDashboard(viewModel.moduleName());
}
};
var getContextData = function(cb) {
var userSettings = utility.persistent.load();
var defaultDate = utility.serializeCustomDate(new Date(new Date().toUTCString()));
if (viewModel.period() !== userSettings.period || viewModel.comparativeTerm() !== userSettings.comparativeTerm) {
viewModel.period(userSettings.period);
viewModel.comparativeTerm(userSettings.comparativeTerm);
viewModel.startDate(userSettings.startDate || defaultDate);
viewModel.endDate(userSettings.endDate || defaultDate);
utility.sf.moduleRoot = 'evoqcontentlibrary';
utility.sf.controller = 'analyticsservice';
utility.sf.getsilence('GetPageAnalyticsInContext', {
period: viewModel.period(),
comparativeTerm: viewModel.comparativeTerm(),
startDate: viewModel.startDate(),
endDate: viewModel.endDate()
},
function(data) {
if (data) {
updatePageAnalyticsModel(data, cb);
}
getContextDataEngage();
}, function() {
// failed...
getContextDataEngage();
});
} else {
if (typeof cb === 'function') cb();
}
};
var getContextDataEngage = function() {
if (viewModel.engageAnalyticsVisible()) {
var userSettings = utility.persistent.load();
var defaultDate = utility.serializeCustomDate(new Date(new Date().toUTCString()));
viewModel.period(userSettings.period);
viewModel.comparativeTerm(userSettings.comparativeTerm);
viewModel.startDate(userSettings.startDate || defaultDate);
viewModel.endDate(userSettings.endDate || defaultDate);
utility.sf.moduleRoot = 'dnncorp/cmx';
utility.sf.controller = 'analytics';
utility.sf.getsilence('GetModuleContextData', {
period: viewModel.period(),
comparativeTerm: viewModel.comparativeTerm(),
moduleName: viewModel.moduleName(),
startDate: viewModel.startDate(),
endDate: viewModel.endDate()
},
function(data) {
if (data) {
updateEngageAnalyticsModel(data);
}
}, function() {
// failed...
});
}
};
var updatePageAnalyticsModel = function(data, cb) {
viewModel.pageName(data.data.pageName || '');
viewModel.viewCount(utility.formatAbbreviateBigNumbers(data.data.totalPageViews || 0));
viewModel.viewCountDetail(utility.formatCommaSeparate(data.data.totalPageViews || 0));
viewModel.timeCount(data.data.averageTimeOnPageTotalMinutes || 0.0);
var bounceRateData = (data.data.bounceRate || '').split(' ');
if (bounceRateData.length > 0) {
viewModel.bounceRate(bounceRateData[0]);
} else {
viewModel.bounceRate('N/A');
}
if (bounceRateData.length > 1) {
viewModel.bounceRateUnits(bounceRateData[1]);
} else {
viewModel.bounceRateUnits('');
}
if (typeof cb === 'function') cb();
};
var updateEngageAnalyticsModel = function (data) {
viewModel.engagementPercent(data.engagementPercent || 0);
viewModel.engagementPercentProgress(data.percentProgress == 1 ? 'higher' : (data.percentProgress == -1 ? 'lower' : data.engagementPercent == 0 ? 'equal hidden' : 'equal'));
};
return {
init: function(wrapper, util, params, callback) {
utility = util;
viewModel.resx = utility.resx.PersonaBar;
viewModel.moduleName(params.moduleName);
if (params.showEngageStats) {
viewModel.engageAnalyticsVisible(true);
} else {
viewModel.engageAnalyticsVisible(false);
}
ko.applyBindings(viewModel, wrapper[0]);
utility.asyncParallel([
function(cb1) {
getContextData(cb1);
}
], function() {
if (typeof callback === 'function') callback();
});
},
load: function(params, callback) {
getContextData(function() {
if (typeof callback === 'function') callback();
});
}
};
});
|
import React from 'react';
import {makeStyles} from "@material-ui/core/styles";
import {connect} from 'react-redux';
import {Container} from "@material-ui/core";
import {Typography} from "@material-ui/core";
import Divider from "@material-ui/core/Divider";
import Snackbar from '@material-ui/core/Snackbar';
import SnackbarContent from '@material-ui/core/SnackbarContent';
import {Call} from "./Call";
import './CallsPage.scss';
import {CallsPageTranslation} from "../../Translations/Pages/CallsPageTranslation";
import {Performance} from "./Performance";
import {Filter} from "./Filter";
import clsx from "clsx";
const useStyles = makeStyles(theme => ({
title: {
display: "block",
textAlign: "center",
marginBottom: theme.spacing(2),
},
link: {
textDecoration: "none",
display: "block"
},
button: {
color: "white"
},
textField: {
marginBottom: theme.spacing(1)
},
wrapper: {
marginTop: theme.spacing(1),
marginLeft: theme.spacing(0.5),
marginRight: theme.spacing(0.5),
position: 'relative',
},
buttonProgress: {
position: 'absolute',
top: '50%',
left: '50%',
marginTop: -12,
marginLeft: -12,
},
buttonIcon: {
marginLeft: -8,
marginRight: -4,
},
snackbar: {
margin: theme.spacing(1),
},
snackbarContentError: {
backgroundColor: theme.palette.primary.main,
},
snackbarContentSuccess: {
backgroundColor: theme.palette.secondary.main,
},
switchLink: {
marginTop: theme.spacing(2),
textAlign: "center",
},
formContainer: {
marginTop: theme.spacing(2),
marginBottom: theme.spacing(2),
},
divider: {
marginTop: theme.spacing(6),
marginBottom: theme.spacing(6),
},
subheading: {
marginBottom: theme.spacing(2),
marginLeft: theme.spacing(1),
},
placeholder: {
marginLeft: theme.spacing(1),
},
callsRoot: {
width: "100%",
},
fulfilledText: {
color: theme.palette.primary.transparent40,
}
}));
export function CallsPageComponent(props) {
const classes = useStyles();
return (
<Container maxWidth="md" className="CallsPage">
<Filter/>
<Divider className={classes.divider}/>
<Typography variant="h6" className={classes.subheading}>
{CallsPageTranslation.acceptedCalls[props.language]}
</Typography>
<div className={classes.callsRoot}>
{props.calls.accepted.map(call => (
<Call key={call.call_id} call={call}/>
))}
{props.calls.accepted.length === 0 && (
<Typography variant="subtitle1" className={classes.placeholder}>
<em>{CallsPageTranslation.noAcceptedCalls[props.language]}</em>
</Typography>
)}
</div>
<div className={classes.divider}/>
<Typography variant="h6" className={clsx(classes.subheading, classes.fulfilledText)}>
{CallsPageTranslation.fulfilledCalls[props.language]}
</Typography>
<div className={classes.callsRoot}>
{props.calls.fulfilled.map(call => (
<Call key={call.call_id} call={call}/>
))}
{props.calls.fulfilled.length === 0 && (
<Typography variant="subtitle1" className={classes.placeholder}>
<em>{CallsPageTranslation.noFulfilledCalls[props.language]}</em>
</Typography>
)}
</div>
<Divider className={classes.divider}/>
<Performance/>
<Snackbar className={classes.snackbar}
open={props.errorMessageVisible}
anchorOrigin={{vertical: 'top', horizontal: 'center'}}>
<SnackbarContent
className={classes.snackbarContentError}
aria-describedby="message-id"
message={<span id="message-id">{props.errorMessageText}</span>}
/>
</Snackbar>
</Container>
);
}
/* Redux link -------------------------------------------------------------------- */
/* Making the RouterComponent watch the loggedIn property of the store */
const mapStateToProps = state => ({
language: state.language,
calls: state.calls,
});
const mapDispatchToProps = () => ({
});
export const CallsPage = connect(mapStateToProps, mapDispatchToProps)(CallsPageComponent);
|
import React, { useMemo, useState, useCallback, useEffect } from 'react';
import DataTable from 'react-data-table-component';
const customStyles = {
headRow: {
style: {
border: 'none',
},
},
headCells: {
style: {
color: '#202124',
fontSize: '14px',
},
},
rows: {
highlightOnHoverStyle: {
backgroundColor: 'rgb(230, 244, 244)',
borderBottomColor: '#FFFFFF',
borderRadius: '25px',
outline: '1px solid #FFFFFF',
},
},
pagination: {
style: {
border: 'none',
},
},
};
const MyDataTable = ({ data, selectedRows, setSelectedRows }) => {
useEffect(() => {
console.log('state', selectedRows);
}, [selectedRows]);
const handleChange = useCallback((state) => {
setSelectedRows(state.selectedRows);
}, []);
const columns = useMemo(
() => [
{
name: 'Name',
selector: 'name',
sortable: true,
grow: 2,
},
{
name: 'Type',
selector: 'type',
sortable: true,
},
{
name: 'Profile',
selector: 'profile',
sortable: true,
},
{
name: 'JSON API Access',
selector: 'jsonApiAccess',
sortable: true,
},
{
name: 'ADOMS',
selector: 'adoms',
sortable: true,
},
{
name: 'Trusted IPV4 Hosts',
selector: 'trustedIpv4Hosts',
sortable: true,
},
],
[]
);
return (
<DataTable
data={data}
columns={columns}
customStyles={customStyles}
onSelectedRowsChange={handleChange}
selectableRows
/>
);
};
export default MyDataTable;
|
/**
*
*/
function Rules() {
var _self = this // Important to simulate a singleton
var _instance
var _model
// var _view
//
// this.display = function() {
// return _view.display(_model)
// }
this.serialize = function() {
return this.toJSON()
}
this.createRule = function(){
var newRule = new Rule((typeof cSYS_ID !== 'undefined' ? cSYS_ID() : arguments[0] ))
_model.addRule(newRule)
return newRule
}
return function() {
if (_instance === undefined || _instance == null) {
_instance = _self // not this!!! - it returns the rule designer
_model = new RulesModel(_instance)
var keys = Object.keys(_model)
for(var n =0; n < keys.length; n++){
eval('_instance.' + keys[n] +' = _model.'+keys[n])
}
}
// _view = new RulesView(_instance)
return _instance
}()
}
function RulesModel(controller) {
var _self = this
var _controller = controller
var rules = []
this.addRule = function(rule) {
rules.push(rule)
}
this.getRules = function() {
return rules
}
this.toJSON = function() {
var tmp = []
for (var n = 0; n < rules.length; n++)
tmp.push(rules[n].toJSON())
return tmp
}
this.getInfo = function (){
var tmp = {}
for(var n =0; n < rules.length; n++){
var info = rules[n].getInfo()
tmp.push[info.ID] = info
}
return tmp
}
}
//function RulesView(controller) {
//
// var _self = this
//
// var _controller = controller
//
// this.display = function(_model) {
//
// }
//
//}
|
const orderController = require('../controllers/orderController');
var express = require('express');
var router = express.Router();
router.get('/', orderController.getOrders);
module.exports = router;
|
import { logger } from 'aries-data'; import { Writable } from 'stream';
import DropSchemaStrategy from './DropSchemaStrategy';
import AlterSchemaStrategy from './AlterSchemaStrategy';
import inferSchema from './util/inferSchema';
import knex from 'knex';
import isString from 'lodash.isstring';
import moment from 'moment';
/**
* This should get piped a highland stream split on newlines.
*/
@logger()
export default class MySQLWriteStream extends Writable {
constructor(schema, config) {
super({});
this.maxBufferLength = 1000;
this.internalBuffer = [];
this.schema = schema;
this.config = config;
this.client = null;
// Close connection after we push a null value.
this.on('finish', ::this.flushAndCloseConnection);
}
/**
* Chunk comes in as a buffer of a string of 1 json object.
* We buffer them up into an interal array, and write to the database when it reaches a given length.
*/
_write(chunk, encoding, next) {
this.setupDatabase().then(() => {
this.pushChunk(chunk);
if (this.shouldFlush()) {
return this.flush();
}
}).then(() => {
next();
}).catch((err) => {
next(err);
});
}
/**
* Creates a knex connection and sets it on this.client.
*/
async setupDatabase() {
if (!this.client) {
// reference: http://knexjs.org/#Installation-client
const ssl = !this.config.ssl ? this.config.ssl : true;
const connection = { ...this.config.connection, ssl };
this.client = knex({ client: 'mysql', connection });
const schemaPreparer = this.config.drop
? new DropSchemaStrategy(this.client)
: new AlterSchemaStrategy(this.client);
// Prepare the schema for the INSERT.
await schemaPreparer.prepare(this.config, this.schema);
}
}
/**
* Takes a chunk from the incoming stream and pushes it onto the internal buffer.
*/
pushChunk(chunk) {
// if there is a newline at the end of a json file
if (chunk.length === 0) {
return;
}
this.internalBuffer.push(chunk.toString('utf-8'));
}
flushAndCloseConnection() {
this.log.info('flushing and closing connection');
this.flush().then(() => this.closeConnection()).catch(err => this.emit('error', err));
}
/**
* Close all active connections in pool.
*/
closeConnection() {
this.log.info('Destroying connection pool.');
this.client.destroy();
this.emit('close');
}
/**
*/
async flush() {
const columnNames = this.schema.map(field => field.name);
this.log.info(`Inserting data into columns: ${columnNames.join(' ')}`);
// just converting the Buffer to string, then parsing each line as JSON
const objectArray = this.internalBuffer.map(JSON.parse);
const valuesString = this.getValuesString(objectArray, columnNames);
// Create query with inserted values
const query = `INSERT INTO ${this.config.table} (${columnNames}) VALUES ${valuesString}`;
await this.client.raw(query);
this.internalBuffer = [];
this.log.info('Successfuly inserted batch of data into MySQL');
}
shouldFlush() {
return this.internalBuffer.length === this.maxBufferLength;
}
/**
* Returns a string of values for the multiple rows of data in the proper format for MySQL.
* Example: (1,2,3), (4,5,6), (7,8,9);
*/
getValuesString(objectArray, columnNames) {
// stringifiedRowsArray will look like [ '(1,2,3)', '(4,5,6)', '(7,8,9)' ]
const stringifiedRowValuesArray = objectArray.map((object) => {
// javacsript map should iterate in order, we need to go in order so the values match up with the columns when inserting
// reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description
const values = columnNames.map((columnName) => {
const column = this.schema.find(x => x.name === columnName);
const value = object[columnName];
// MySQL 5.7 can't handle non-string/text having empty string inserted
if (['string', 'text'].indexOf(column.type) === -1 && !value) {
return 'NULL';
}
// convert all date values to MySQL expected format
if (column.type === 'datetime') {
const formattedValue = moment(value).utc().format('YYYY-MM-DD HH:MM:SS');
return `\'${formattedValue}\'`;
}
if (isString(value)) {
const escapedValue = value.replace(/'/g, "\\'");
return `\'${escapedValue}\'`;
}
if (value === undefined || value === null) {
return 'NULL';
}
return value;
});
return `(${values})`;
});
return stringifiedRowValuesArray.join(',') + ';';
}
}
|
//Copyright (C) 2020. Omar Pino. All rights Reserved
export default class TelemetryRecord {
constructor(buildId = 0, playerId = 0, pos = {x: 0, y:0}, action = 0, count = 1) {
this.data = {
buildId,
playerId,
pos,
action
};
this.count = count
}
get buildId() {
return this.data.buildId;
}
set buildId(value) {
this.data.buildId = value;
}
get playerId() {
return this.data.playerId;
}
set playerId(value) {
this.data.playerId = value;
}
get pos() {
return this.data.pos;
}
set pos(value) {
this.data.pos = value;
}
get action() {
return this.data.action;
}
set action(value) {
this.data.action = value;
}
asString() {
return `${this.count} -> Build: ${this.data.buildId} Player: ${this.data.playerId} Position: X->${this.data.pos.x} Y-> ${this.data.pos.y} is doing ${this.data.action}`;
}
serialize() {
return JSON.stringify(this.data);
}
deserialize(JSONString) {
this.data = JSON.parse(JSONString);
}
}
|
componentWillMount() {
this.animatedValue = new Animated.Value(0)
}
componentDidMount() {
Animated.timing(this.animatedValue, {
toValue: 150,
duration: 2000,
delay: 500
}).start()
}
render() {
const { navigate } = this.props.navigation;
const interpolateColor = this.animatedValue.interpolate({
inputRange: [0, 150],
outputRange: ['#e15d64', '#fff']
})
const animatedStyle = {
backgroundColor: interpolateColor,
/*transform: [{ translateY: this.animatedValue }]*/
}
|
// Sum all the numbers of the array except the highest and the lowest element (the value, not the index!).
// (Only one element at each edge, even if there are more than one with the same value!)
//
// Example:
//
// { 6, 2, 1, 8, 10 } => 16
// { 1, 1, 11, 2, 3 } => 6
//
//
// If array is empty, null or None, or if only 1 Element exists, return 0.
function sumArray(array) {
var sum = 0;
if (!array || array.length < 2){
return 0;
} else {
var sortArr = array.sort(function(a,b){return a - b;});
for (var i = 1; i < sortArr.length - 1; i++) {
sum += sortArr[i];
}
}
return sum;
}
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var server = http.createServer(app);
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/bower_components'));
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.set('view engine', 'html');
app.use('/', function (req, res) {
res.render('./angular-demo.html');
});
server.listen(3000);
console.log('Server is listen: 3000');
|
import React, { Component } from 'react';
import LocationSearchInput from './LocationSearchInput';
class Search extends Component {
constructor(props) {
super(props);
}
render() {
return (
<form onSubmit={this.props.onSubmit} >
<div className="row">
<div className="col-sm-12 col-md-6 col-lg-6">
<div className="form-group">
<input type="text" className="form-control" id="keyword" name="keyword" placeholder="Search Keyword" onChange={this.props.handleChange} />
</div>
</div>
<div className="col-sm-12 col-md-5 col-lg-5">
<div className="form-group">
<LocationSearchInput setLatLong={this.props.setLatLong} />
</div>
</div>
<div className="col-sm-12 col-md-1 col-lg-1">
<input type="image" alt="Locate" src={require('./../images/analysis32.png')} />
</div>
</div>
</form>
);
}
}
export default Search;
|
(function (root, socket) {
var rows = [];
if (root) addRow(0, '/', root.name_, root);
return rows;
function addRow (depth, path, id, row) {
if (row.nodes) id = id + '/';
if (depth > 0) path = path + id;
rows.push(_.glagolRow(depth, path, id, row, socket))
if (row.nodes) {
Object.keys(row.nodes).forEach(function (childId) {
addRow(depth + 1, path, childId, row.nodes[childId]);
})
}
}
})
|
const state = {
actionPoints: 15,
allAbilities: [
{
id: 1,
name: 'Agility',
value: 5,
max: 15
},
{
id: 2,
name: 'Speed',
value: 5,
max: 15
},
{
id: 3,
name: 'Power',
value: 5,
max: 15
},
{
id: 4,
name: 'Intelligence',
value: 5,
max: 20
},
{
id: 5,
name: 'Life',
value: 5,
max: 20
}
]
};
const getters = {
actionPoints(state) {
return state.actionPoints;
},
allAbilities(state) {
return state.allAbilities.sort((a, b) => {
if (a.name < b.name) {
return -1
}
if (a.name > b.name) {
return 1
}
return 0
})
}
};
const mutations = {
increaseAbility(state, ability){
if(ability.value < ability.max && state.actionPoints > 0) {
state.actionPoints--;
state.allAbilities.map(item => {
if (item.id === ability.id && item.value !== item.max) item.value++;
});
}
},
decreaseAbility(state, ability){
if(ability.value !== 0) {
state.actionPoints++;
state.allAbilities.map(item => {
if (item.id === ability.id) item.value--;
});
}
}
};
const actions = {
increaseAbility( {commit}, ability ){
commit('increaseAbility', ability)
},
decreaseAbility( {commit}, ability ){
commit('decreaseAbility', ability)
}
}
export default {
state,
getters,
mutations,
actions
}
|
import { ViewWeather } from './MVC/ViewWeather';
import { ModelWeather } from './MVC/ModelWeather';
import { ControllerWeather } from './MVC/ControllerWeather';
const view = new ViewWeather();
const model = new ModelWeather();
const controller = new ControllerWeather(model, view);
controller.init();
|
// Toujour Commenter
/**
* Model ...
*
*/
const mongoose = require('mongoose');
const CommentaireSchema = new mongoose.Schema({
article_id: String,
avatarImg: String,
article_id: String,
username: String,
content: String,
dateLe: String,
dateA: String,
})
const Commentaire = mongoose.model('Commentaire', CommentaireSchema);
module.exports = Commentaire
|
menuGame = {
create:function () {
game.physics.startSystem(Phaser.Physics.ARCADE);
game.add.sprite(0,0, "bg");
menuText = game.add.text(50,h/2-70, "Press UP button to start",{"fill":"black"});
menuText.scale.x = 2;
menuText.scale.y = 2;
player = game.add.sprite(64, game.world.height - 150, 'dude');
keyboard = game.input.keyboard.createCursorKeys();
var count = 0;
},
update:function(){
if(keyboard.up.isDown){
game.state.start("playGame");
}
}
}
|
import React from 'react';
import { Link } from 'react-router-dom';
//imagens
import CardCalc from '../../cards/calc.jpg';
import ApiList from '../../cards/apilist.jpg';
import Redux from '../../cards/noname.jpg'
function Main() {
return (
<>
<div className="container">
<div className="main">
<div className="cards">
<Link to="/redux">
<div className="card">
<div className="card-img">
<img src={Redux} alt="Redux" />
</div>
<div className="description"><p>Redux Saga</p></div>
</div>
</Link>
<Link to="/apilist">
<div className="card">
<div className="card-img">
<img src={ApiList} alt="ApiList" />
</div>
<div className="description"><p>Simple API List</p></div>
</div>
</Link>
<Link to="/calculator">
<div className="card">
<div className="card-img">
<img src={CardCalc} alt="Calculator" />
</div>
<div className="description"><p>Calculator</p></div>
</div>
</Link>
</div>
</div>
</div>
</>
);
}
export default Main;
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var axios = _interopDefault(require('axios'));
let protocolClient;
let registry = {
registerProtocolClient: registerProtocolClient
};
function registerProtocolClient (client) {
protocolClient = client;
}
function getProtocolClient () {
return protocolClient;
}
function serviceOptions(service, serviceName, initObj) {
if (typeof initObj === 'string') {
initObj = { baseUrl: initObj };
}
else if (typeof initObj !== 'object') {
initObj = {};
}
service.serviceLatency = 0;
service.serviceLatencyStartTime = 0;
service.serviceLastConnectedTime = Date.now();
service.serviceName = serviceName;
service.serviceBaseUrl = initObj.baseUrl || '';
service.servicePollInterval = initObj.poll;
service.serviceMonitorLatency = initObj.monitorLatency;
service.baseUrl = baseUrl;
service.protocolClient = protocolClient;
service.poll = poll;
service.monitorLatency = monitorLatency;
service.startLatencyTimer = startLatencyTimer;
service.stopLatencyTimer = stopLatencyTimer;
service.latency = latency;
service.lastConnectedTime = lastConnectedTime;
function startLatencyTimer () {
service.serviceLatencyStartTime = Date.now();
}
function stopLatencyTimer (hasError) {
if (hasError) {
service.serviceLatency = 0;
}
else {
service.serviceLastConnectedTime = Date.now();
service.serviceLatency = service.serviceLastConnectedTime - service.serviceLatencyStartTime;
}
}
function baseUrl (val) {
if (!val) {
return this.serviceBaseUrl;
}
this.serviceBaseUrl = val;
return this;
}
function protocolClient (val) {
if (!val) {
return this.serviceProtocolClient || getProtocolClient();
}
this.serviceProtocolClient = val;
return this;
}
function poll (val) {
if (!val) {
return this.servicePollInterval;
}
this.servicePollInterval = val;
return this;
}
function monitorLatency (val) {
if (!val) {
return this.serviceMonitorLatency;
}
this.serviceMonitorLatency = val;
return this;
}
function latency (val) {
if (!val) {
return this.serviceLatency;
}
//read-only
//this.serviceLatency = val;
return this;
}
function lastConnectedTime (val) {
if (!val) {
return this.serviceLastConnectedTime;
}
//read-only
//this.serviceLastConnectedTime = val;
return this;
}
}
function IntervalUtil (options) {
var _defaults = {
interval: 25 * 1000, //25 Seconds
errorInterval: 5 * 60 * 1000 //5 Minutes
};
var _options;
var _intervalFunction;
var _intervalId;
var _running;
if (typeof options === 'number') {
options = Math.max(1000, options); //1 second minimum
options = {interval: options};
}
_options = Object.assign({}, _defaults, options || {});
//function noop () {}
function start (intervalFunction) {
if (_running) {
stop();
}
_intervalFunction = intervalFunction;
_running = true;
_startInterval(_options.interval);
}
function stop () {
_running = false;
clearTimeout(_intervalId);
}
function isRunning () {
return _running;
}
function _startInterval (delay) {
_intervalId = setTimeout(function () {
_intervalFunction();
}, delay);
}
this.stop = stop;
this.start = start;
this.isRunning = isRunning;
}
function RpcService () {
this.$post = $post;
function $post (rpcMethod, rpcParams) {
return rpcRequest(this, 'POST', rpcMethod, rpcParams);
}
function rpcRequest (service, method, rpcMethod, rpcParams) {
if (!rpcMethod) {
throw new Error('You must configure the rpc method');
}
var data = { jsonrpc: '2.0', id: 1 };
data.method = rpcMethod;
data.params = rpcParams || [];
var options = {};
options.url = service.baseUrl();
options.data = data;
options.method = method;
options.transformResponse = function (response) {
return response.data.result;
};
options.transformResponseError = function (response) {
return response.data.error;
};
return makeServiceRequest(service, options);
}
}
function IpcService () {
this.$send = $send;
function $send (method, params) {
return ipcRequest(this, method, params);
}
function ipcRequest (service, method, params) {
if (!method) {
throw new Error('You must configure the ipc method');
}
let data = {
method: method,
params: params || []
};
let options = {};
options.data = data;
return makeServiceRequest(service, options);
}
}
let factory = ServiceFactory();
function ServiceFactory () {
function createRcpService (options) {
let inst = new RpcService();
serviceOptions(inst, 'node', options);
return inst;
}
function createIpcService (options) {
let inst = new IpcService();
serviceOptions(inst, 'node', options);
return inst;
}
function createRestService (options) {
let inst = new RestService();
serviceOptions(inst, 'node', options);
return inst;
}
return {
createRcpService: createRcpService,
createIpcService: createIpcService,
createRestService: createRestService
};
}
let service = Service();
service.factory = factory;
function Service () {
// All requests under the same policy will get coalesced.
function PollingPolicy (options) {
this.options = options;
this.stopAll = function () {}; //set by PollRunner
this.startAll = function () {}; //set by PollRunner
this._interval = function () {};
this._requests = [];
}
//When Batch of methods complete
PollingPolicy.prototype.onInterval = onInterval;
PollingPolicy.prototype.run = run;
function onInterval (fn) {
if (typeof fn !== 'function') {
throw new Error('onInterval(fn) - "fn" must be of type "function"');
}
this._interval = fn;
}
function run (method) {
this._requests.push(method);
}
function createPollingPolicy (options) {
return new PollingPolicy(options);
}
function isPollingPolicy (obj) {
return obj instanceof PollingPolicy;
}
//number, optionsObj or PollPolicy
function getPollRunner (obj) {
if(obj instanceof PollingPolicy) {
if (!obj._pollRunner) {
obj._pollRunner = new PollRunner(obj);
}
return obj._pollRunner;
}
return new PollRunner(new PollingPolicy(obj));
}
return {
createPollingPolicy: createPollingPolicy,
isPollingPolicy: isPollingPolicy,
getPollRunner: getPollRunner
};
}
function PollRunner (policy) {
let intervalUtil = new IntervalUtil(policy.options);
let _isPaused = false;
let _isPolling = false;
this.isPolling = isPolling;
this.addRequest = addRequest;
this.pause = pause;
this.play = play;
policy.stopAll = pause;
policy.startAll = play;
function isPolling() {
return _isPolling || intervalUtil.isRunning();
}
function addRequest (request) {
policy._requests.push(request);
return this;
}
function pause() {
_isPaused = true;
intervalUtil.stop();
}
function play() {
if (_isPaused) {
_isPaused = false;
intervalUtil.start(runAll);
}
}
setTimeout(runAll, 0);
function runAll () {
let count = policy._requests.length;
_isPolling = true;
policy._requests.forEach(function (request) {
request().then(complete).catch(complete);
});
function complete () {
--count;
if (count === 0) {
policy._interval();
_isPolling = false;
if (!_isPaused) {
intervalUtil.start(runAll);
}
}
}
}
}
function makeServiceRequest (restService, httpOptions) {
return _wrapPromise(function (resolve, reject, notify) {
let ctx = prepareContext();
ctx.successFunction = resolve;
ctx.errorFunction = reject;
ctx.notifyFunction = notify;
ctx.transformResponse = httpOptions.transformResponse || noop;
ctx.transformResponseError = httpOptions.transformResponseError || noop;
let client = restService.protocolClient();
let options = client.buildRequestOptions(httpOptions);
let poll = restService.poll();
if (restService.monitorLatency()) {
ctx.startLatencyTimer = restService.startLatencyTimer;
ctx.stopLatencyTimer = restService.stopLatencyTimer;
}
if (poll) {
let pollRunner = service.getPollRunner(poll).addRequest(function () {
return _makeServiceRequest(client, options, ctx);
});
ctx.stopPolling = pollRunner.pause;
ctx.isPolling = pollRunner.isPolling;
}
else {
_makeServiceRequest(client, options, ctx);
}
});
}
function noop () {}
//Only top-level Promise has notify. This is intentional as then().notify() does not make any sense.
// Notify keeps the chain open indefinitely and can be called repeatedly.
// Once Then is called, the promise chain is considered resolved and marked for cleanup. Notify can never be called after a then.
function _wrapPromise (callback) {
let promise = new Promise(function (resolve, reject) {
callback(resolve, reject, handleNotify);
});
promise._notify = noop;
promise.notify = notify;
function notify (fn) {
if (promise._notify === noop) {
promise._notify = fn;
}
else {
//Support chaining notify calls: notify().notify()
let chainNotify = promise._notify;
promise._notify = function (result) {
return fn(chainNotify(result));
};
}
return this;
}
function handleNotify (result) {
promise._notify(result);
}
return promise;
}
function prepareContext() {
let ctx = { };
ctx.stopPolling = noop;
ctx.isPolling = noop;//function () { return false; };
ctx.startLatencyTimer = noop;
ctx.stopLatencyTimer = noop;
return ctx;
}
function _makeServiceRequest (client, options, ctx) {
ctx.startLatencyTimer();
let promise = client.invoke(options);
promise.catch(function (response) {
ctx.errorFunction(response);
ctx.stopLatencyTimer(true);
});
promise = promise.then(function (response) {
ctx.stopLatencyTimer();
let data = ctx.transformResponse(response);
if (!data) {
let error = ctx.transformResponseError(response);
if (error) {
ctx.errorFunction(error, response);
if (ctx.isPolling()) {
ctx.stopPolling();
}
return;
}
}
if (ctx.isPolling()) {
ctx.notifyFunction(data, response);
}
else {
ctx.successFunction(data, response);
}
});
return promise;
}
function rest (options) {
let inst = new RestService();
serviceOptions(inst, 'rest', options);
return inst;
}
function RestService () {
this.$post = $post;
this.$get = $get;
this.$put = $put;
this.$delete = $delete;
function $post (url, data, options, queryParams) {
return httpRequest(this, url, 'POST', data, options, queryParams);
}
function $get (url, queryParams, options) {
return httpRequest(this, url, 'GET', null, options, queryParams);
}
function $put (url, data, options, queryParams) {
return httpRequest(this, url, 'PUT', data, options, queryParams);
}
function $delete (url, queryParams, options) {
return httpRequest(this, url, 'DELETE', null, options, queryParams);
}
function httpRequest (service, url, method, data, options, queryParams) {
if (!method || !url) {
throw new Error('You must configure at least the http method and url');
}
options = options || {};
if (service.baseUrl() !== undefined) {
url = service.baseUrl() + url;
}
options.url = url;
options.body = data;
options.method = method;
options.queryParams = queryParams;
if (!options.hasOwnProperty('transformResponse')) {
options.transformResponse = function (response) {
return response.data;
};
}
if (!options.hasOwnProperty('transformResponseError')) {
options.transformResponseError = function (response) {
return response.data;
};
}
return makeServiceRequest(service, options);
}
}
function antChain(options) {
let inst = new RestService();
serviceOptions(inst, 'antChain', options);
//Block
inst.getBlockByHash = getBlockByHash;
inst.getBlockByHeight = getBlockByHeight;
inst.getCurrentBlock = getCurrentBlock;
inst.getCurrentBlockHeight = getCurrentBlockHeight;
//Address
inst.getAddressBalance = getAddressBalance;
inst.getUnspentCoinsByAddress = getUnspentCoinsByAddress;
//Tx
inst.getTransactionByTxid = getTransactionByTxid;
return inst;
}
function getAddressBalance (address) {
return this.$get('address/get_value/' + address);
}
function getUnspentCoinsByAddress (address) {
return this.$get('address/get_unspent/' + address);
}
function getBlockByHash (blockhash) {
return this.$get('block/get_block/' + blockhash);
}
function getBlockByHeight (height) {
return this.$get('block/get_block/' + height);
}
function getCurrentBlock () {
return this.$get('block/get_current_block');
}
function getCurrentBlockHeight () {
return this.$get('block/get_current_height');
}
function getTransactionByTxid (txid) {
return this.$get('tx/get_tx/' + txid);
}
function antChainXyz(options) {
var inst = new RestService();
serviceOptions(inst, 'antChainXyz', options);
inst.getAddressBalance = getAddressBalance$1;
inst.getAssetTransactionsByAddress = getAssetTransactionsByAddress;
return inst;
}
function getAddressBalance$1 (address) {
return this.$get('address/info/' + address);
}
function getAssetTransactionsByAddress (address) {
return this.$get('address/utxo/' + address);
}
function neoScan(options) {
var inst = new RestService();
serviceOptions(inst, 'neoScan', options);
inst.getCurrentBlockHeight = getCurrentBlockHeight$1;
return inst;
}
function getCurrentBlockHeight$1 () {
return this.$get('get_height');
}
function neon(options) {
var inst = new RestService();
serviceOptions(inst, 'neon', options);
inst.getCurrentBlockHeight = getCurrentBlockHeight$2;
inst.getAddressBalance = getAddressBalance$2;
inst.getAssetTransactionsByAddress = getAssetTransactionsByAddress$1;
inst.getTransactionByTxid = getTransactionByTxid$1;
return inst;
}
function getCurrentBlockHeight$2 () {
return this.$get('block/height', null, { transformResponse: transformResponse });
function transformResponse (response) {
return {
height: response.data && response.data.block_height
};
}
}
function getAddressBalance$2 (address) {
return this.$get('address/balance/' + address);
}
function getAssetTransactionsByAddress$1 (address) {
return this.$get('address/history/' + address);
}
function getTransactionByTxid$1 (txid) {
return this.$get('transaction/' + txid);
}
function pyrest(options) {
var inst = new RestService();
serviceOptions(inst, 'pyrest', options);
inst.getCurrentBlockHeight = getCurrentBlockHeight$3;
return inst;
}
function getCurrentBlockHeight$3 () {
return this.$get('status', null, { transformResponse: transformResponse });
function transformResponse (response) {
return {
height: response.data && response.data.current_height,
version: response.data && response.data.version
};
}
}
function node(options) {
var inst = new RpcService();
serviceOptions(inst, 'node', options);
inst.dumpPrivKey = dumpPrivKey;
inst.getAccountState = getAccountState;
inst.getApplicationLog = getApplicationLog;
inst.getAssetState = getAssetState;
inst.getBalance = getBalance;
inst.getBestBlockHash = getBestBlockHash;
inst.getBlock = getBlock;
inst.getBlockCount = getBlockCount;
inst.getBlockHash = getBlockHash;
inst.getBlockSysFee = getBlockSysFee;
inst.getConnectionCount = getConnectionCount;
inst.getContractState = getContractState;
inst.getNewAddress = getNewAddress;
inst.getRawMemPool = getRawMemPool;
inst.getRawTransaction = getRawTransaction;
inst.getStorage = getStorage;
inst.getTxOut = getTxOut;
inst.getPeers = getPeers;
inst.getVersion = getVersion;
inst.invoke = invoke;
inst.invokeFunction = invokeFunction;
inst.invokeScript = invokeScript;
inst.listAddress = listAddress;
inst.sendRawTransaction = sendRawTransaction;
inst.sendToAddress = sendToAddress;
inst.sendMany = sendMany;
inst.validateAddress = validateAddress;
return inst;
}
//http://docs.neo.org/en-us/node/api/dumpprivkey.html
function dumpPrivKey (address) {
return this.$post('dumpprivkey', [address]);
}
//http://docs.neo.org/en-us/node/api/getaccountstate.html
function getAccountState (address) {
return this.$post('getaccountstate', [address]);
}
//http://docs.neo.org/en-us/node/api/getapplicationlog.html
function getApplicationLog (txId, verbose) {
return this.$post('getapplicationlog', [txId, verbose ? 1 : 0]);
}
//http://docs.neo.org/en-us/node/api/getassetstate.html
function getAssetState (assetId) {
return this.$post('getassetstate', [assetId]);
}
//http://docs.neo.org/en-us/node/api/getbalance.html
function getBalance (assetId) {
return this.$post('getbalance', [assetId]);
}
//http://docs.neo.org/en-us/node/api/getbestblockhash.html
function getBestBlockHash () {
return this.$post('getbestblockhash', []);
}
//http://docs.neo.org/en-us/node/api/getblock.html
//http://docs.neo.org/en-us/node/api/getblock2.html
function getBlock (hashOrIndex, verbose) {
return this.$post('getblock', [hashOrIndex, verbose ? 1 : 0]);
}
//http://docs.neo.org/en-us/node/api/getblockcount.html
function getBlockCount () {
return this.$post('getblockcount', []);
}
//http://docs.neo.org/en-us/node/api/getblockhash.html
function getBlockHash (index) {
return this.$post('getblockhash', [index]);
}
//http://docs.neo.org/en-us/node/api/getblocksysfee.html
function getBlockSysFee (index) {
return this.$post('getblocksysfee', [index]);
}
//http://docs.neo.org/en-us/node/api/getconnectioncount.html
function getConnectionCount () {
return this.$post('getconnectioncount', []);
}
//http://docs.neo.org/en-us/node/api/getcontractstate.html
function getContractState (scriptHash) {
return this.$post('getcontractstate', [scriptHash]);
}
//http://docs.neo.org/en-us/node/api/getnewaddress.html
function getNewAddress () {
return this.$post('getnewaddress', []);
}
//http://docs.neo.org/en-us/node/api/getrawmempool.html
function getRawMemPool () {
return this.$post('getrawmempool', []);
}
//http://docs.neo.org/en-us/node/api/getrawtransaction.html
function getRawTransaction (txId, verbose) {
return this.$post('getrawtransaction', [txId, verbose ? 1 : 0]);
}
//http://docs.neo.org/en-us/node/api/getstorage.html
function getStorage (scriptHash, key) {
return this.$post('getstorage', [scriptHash, key]);
}
//http://docs.neo.org/en-us/node/api/gettxout.html
function getTxOut (txId, n) {
return this.$post('gettxout', [txId, n]);
}
//http://docs.neo.org/en-us/node/api/getpeers.html
function getPeers () {
return this.$post('getpeers', []);
}
//http://docs.neo.org/en-us/node/api/getversion.html
function getVersion () {
return this.$post('getversion', []);
}
//http://docs.neo.org/en-us/node/api/invoke.html
function invoke (scriptHash, params) {
return this.$post('invoke', [scriptHash, params]);
}
//http://docs.neo.org/en-us/node/api/invokefunction.html
function invokeFunction (scriptHash, operation, params) {
return this.$post('invokefunction', [scriptHash, operation, params]);
}
//http://docs.neo.org/en-us/node/api/invokescript.html
function invokeScript (script) {
return this.$post('invokescript', [script]);
}
//http://docs.neo.org/en-us/node/api/listaddress.html
function listAddress () {
return this.$post('listaddress', []);
}
//http://docs.neo.org/en-us/node/api/sendrawtransaction.html
function sendRawTransaction(hex) {
return this.$post('sendrawtransaction', [hex]);
}
//http://docs.neo.org/en-us/node/api/sendtoaddress.html
function sendToAddress(assetId, address, value, fee) {
return this.$post('sendtoaddress', [assetId, address, value, fee ? 1 : 0]);
}
//http://docs.neo.org/en-us/node/api/sendmany.html
function sendMany(outputsArray, fee, changeAddress) {
var params = [outputsArray, fee ? 1 : 0];
if(changeAddress !== undefined) {
params.push(changeAddress);
}
return this.$post('sendmany', params);
}
//http://docs.neo.org/en-us/node/api/validateaddress.html
function validateAddress(address) {
return this.$post('validateaddress', [address]);
}
//AXIOS workaround - process.env.NODE_ENV
if (typeof process === 'undefined' && !window.process) {
window.process = {env: {}};
}
let axiosClient = AxiosClient();
function AxiosClient (){
function invoke (restOptions) {
return axios(restOptions);
}
function serialize (obj) {
return obj && Object.keys(obj).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]);
}).join('&');
}
function filterKeys (srcOptions, keys) {
return keys.reduce(function (result, k) {
if (srcOptions[k]) {
result[k] = srcOptions[k];
}
return result;
}, {});
}
function buildRequestOptions (options) {
//Build Url with queryParams
let paramStr = options.queryParams && serialize(options.queryParams);
if(paramStr) {
options.url = options.url + '?' + paramStr;
}
// Don't allow any undefined values into Fetch Options
options = filterKeys(options, ['method', 'url', 'params', 'body', 'data', 'cache', 'headers']);
options.headers = {};
options.headers['Accept'] = 'application/json';
options.headers['Content-Type'] = 'application/json';
if (options.body) {
options.body = JSON.stringify(options.body);
}
if (options.data) {
options.data = JSON.stringify(options.data);
}
return options;
}
return {
invoke: invoke,
buildRequestOptions: buildRequestOptions
};
}
registerProtocolClient(axiosClient);
exports.antChain = antChain;
exports.antChainXyz = antChainXyz;
exports.neoScan = neoScan;
exports.neon = neon;
exports.pyrest = pyrest;
exports.node = node;
exports.rest = rest;
exports.registry = registry;
exports.service = service;
|
const TwingCacheFilesystem = require('../../../../../lib/twing/cache/filesystem').TwingCacheFilesystem;
const tap = require('tap');
const nodePath = require('path');
let fixturesPath = nodePath.resolve('test/tests/unit/twing/cache/fixtures');
tap.test('cache filesystem', function (test) {
let cache = new TwingCacheFilesystem(fixturesPath);
test.test('load', function (test) {
test.test('should bypass require cache', function (test) {
let load1 = cache.load(nodePath.join(fixturesPath, 'template.js'));
let load2 = cache.load(nodePath.join(fixturesPath, 'template.js'));
let load3 = cache.load(nodePath.join(fixturesPath, 'template.js'));
test.same(load1(), 1);
test.same(load2(), 1);
test.same(load3(), 1);
test.end();
});
test.end();
});
test.end();
});
|
// Object transitions
var FiniteLife = {
init: function (T) {
this.T = T || 1
},
think: function (dt) {
if (this.t > this.T) {
this.t = this.T
this.done = true
}
},
}
var LinearTrans = {
think: function (dt) {
this.f = this.t / this.T
},
}
var NonLinearTrans = {
init: function (p) {
this.p = p || 0
this.A = p ? 1 / (Math.exp(this.p) - 1) : 0
},
think: function (dt) {
var f = this.t / this.T
this.f = this.p ? this.A * (Math.exp(this.p * f) - 1) : f
},
}
var Hesitates = {
init: function (T) {
this.hT0 = T || 0
this.hT = 0
},
think: function (dt) {
this.hT += dt
this.t = Math.max(Math.min(this.t, this.hT - this.hT0), 0)
},
}
function Spin() {
}
Spin.prototype = UFX.Thing()
.addcomp(Ticks)
.addcomp(FiniteLife, 0.8)
.addcomp(NonLinearTrans, -1)
.addcomp({
draw: function (obj) {
UFX.draw("r", this.f * tau)
},
})
function Deploy(obj) {
var A = Math.atan2(obj.x, obj.y)
this.hT0 = 0.1 * A
}
Deploy.prototype = UFX.Thing()
.addcomp(Ticks)
.addcomp(Hesitates)
.addcomp(FiniteLife, 0.8)
.addcomp(NonLinearTrans, -3)
.addcomp({
init: function () {
this.halts = true
},
draw: function (obj) {
UFX.draw("t", -obj.x * (1-this.f), -obj.y * (1-this.f))
},
})
function Undeploy(obj) {
var A = Math.atan2(obj.x, obj.y)
this.hT0 = 0.1 * A
}
Undeploy.prototype = UFX.Thing()
.addcomp(Ticks)
.addcomp(Hesitates)
.addcomp(FiniteLife, 0.8)
.addcomp(NonLinearTrans, -3)
.addcomp({
init: function () {
this.kills = true
this.halts = true
},
draw: function (obj) {
UFX.draw("t", -obj.x * this.f, -obj.y * this.f)
},
})
function GrowFade() {
}
GrowFade.prototype = UFX.Thing()
.addcomp(Ticks)
.addcomp(FiniteLife, 0.5)
.addcomp(NonLinearTrans)
.addcomp({
init: function () {
this.kills = true
},
draw: function (obj) {
s = 1 + 2 * this.f
UFX.draw("z", s, s, "alpha", 1-this.f)
},
})
function GrowFadeHalt() {
}
GrowFadeHalt.prototype = UFX.Thing()
.addcomp(Ticks)
.addcomp(FiniteLife, 0.5)
.addcomp(NonLinearTrans)
.addcomp({
init: function () {
this.kills = true
this.halts = true
},
draw: function (obj) {
s = 1 + 2 * this.f
UFX.draw("z", s, s, "alpha", 1-this.f)
},
})
// Effects
function Ghost(thing0, thing1) {
this.thing0 = thing0
this.thing1 = thing1
var dx = thing1.x - thing0.x, dy = thing1.y - thing0.y
this.T = Math.sqrt(Math.max(dx * dx + dy * dy, 1)) / settings.ghostv
this.think(0)
this.trans = { kills: true }
}
Ghost.prototype = UFX.Thing()
.addcomp(Ticks)
.addcomp(FiniteLife, 0.3)
.addcomp(NonLinearTrans, -3)
.addcomp({
getf: function (t) {
var f = clip(t / this.T, 0, 1)
return this.p ? this.A * (Math.exp(this.p * f) - 1) : f
},
getpos: function (t) {
var f = this.getf(t)
return [
this.thing1.x * f + this.thing0.x * (1 - f),
this.thing1.y * f + this.thing0.y * (1 - f),
]
},
draw: function () {
UFX.draw("[ t", this.getpos(this.t), "b o 0 0 0.4 f ]")
UFX.draw("[ t", this.getpos(this.t - 0.02), "b o 0 0 0.3 f ]")
UFX.draw("[ t", this.getpos(this.t - 0.03), "b o 0 0 0.2 f ]")
},
halts: function () {
return true
},
})
.addcomp(Unclickable)
|
const models = require('../models');
const MINIMUM_YEAR = 2015;
const sendError = (err, res) => {
res.status(500).send(`Error while doing operation: ${err.name}, ${err.message}`);
};
exports.findByYear = function findByYear(req, res) {
const { year } = req.query;
models.Omzet.findAll({
where: {
year: year || MINIMUM_YEAR,
},
order: ['year', 'month'],
})
.then((omzets) => {
res.json(omzets);
})
.catch((err) => {
sendError(err, res);
});
};
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of
* the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing
* permissions and limitations under the License.
*/
'use strict';
const kSetControlLineState = 0x22;
const kGetLineCoding = 0x21;
const kSetLineCoding = 0x20;
const kDefaultSerialOptions = {
baudrate: 115200,
databits: 8,
stopbits: 1,
parity: 'none',
buffersize: 255,
rtscts: false,
xon: false,
xoff: false,
xany: false,
};
const kAcceptableDataBits = [16, 8, 7, 6, 5];
const kAcceptableStopBits = [1, 2];
const kAcceptableParity = ['none', 'even', 'mark', 'odd', 'space'];
const kParityIndexMapping = ['none', 'odd', 'even', 'mark', 'space'];
const kStopbitsIndexMapping = [1, 1.5, 2];
/** a class used to control serial devices over WebUSB */
class SerialPort {
/**
* constructor taking a WebUSB device that creates a SerialPort instance.
* @param {object} device A device acquired from the WebUSB API
* @param {object} serialOptions Optional object containing serial options
*/
constructor(device, serialOptions = {}) {
/** @private {number} */
this.transferInterface_ = 0;
/** @private {number} */
this.controlInterface_ = 0;
/** @private {number} */
this.serialOptions_ =
Object.assign({}, kDefaultSerialOptions, serialOptions);
/** @private {object} */
this.device_ = {};
this.validateOptions_();
this.setPort_(device);
}
/**
* a function that opens the device and claims all interfaces needed to
* control and communicate to and from the serial device
* @return {Promise} A promise that will resolve when device is ready for
* communication
*/
async open() {
try {
await this.device_.open();
if (this.device_.configuration === null) {
await this.device_.selectConfiguration(1);
}
await this.device_.claimInterface(this.controlInterface_.interfaceNumber);
await this.device_.claimInterface(
this.transferInterface_.interfaceNumber);
await this.setOptions();
await this.device_.controlTransferOut({
'requestType': 'class',
'recipient': 'interface',
'request': kSetControlLineState,
'value': 0x01,
'index': this.controlInterface_.interfaceNumber,
});
this.in = new ReadableStream({start: this.readStart_.bind(this)});
this.out = new WritableStream({
write: this.write_.bind(this),
});
} catch (error) {
throw new Error('Error setting up device: ' + error.toString());
}
}
/**
* A function used the get the options directoly from the device
* @return {Promise} A promise that will resolve with an object containing
* the device serial options
*/
getInfo() {
return this.device_
.controlTransferIn(
{
'requestType': 'class',
'recipient': 'interface',
'request': kGetLineCoding,
'value': 0x00,
'index': 0x00,
},
7)
.then((response) => {
return this.readLineCoding_(response.data.buffer);
});
}
/**
* A function used to change the serial settings of the device
* @param {object} options the object which carries serial settings data
* @return {Promise} A promise that will resolve when the options are set
*/
setOptions(options) {
const newOptions = Object.assign({}, this.serialOptions_, options);
this.serialOptions_ = newOptions;
this.validateOptions_();
return this.setSerialOptions_();
}
/**
* Set the device inside the class and figure out which interface is the
* proper one for transfer and control
* @param {object} device A device acquired from the WebUSB API
*/
setPort_(device) {
if (!SerialPort.isSerialDevice_(device)) {
throw new TypeError('This is not a serial port');
}
this.device_ = device;
this.transferInterface_ = this.getTransferInterface_(device);
this.controlInterface_ = this.getControlInterface_(device);
}
/**
* Checks the serial options for validity and throws an error if it is
* not valid
*/
validateOptions_() {
if (!this.isValidBaudRate_(this.serialOptions_.baudrate)) {
throw new RangeError('invalid Baud Rate ' + this.serialOptions_.baudrate);
}
if (!this.isValidDataBits_(this.serialOptions_.databits)) {
throw new RangeError('invalid databits ' + this.serialOptions_.databits);
}
if (!this.isValidStopBits_(this.serialOptions_.stopbits)) {
throw new RangeError('invalid stopbits ' + this.serialOptions_.stopbits);
}
if (!this.isValidParity_(this.serialOptions_.parity)) {
throw new RangeError('invalid parity ' + this.serialOptions_.parity);
}
}
/**
* Checks the baud rate for validity
* @param {number} baudrate the baud rate to check
* @return {boolean} A boolean that reflects whether the baud rate is valid
*/
isValidBaudRate_(baudrate) {
return baudrate % 1 === 0;
}
/**
* Checks the data bits for validity
* @param {number} databits the data bits to check
* @return {boolean} A boolean that reflects whether the data bits setting is
* valid
*/
isValidDataBits_(databits) {
return acceptableDataBits.includes(databits);
}
/**
* Checks the stop bits for validity
* @param {number} stopbits the stop bits to check
* @return {boolean} A boolean that reflects whether the stop bits setting is
* valid
*/
isValidStopBits_(stopbits) {
return acceptableStopBits.includes(stopbits);
}
/**
* Checks the parity for validity
* @param {number} parity the parity to check
* @return {boolean} A boolean that reflects whether the parity is valid
*/
isValidParity_(parity) {
return acceptableParity.includes(parity);
}
/**
* The function called by the writable stream upon creation
* @param {number} controller The stream controller
* @return {Promise} A Promise that is to be resolved whe this instance is
* ready to use the writablestream
*/
writeStart_(controller) {
return new Promise((resolve, reject) => {
if (this.device_) {
resolve();
}
});
}
/**
* The function called by the readable stream upon creation
* @param {number} controller The stream controller
*/
readStart_(controller) {
const readLoop = () => {
this.device_
.transferIn(this.getDirectionEndpoint_('in').endpointNumber, 64)
.then(
(result) => {
controller.enqueue(result.data);
readLoop();
},
(error) => {
controller.error(error.toString());
});
};
readLoop();
}
/**
* Sends data along the "out" endpoint of this
* @param {ArrayBuffer} chunk the data to be sent out
* @param {Object} controller The Object for the
* WritableStreamDefaultController used by the WritablSstream API
* @return {Promise} a promise that will resolve when the data is sent
*/
write_(chunk, controller) {
if (chunk instanceof ArrayBuffer) {
return this.device_
.transferOut(this.getDirectionEndpoint_('out').endpointNumber, chunk)
.catch((error) => {
controller.error(error.toString());
});
} else {
throw new TypeError(
'Can only send ArrayBuffers please use transform stream to convert ' +
'data to ArrayBuffer');
}
}
/**
* sends the options alog the control interface to set them on the device
* @return {Promise} a promise that will resolve when the options are set
*/
setSerialOptions_() {
return this.device_.controlTransferOut(
{
'requestType': 'class',
'recipient': 'interface',
'request': kSetLineCoding,
'value': 0x00,
'index': 0x00,
},
this.getLineCodingStructure_());
}
/**
* Takes in an Array Buffer that contains Line Coding according to the USB
* CDC spec
* @param {ArrayBuffer} buffer The data structured accoding to the spec
* @return {object} The options
*/
readLineCoding_(buffer) {
const options = {};
const view = new DataView(buffer);
options.baudrate = view.getUint32(0, true);
options.stopbits = view.getUint8(4) < stopbitsIndexMapping.length ?
stopbitsIndexMapping[view.getUint8(4)] :
1;
options.parity = view.getUint8(5) < parityIndexMapping.length ?
parityIndexMapping[view.getUint8(5)] :
'none';
options.databits = view.getUint8(6);
return options;
}
/**
* Turns the serialOptions into an array buffer structured into accordance to
* the USB CDC specification
* @return {object} The array buffer with the Line Coding structure
*/
getLineCodingStructure_() {
const buffer = new ArrayBuffer(7);
const view = new DataView(buffer);
view.setUint32(0, this.serialOptions_.baudrate, true);
view.setUint8(
4, stopbitsIndexMapping.indexOf(this.serialOptions_.stopbits));
view.setUint8(5, parityIndexMapping.indexOf(this.serialOptions_.parity));
view.setUint8(6, this.serialOptions_.databits);
return buffer;
}
/**
* Check whether the passed device is a serial device with the proper
* interface classes
* @param {object} device the device acquired from the WebUSB API
* @return {boolean} the boolean indicating whether the device is structured
* as a serial device
*/
static isSerialDevice_(device) {
if (!(device.configurations instanceof Array)) {
return false;
}
let hasInterfaceClassTen = false;
let hasInterfaceClassTwo = false;
device.configurations.forEach((config) => {
if (config.interfaces instanceof Array) {
config.interfaces.forEach((thisInterface) => {
if (thisInterface.alternates instanceof Array) {
thisInterface.alternates.forEach((alternate) => {
if (alternate.interfaceClass === 10) {
hasInterfaceClassTen = true;
}
if (alternate.interfaceClass === 2) {
hasInterfaceClassTwo = true;
}
});
}
});
}
});
return hasInterfaceClassTen && hasInterfaceClassTwo;
}
/**
* Finds the interface used for controlling the serial device
* @param {Object} device the object for a device from the WebUSB API
* @return {object} The interface Object created from the WebUSB API that is
* expected to handle the control of the Serial Device
*/
getControlInterface_(device) {
return this.getInterfaceWithClass_(device, 2);
}
/**
* Finds the interface used for transfering data over the serial device
* @param {Object} device the object for a device from the WebUSB API
* @return {object} The interface Object created from the WebUSB API that is
* expected to handle the transfer of data.
*/
getTransferInterface_(device) {
return this.getInterfaceWithClass_(device, 10);
}
/**
* Utility used to get any interface on the device with a given class number
* @param {Object} device the object for a device from the WebUSB API
* @param {Object} classNumber The class number you want to find
* @return {object} The interface Object created from the WebUSB API that is
* has the specified classNumber
*/
getInterfaceWithClass_(device, classNumber) {
let interfaceWithClass;
device.configuration.interfaces.forEach((deviceInterface) => {
deviceInterface.alternates.forEach((alternate) => {
if (alternate.interfaceClass === classNumber) {
interfaceWithClass = deviceInterface;
}
});
});
return interfaceWithClass;
}
/**
* Utility function to get an endpoint from the Tranfer Interface that
* has the given direction
* @param {String} direction A string either "In" or "Out" specifying the
* direction requested
* @return {object} The Endpoint Object created from the WebUSB API that is
* has the specified direction
*/
getDirectionEndpoint_(direction) {
let correctEndpoint;
this.transferInterface_.alternates.forEach((alternate) => {
alternate.endpoints.forEach((endpoint) => {
if (endpoint.direction == direction) {
correctEndpoint = endpoint;
}
});
});
return correctEndpoint;
}
}
/* an object to be used for starting the serial workflow */
const serial = {
requestPort: function() {
const filters = [
{classCode: 10},
];
return navigator.usb.requestDevice({'filters': filters})
.then(async (device) => {
const port = new SerialPort(device);
return port;
});
},
SerialPort: SerialPort,
getPorts: function() {
return navigator.usb.getDevices().then((devices) => {
const serialDevices = [];
devices.forEach((device) => {
if (SerialPort.isSerialDevice_(device)) {
serialDevices.push(new SerialPort(device));
}
});
return serialDevices;
});
},
};
/* eslint-disable no-undef */
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = serial;
}
exports.serial = serial;
}
|
$(document).ready(function() {
$('#div_for_img img').click(function(eventObject) {
if(eventObject.shiftKey){
var borderColor = '#cc0000';
}
else{
var borderColor = '#333333';
}
if($(this).attr('class')){
$(this).removeClass('myBorder');
$(this).css({'border' : 'none'});
}
else{
$(this).addClass('myBorder');
$(this).css({'border' : '4px solid' + borderColor});
}
});
}); // End of ready
|
$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("file:src/test/resources/feature/tests.feature");
formatter.feature({
"name": "Find a hotel",
"description": "",
"keyword": "Feature"
});
formatter.scenario({
"name": "Hotel searching and finding on the booking page",
"description": "",
"keyword": "Scenario"
});
formatter.step({
"name": "The booking page is loaded",
"keyword": "Given "
});
formatter.match({
"location": "BookingHomePage_Steps.openPage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "Enter Hotel Name And Click the Search Button",
"keyword": "When "
});
formatter.match({
"location": "BookingHomePage_Steps.searchTheHotel()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "The Hotel is displayed with the Rating Exceptional",
"keyword": "Then "
});
formatter.match({
"location": "BookingHomePage_Steps.hotelResults()"
});
formatter.result({
"status": "passed"
});
});
|
/* global module */
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
requirejs: {
default: {
options: {
name: "main",
wrapShim: true,
baseUrl: "../webroot/mengniu/assets/js/app",
mainConfigFile: "../webroot/mengniu/assets/js/app/config/config.js",
out: "../webroot/mengniu/assets/js/_app.js",
insertRequire: ['main'],
preserveLicenseComments: false
}
}
},
jst: {
default: {
options: {
templateSettings: {
interpolate: /\{\{(.+?)\}\}/g
},
prettify: true,
processName: function (filepath) {
var prefix = '../webroot/mengniu/assets/js/app/views/';
var suffix = '.html';
if (filepath.indexOf(prefix) == 0) {
filepath = filepath.substring(prefix.length);
}
if (filepath.lastIndexOf(suffix) == filepath.length - suffix.length) {
filepath = filepath.substring(0, filepath.length - suffix.length);
}
return filepath;
}
},
files: {
"../webroot/mengniu/assets/js/_views.js": ["../webroot/mengniu/assets/js/app/views/**/*.html"]
}
}
},
concat: {
options: {
separator: ';\n\n'
},
dist: {
src: ['../webroot/mengniu/assets/js/app/vendor/base/require.js', '../webroot/mengniu/assets/js/_views.js', '../webroot/mengniu/assets/js/_app.js'],
dest: '../webroot/mengniu/assets/js/app.js'
}
},
less: {
default: {
options: {
//paths: ["assets/css"],
cleancss: true,
modifyVars: {
//imgPath: '"http://mycdn.com/path/to/images"',
//bgColor: 'red'
}
},
files: {
"../webroot/mengniu/assets/css/style.css": "../webroot/mengniu/assets/css/style.less"
}
}
},
clean: {
options: { force: true },
default: ["../webroot/mengniu/assets/js/_app.js", "../webroot/mengniu/assets/js/_views.js"]
},
tmtTinyPng: {
default_options: {
options: {
},
files: [
{
expand: true,
src: ['*.png','*.jpg','*/*.png','*/*.jpg'],
cwd: '../webroot/mengniu/assets/images',
filter: 'isFile'
}
]
}
},
ziti: {
index: {
options: {
font: {
pattern: '\\.ttf$',
chars: '',
charsFilePattern: '\\.txt$'
},
subset: true,
optimize: true,
deleteCharsFile: false,
convert: false
},
files: {
'../webroot/mengniu/assets/font/out.ttf': [ '../webroot/mengniu/assets/font/RTWSYueGoG0v1-ExLightCom.ttf', '../webroot/mengniu/assets/font/num.txt' ],
//'../webroot/mengniu/assets/font/hyb1gjm_out.ttf': [ '../webroot/mengniu/assets/font/hyb1gjm.ttf', '../webroot/mengniu/assets/font/app_common.txt' ]
}
}
},
jsObfuscate: {
test: {
options: {
concurrency: 2,
keepLinefeeds: false,
keepIndentations: false,
encodeStrings: true,
encodeNumbers: true,
moveStrings: true,
replaceNames: true,
variableExclusions: [ '^_get_', '^_set_', '^_mtd_' ]
},
files: {
'../webroot/mengniu/assets/js/dest.js': [
'../webroot/mengniu/assets/js/app.js'
]
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-jst');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.loadNpmTasks('grunt-css-url-embed');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-tmt-tiny-png');
grunt.loadNpmTasks('grunt-ziti');
grunt.loadNpmTasks('js-obfuscator');
grunt.registerTask('default', ['requirejs', 'jst', 'concat', 'less', 'clean']);
};
|
import styled from 'styled-components';
import { montserrat } from '../fontFamily';
const Label = styled.div`
font-family: ${montserrat}, sans-serif;
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
color: #212121;
margin-bottom: 8px;
opacity: 0.5;
letter-spacing: 1px;
`;
export default Label;
|
export default {
'pie': '饼图', 'bar': '柱状图',
'line': '折线图', 'radar': '雷达图',
'gauge': '仪表盘', 'funnel': '漏斗图',
'rose': '玫瑰图', 'map': '地图'
}
|
import React, { Component } from 'react'
import lottie from 'lottie-web';
import { Link } from 'react-router-dom'
export default class LottieWeb extends Component {
componentDidMount() {
lottie.loadAnimation({
container: this.refJson, // the dom element that will contain the animation
renderer: 'svg',
loop: true,
autoplay: true,
path: 'https://labs.nearpod.com/bodymovin/demo/markus/halloween/markus.json' // the path to the animation json
});
}
render() {
return (
<div>
<div
style={{ width: '100px', height: '200px' }}
ref={(element) => { this.refJson = element }}>
</div>
<div>
<li>
<Link to='/'>home</Link>
</li>
</div>
</div>
)
}
}
|
var isSysLog = true;
var isDebug = false;
//var isDebug = true;
function sysLog(message) {
var sysLogPrefix = "SysLog :: ";
if(isSysLog) {
console.log(sysLogPrefix + message);
return true;
}
}
var powObj = {
base : undefined,
exponent : undefined,
result : undefined,
powInputState : undefined,
powComputeState : undefined,
// pow : function() {
//
// }
};
// Throw a random value ...
function getRandomSample(min, max) {
var randomValue = Math.floor((Math.floor(max) - Math.ceil(min)) * Math.random()) + Math.ceil(min);
return randomValue;
}
function parseInput(input) {
// var templateString = " -4 3";
/* If we'd like to split (ie. eliminate space-chars) ::
N.B. !!!! Skip the 1st empty-string El of an Array,
when the original input has the space-chars before the 1st parameter, called <base> !
*/
// var reSplitLiteral = /\s+/;
// If we'd like to match
// Here are 2 'capturing parentheses' : base and exponent
var reMatchLiteral = /\s*((?:\+|-)?\d+)\s+(\d+)\s*/;
// var inputList = templateString.split(reSplitLiteral);
// debugger;
var inputList = input.match(reMatchLiteral);
if(!inputList) {
console.log('POW-service : Ooops ! Wrong Parameters are provided.\n\
There is nothing to compute. \n\
Run the POW-script again (e.g. via Refresh/F5) !!!');
powObj.powInputState = false;
} else {
powObj.base = parseInt(inputList[1]);
powObj.exponent = parseInt(inputList[2]);
powObj.powInputState = true;
}
sysLog("powObj.base = " + powObj.base + "" + " powObj.exponent = " + powObj.exponent);
return powObj.powInputState;
// var inputList = templateString.match(reMatchLiteral);
// console.log(inputList);
}
function powInput(powArray) {
var autoInput = false;
// var autoInput = true;
if(isDebug) {
debugger;
}
var powSample_base = getRandomSample(0, 10000),
powSample_exponent = getRandomSample(0, 1000),
powSample = powSample_base + ' ' + powSample_exponent;
var input;
if(!autoInput) {
input = window.prompt("POW-service { pow(<BASE>, <EXPONENT>) } : \n\
Please, enter the BASE and EXPONENT values to compute the POW !\n\
Example: " + powSample,
""); // set the default value for the Prompt's input-element
} // eoIF autoInput
else {
sysLog("An input via PROMPT-dialog is off !\n\
Let's get RANDOM-values for <BASE>, and <EXPONENT> {" + powSample + "}");
input = powSample;
}
switch(input) {
// null, '' (i.e. <empty_string>) => Handle as nothing to analyze, and finish the POW-task
case null: // "Cancel"-state of the PROMPT Modal-dialog but the Safari browser behaviour
case '':
console.log('POW-service : There is nothing to compute. \nRun the POW-script again (e.g. via Refresh/F5)');
return false;
default:
if(parseInput(input)) {
return true;
} else
return false;
}
}
// Compute th POW-function
function powCompute() {
// my realization is based on statements of < www.ecma-international.org/ecma-262/6.0/#sec-math.pow >
var base = powObj.base,
exponent = powObj.exponent,
result;
if(exponent === 0) {
return powObj.result = 1;
}
if(base === 0) {
if(exponent > 0)
return powObj.result = 0;
}
for( var cntr = 1, result = base; cntr < exponent; cntr++ ) {
result *= base;
}
powObj.result = result;
powObj.powComputeState = true;
sysLog("{ powCompute base: " + base + " exponent: " + exponent +" } cntr = " + cntr + " result = " + result);
}
// Output the result of POW-function execution
function powOutput() {
console.log("POW-service : The result of raising <base = " + powObj.base + "> to the <power = " + powObj.exponent + ">\n\
EQUALS <" + powObj.result + ">");
}
// get values of base and exponent
powObj.powInputState = powInput();
if(powObj.powInputState) {
// Compute the result of POW-function
powCompute();
}
if(powObj.powComputeState) {
powOutput();
}
// Finish the execution
|
import { parseSpecValue } from "../../utils/sku"
import { Cart } from "../../model/cart"
// components/car-item/index.js
const cart = new Cart()
Component({
/**
* 组件的属性列表
*/
properties: {
cartItem:Object
},
observers:{
cartItem:function(cartItem){
if(!cartItem){
return
}
const specStr = parseSpecValue(cartItem.sku.specs)
const discount = cartItem.sku.discount_price ?true:false
const soldOut = cart.isSoldOut(cartItem)
const online = cart.isOnline(cartItem)
this.setData({
specStr,
discount,
soldOut,
online,
stock: cartItem.sku.stock,
skuCount: cartItem.count,
isChecked:cartItem.checked
})
}
},
/**
* 组件的初始数据
*/
data: {
specStr:String,
discount:Boolean,
soldOut:Boolean,
online:Boolean,
stock: 99,
skuCount:1,
isChecked:true
},
/**
* 组件的方法列表
*/
methods: {
onDelete(){
const skuId = this.properties.cartItem.skuId
cart.removeItem(skuId)
this.setData({
cartItem:null
})
this.triggerEvent("deleteItem",{skuId})
},
selectCheckBox(e){
const checked = e.detail.checked
this.setData({
isChecked:checked
})
cart.checkItem(this.properties.cartItem.skuId)
this.triggerEvent("checkItem",{})
},
onChangeCount(e){
const count = e.detail.count
const skuId = this.properties.cartItem.skuId
cart.replcaSkuCount(skuId,count)
this.triggerEvent("changeCount",{
count
})
},
todetail(){
const spuId = this.properties.cartItem.sku.spu_id
wx.navigateTo({
url: `/pages/detail/index?pid=${spuId}`
})
}
}
})
|
var gulp = require( 'gulp' ),
autoprefixer = require( 'gulp-autoprefixer' ),
concat = require( 'gulp-concat' ),
minifycss = require( 'gulp-minify-css' ),
csscomb = require( 'gulp-csscomb' ), // Settings in file .csscomb.json
notify = require( 'gulp-notify' ),
plumber = require( 'gulp-plumber' ),
sourcemaps = require( 'gulp-sourcemaps' ),
// Load config file
config = require( '../gulp-tasks/config' ).styles,
size = config.size;
gulp.task('styles', function() {
return gulp.src( config.src )
.pipe( plumber( {
errorHandler: config.notifyOnError
} ) )
.pipe( size.s )
.pipe( size.sg )
.pipe( sourcemaps.init( ) )
.pipe( autoprefixer( config.autoprefixer ) )
.pipe( concat( config.name ) )
.pipe( csscomb( ) )
.pipe( minifycss( config.minifycss ) )
.pipe( sourcemaps.write( config.srcMapDest ) )
.pipe( gulp.dest( config.dest ) )
.pipe( notify( {
title: config.notifyOnSucess.title,
message: function( ) {
return config.notifyOnSucess.message + ' ' + size.totalSizeMessage + ' ' + size.s.prettySize + ' ' + size.gzipMessage + ' ' + size.sg.prettySize;
},
onLast: true
} ) );
} );
|
import axios from 'axios'
class CourseService {
async getAllCoursesAsync() {
return await axios.get('https://demonodejsserver.herokuapp.com/api/course');
}
static getAllCourses() {
return axios.get('https://demonodejsserver.herokuapp.com/api/course');
}
}
export default CourseService;
|
import axios from "axios";
export default async(uname, hourlySalary = 45) => {
let data
let hoursCounter = { morning: 0, noon: 0, night: 0, fridayMorning: 0, fridayNoon: 0 }
let salary = 0
let totalHours = 0
await axios.get(`/get-user-shifts/${uname}`)
.then(res => {
data = res.data
console.log(data)
})
.catch(err => {
console.log(err)
})
const currentMonth = new Date().getMonth()
data = data.filter(item => (new Date(item.end).getMonth() === currentMonth && new Date(item.end).getDay() < 24 && new Date(item.end).getDay() >= 1)
|| (new Date(item.end).getMonth() === currentMonth - 1 && new Date(item.end).getDay() >= 25))
console.log(data)
for(let i = 0 ; i < data.length ; i++) {
totalHours += Math.abs(Date.parse(data[i].end) - Date.parse(data[i].start)) / 3600000
salary += shiftSalary(data[i].start, data[i].end, hourlySalary, hoursCounter)
}
return {totalHours, salary, hoursCounter}
}
const shiftSalary = (dateOne, dateTwo, hourlySalary, hoursCounter) => {
const dateOneObj = new Date(dateOne);
const dateTwoObj = new Date(dateTwo);
let isCaclculated = false
//convert time from milisec to hours
const totalHours = Math.abs(dateTwoObj.getTime() - dateOneObj.getTime()) / 3600000
console.log(totalHours)
let sum = 0
let addittionlaHours = 0
if(totalHours > 8)
addittionlaHours = totalHours - 8
let j = 1, i = dateOneObj.getHours()
console.log(i)
for (; i < totalHours + dateOneObj.getHours() - addittionlaHours ; i++, j++) {
if ( dateOneObj.getDay() === 6 ) {
if ( i > 7 && i <= 15) {
sum += (hourlySalary * 1.25)
if (!isCaclculated) {
hoursCounter.fridayMorning += totalHours
isCaclculated = true
}
}
else if ( i > 15 && i <= 23) {
sum += (hourlySalary * 1.5)
if (!isCaclculated) {
hoursCounter.fridayNoon += totalHours
isCaclculated = true
}
}
}
else {
if ( i >= 23 || i < 7) {
sum += (hourlySalary * 1.5)
if (!isCaclculated) {
hoursCounter.night += totalHours
isCaclculated = true
}
}
else {
sum += hourlySalary
if ( i >= 7 && i < 15 && !isCaclculated){
hoursCounter.morning +=totalHours
isCaclculated = true
}
else if (!isCaclculated) {
hoursCounter.noon += totalHours
isCaclculated = true
}
}
}
}
//Calculate addittional hours
if (j > 8 && j <=10) {
sum += (hourlySalary * 1.25 * addittionlaHours)
}
else if (j > 10 && j <= 12) {
sum += hourlySalary * 1.25 * 2 + hourlySalary * 1.5 * (addittionlaHours - 2)
}
return sum
}
// const
|
window.addEventListener("keydown", doKeyDown, false);
window.addEventListener("keyup", doKeyUp, false);
var game= {
stage: null,
type: null,
},
messages = {
paddle: {
move: false,
direction: null,
},
messag: null,
pName : null,
gType : null,
},
gameTypes = {
opponents: "opponents",
friends: "friends"
};
var link = document.querySelector('link[rel=import]');
var content = link.import.querySelector('#main');
var applicationID = '06A159A5';
var namespace = 'urn:x-cast:ping-pong';
var session = null;
/**
* Call initialization for Cast
*/
if (!chrome.cast || !chrome.cast.isAvailable) {
setTimeout(initializeCastApi, 1000);
}
/**
* initialization
*/
function initializeCastApi() {
var sessionRequest = new chrome.cast.SessionRequest(applicationID);
var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
sessionListener,
receiverListener);
chrome.cast.initialize(apiConfig, onInitSuccess, onError);
};
/**
* initialization success callback
*/
function onInitSuccess() {
console.log("onInitSuccess");
}
/**
* initialization error callback
*/
function onError(message) {
console.log("onError: "+JSON.stringify(message));
}
/**
* generic success callback
*/
function onSuccess(message) {
// console.log("onSuccess: "+message);
console.log('this');
}
/**
* callback on success for stopping app
*/
function onStopAppSuccess() {
console.log('onStopAppSuccess');
}
/**
* session listener during initialization
*/
function sessionListener(e) {
console.log('New session ID:' + e.sessionId);
session = e;
session.addUpdateListener(sessionUpdateListener);
session.addMessageListener(namespace, receiverMessage);
}
/**
* listener for session updates
*/
function sessionUpdateListener(isAlive) {
var message = isAlive ? 'Session Updated' : 'Session Removed';
message += ': ' + session.sessionId;
console.log(message);
if (!isAlive) {
session = null;
}
};
/**
* utility function to log messages from the receiver
* @param {string} namespace The namespace of the message
* @param {string} message A message string
*/
function receiverMessage(namespace, message) {
console.log("receiverMessage: "+namespace+", "+message);
message = JSON.parse(message);
game = message.game;
player = message.player;
console.log(game);
if(game.stage != null)
{
document.querySelector('#major').style.display = "none";
if (document.querySelector('#main')){
document.querySelector('#main').style.display = "block";
} else {
document.body.appendChild(content.cloneNode(true));
}
document.querySelector('#stage').innerHTML = game.stage;
document.querySelector('#state').innerHTML = player.state;
document.querySelector('#paddle').innerHTML = player.paddle.position;
document.querySelector('#pName').innerHTML = document.getElementById("name").value;
} else {
document.querySelector('#major').style.display = "block";
document.querySelector('#main').style.display = "none";
}
};
/**
* receiver listener during initialization
*/
function receiverListener(e) {
if( e === chrome.cast.ReceiverAvailability.AVAILABLE) {
console.log("receiver found");
}
else {
console.log("receiver list empty");
}
}
/**
* stop app/session
*/
function stopApp() {
session.stop(onStopAppSuccess, onError);
}
/**
* send a message to the receiver using the custom namespace
* receiver CastMessageBus message handler will be invoked
* @param {string} message A message string
*/
function sendMessage(message) {
console.log(message);
if (session!=null) {
session.sendMessage(namespace, message, onSuccess.bind(this, "Message sent: " + message), onError);
}
else {
chrome.cast.requestSession(function(e) {
session = e;
session.sendMessage(namespace, message, onSuccess.bind(this, "Message sent: " + message), onError);
}, onError);
}
}
/**
* append message to debug message window
* @param {string} message A message string
*/
// function console.log(message) {
// console.log(JSON.parse(message));
// };
/**
* utility function to handle text typed in by user in the input field
*/
function update() {
sendMessage(document.getElementById("input").value);
}
/**
* handler for the transcribed text from the speech input
* @param {string} words A transcibed speech string
function transcribe(words) {
sendMessage(words);
}*/
function doKeyDown (e) {
if (e.keyCode === 65){
if(messages.paddle.direction !=="left")
left();
}else if (e.keyCode === 68){
if(messages.paddle.direction !== "right")
right();
}
};
function doKeyUp (e) {
if (e.keyCode === 65) {
stopMove();
}
if (e.keyCode === 68){
stopMove();
}
}
function connection () {
this.pName = document.getElementById("name").value;
if(session !== null && pName !== "") {
messages.pName = pName;
messages.messag = "connect";
sendMessage(messages);
} else alert("Выберете Chromecast и введите имя!");
}
function left () {
messages.paddle.move = true;
messages.paddle.direction = "left";
messages.messag = "move";
sendMessage(messages);
}
function right () {
console.log("1");
messages.paddle.move = true;
messages.paddle.direction = "right";
messages.messag = "move";
sendMessage(messages);
}
function stopMove () {
messages.paddle.move = false;
messages.paddle.direction = "";
messages.messag = "move";
sendMessage(messages);
}
function pause () {
messages.messag = "pause";
sendMessage(messages);
}
function start (){
this.gType = document.getElementById("type").value;
console.log(gType);
messages.gType = gType;
messages.messag = "game";
sendMessage(messages);
}
function ready () {
if(document.getElementById("btnReady").value === "Ready") {
messages.messag = "ready";
document.getElementById("btnReady").value = "Unready";
} else if(document.getElementById("btnReady").value === "Unready") {
messages.messag = "unready";
document.getElementById("btnReady").value = "Ready";
}
sendMessage(messages);
}
function exit () {
messages.messag = "exit";
sendMessage(messages);
}
|
export const formatarParaReal = (str) => {
return `R$ ${str}`;
}
const meses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
export const obterMesDeDate = (date) => {
return meses[date.getMonth()];
}
export const obterMes = (int) => meses[int];
const formatadorDeString = { formatarParaReal, obterMesDeDate, obterMes };
export default formatadorDeString;
|
'use strict';
angular.module('mockedSitesJSON', [])
.value('mockedSites',
[
{
"id":1,
"siteName":"GizMag",
"siteUrl":"www.gizmag.com",
"description":"This is the description for Gizmag",
"categoryIds":[
2
]
},
{
"id":2,
"siteName":"Ebay",
"siteUrl":"www.ebay.com.au",
"description":"This is the description for ebay",
"categoryIds":[
1
]
},
{
"id":3,
"siteName":"Robs UI Tips",
"siteUrl":"www.awesomeui.com.au",
"description":"This is the description for the best site in the world. It is the best:)",
"categoryIds":[
4,
3
]
},
{
"id":4,
"siteName":"Table Tennis Tips - How to not come runners up",
"siteUrl":"www.ttt.com",
"description":"This is the description for Table Tennis Tips",
"categoryIds":[
1,
2,
3,
4
]
}
]
);
|
import React from 'react';
import {View, Dimensions, StatusBar, Platform, SafeAreaView} from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
const MainCard = (props) => {
const {height, width} = Dimensions.get('window');
const statusBarHeight = Platform.OS == 'android' ? StatusBar.currentHeight : 0;
return (
<KeyboardAwareScrollView>
<SafeAreaView
style={[style.containerStyle,props.style, {height: height - statusBarHeight}]}
>
{props.children}
</SafeAreaView>
</KeyboardAwareScrollView>
)
}
const style = {
containerStyle: {
flex:1,
backgroundColor: '#FFFFFF',
flexDirection: 'column',
justifyContent: 'flex-start',
}
}
export {MainCard};
|
import React, { Component } from "react";
import Nav from "./Nav";
import JokesPrev from "./JokesPrev";
import RoutinesPrev from "./RoutinesPrev";
import Paper from "@material-ui/core/Paper";
class ProfilePage extends Component {
render() {
const user = this.props.user;
const firstName = user.first_name;
const lastName = user.last_name;
return (
<Paper elevation={20} className="container">
<div className="nav_bar_container">
<Nav user={this.props.user} logout={this.props.logout} />
</div>
<h1 className="profile_greeting">
Welcome to your profile page, {firstName} {lastName} !
</h1>
<JokesPrev />
<RoutinesPrev />
</Paper>
);
}
}
export default ProfilePage;
|
import {
FIRST_NAME_CHANGED, LAST_NAME_CHANGED, EMAIL_CHANGED_SIGNUP,
PASSWORD_CHANGED_SIGNUP, PASSWORD_RETYPE_CHANGED, DATE_DAY_CHANGED,
DATE_MONTH_CHANGED, DATE_YEAR_CHANGED, GENDER_CHANGED, TERMS_CHANGED,
SIGN_UP, SIGN_UP_SUCCESS, SIGN_UP_FAIL
} from './types';
export const firstNameChanged = (text) => {
return {
type: FIRST_NAME_CHANGED,
payload: text
};
}
export const emailChangedSignUp = (text) => {
return {
type: EMAIL_CHANGED_SIGNUP,
payload: text
};
}
export const lastNameChanged = (text) => {
return {
type: LAST_NAME_CHANGED,
payload: text
};
}
export const passwordChangedSignUp = (text) => {
return {
type: PASSWORD_CHANGED_SIGNUP,
payload: text
};
}
export const passwordRetypeChanged = (text) => {
return {
type: PASSWORD_RETYPE_CHANGED,
payload: text
};
}
export const dateDayChanged = (text) => {
return {
type: DATE_DAY_CHANGED,
payload: text
};
}
export const dateMonthChanged = (text) => {
return {
type: DATE_MONTH_CHANGED,
payload: text
};
}
export const dateYearChanged = (text) => {
return {
type: DATE_YEAR_CHANGED,
payload: text
};
}
export const genderChanged = (text) => {
return {
type: GENDER_CHANGED,
payload: text
};
}
export const termsChanged = (text) => {
return {
type: TERMS_CHANGED,
payload: text
};
}
export const SignUpAction = (firstName, lastName,email, password, day, month, year, gender) => {
return (dispatch) => {
dispatch({ type: SIGN_UP })
fetch('https://mobilebackend.turing.com/customers', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: firstName + " " + lastName, email: email, password: password })
})
.then((response) => response.json())
.then((responseJson) => {
//do something
if (responseJson.error) {
SignUpFail(dispatch, responseJson.error)
}
else {
SignUpSuccess(dispatch, responseJson)
}
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
}
}
const SignUpFail = (dispatch, error) => {
dispatch({
type: SIGN_UP_FAIL,
payload: error
});
alert("signup fail");
}
const SignUpSuccess = (dispatch, responseJson) => {
dispatch({
type: SIGN_UP_SUCCESS,
payload: responseJson
});
alert("signup success");
}
|
var exception__manager__8h_8js =
[
[ "exception_manager_8h", "exception__manager__8h_8js.html#a26a9fcc217ba377fc6982199b35c3557", null ]
];
|
import { combineReducers } from "redux";
const initialState = {
user: "",
userRepos: {},
userCommits: {}
};
function data(state = initialState, action) {
switch (action.type) {
case "HANDLE_USER": {
return {
...state,
user: action.user
};
}
case "HANDLE_USER_REPOS": {
return {
...state,
userRepos: action.data
};
}
case "HANDLE_USER_COMMITS": {
return {
...state,
userCommits: action.commits
};
}
default:
return state;
}
}
export default combineReducers({ data });
|
const bcrypt = require('bcryptjs');
const Sequelize = require('sequelize');
const { db } = require('../configuration/db');
const sequelize = db();
const User = sequelize.define('user', {
firstName: Sequelize.STRING,
lastName: Sequelize.TEXT,
email: Sequelize.TEXT,
practice: Sequelize.TEXT,
roles: Sequelize.TEXT,
password: Sequelize.TEXT,
});
User.beforeCreate(async (user) => {
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt); // eslint-disable-line
user.email = user.email.toLowerCase(); // eslint-disable-line
return user;
});
// Create the table if it doesn't exist
// TO-DO
User.sync();
// User.sync({force: true});
module.exports = User;
|
exports.createArray = function(){
var collection = new MyArray(arguments);
return collection;
};
exports.rotateByLast = function(array, positions){
var arrayLength = array.length - 1;
var midElement = array.length - positions;
var tempArr = [];
tempArr = array.reverse(midElement, arrayLength);
tempArr = array.reverse(0, midElement-1, tempArr);
tempArr = tempArr.reverse(0, tempArr.length);
return tempArr;
};
function MyArray(){
var customArray = Object.create(Array.prototype);
customArray = Array.apply(this, arguments[0]);
customArray.reverse = function(startIndex, endIndex, tempArr){
var arrayLengthToReverse = startIndex;
var tempArr = tempArr || [];
for(var i=endIndex;i >= startIndex;i--){
tempArr[arrayLengthToReverse] = this[i];
arrayLengthToReverse++;
}
return tempArr;
};
return customArray;
}
|
/**
* Copyright 2019-2020 ForgeRock AS. All Rights Reserved
*
* Use of this code requires a commercial software license with ForgeRock AS.
* or with one of its affiliates. All use shall be exclusively subject
* to such license between the licensee and ForgeRock AS.
*/
/* eslint-disable import/no-extraneous-dependencies */
import BootstrapVue from 'bootstrap-vue';
import { createLocalVue, shallowMount } from '@vue/test-utils';
import EditResource from './index';
const localVue = createLocalVue();
localVue.use(BootstrapVue);
describe('EditResource.vue', () => {
const $route = {
path: '/test',
meta: {},
params: {
resourceName: 'test',
resourceType: 'test',
resourceId: 'test',
},
};
let wrapper;
beforeEach(() => {
jest.spyOn(EditResource, 'mounted')
.mockImplementation(() => { });
wrapper = shallowMount(EditResource, {
localVue,
stubs: {
'router-link': true,
ToggleButton: true,
},
mocks: {
$route,
$t: () => {},
$store: {
state: {
userId: 'foo',
UserStore: {
adminUser: false,
},
},
},
},
});
});
afterEach(() => {
wrapper = null;
});
it('EditResource page loaded', () => {
expect(wrapper.name()).toBe('EditResource');
expect(wrapper).toMatchSnapshot();
});
it('Format display data', () => {
const schema = {
icon: 'fa-test',
order: ['country', 'userName', 'sn', 'email', 'contractor', 'manager'],
required: ['userName'],
properties: {
userName: {
type: 'string',
title: 'Username',
viewable: true,
},
sn: {
type: 'string',
title: 'Last Name',
viewable: true,
},
email: {
type: 'string',
title: 'Email',
viewable: true,
},
contractor: {
type: 'boolean',
title: 'Contractor',
viewable: true,
},
country: {
type: 'string',
title: 'Country',
viewable: true,
},
manager: {
type: 'relationship',
title: 'Manager',
viewable: true,
},
},
};
const privilege = {
UPDATE: {
allowed: true,
properties: ['userName', 'contractor', 'sn', 'email', 'manager'],
},
DELETE: {
allowed: true,
},
VIEW: {
allowed: true,
properties: ['userName', 'country', 'sn', 'email'],
},
};
const resourceDetails = {
userName: 'test',
email: 'test@test.com',
};
wrapper.vm.generateDisplay(schema, privilege, resourceDetails);
expect(wrapper.vm.icon).toBe('check_box_outline_blank');
expect(wrapper.vm.formFields.contractor).toBe(false);
// make sure the view and update properties are merged together and in the correct order
expect(wrapper.vm.displayProperties.length).toBe(6);
expect(wrapper.vm.displayProperties[0].key).toBe('country');
// set relationshipProperties
wrapper.vm.relationshipProperties = wrapper.vm.getRelationshipProperties(schema, privilege);
expect(wrapper.vm.relationshipProperties).toEqual({
manager: {
type: 'relationship',
title: 'Manager',
key: 'manager',
propName: 'manager',
readOnly: false,
disabled: false,
value: '',
viewable: true,
},
});
expect(wrapper.vm.buildResourceUrl()).toEqual('test/test/test?_fields=*,manager/*');
});
});
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import '../../../public/css/footer.css';
export default class Footer extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div className="footer">
<div className="footer-left col-12 col-md-4 mb-4 text-center" style={{ transform: 'translate(-6px, 3px)'}}>
<div className="col-12">
<h3>NALA KIDS</h3>
</div>
<p className="company-name col-12">
©NALAKIDS
<div>
Todos los derechos reservados
</div>
</p>
</div>
<div className="footer-center col-12 col-md-4 p-0 mb-4 text-center" style={{ transform: 'translate(-22px, -1px)'}}>
<div className="d-flex justify-content-center">
<i class="fas fa-map-marker-alt" style={{ transform: 'translate(37px, 6px)'}}></i>
<p>
<span>Rivadavia 108</span>
Quilmes, Buenos Aires
</p>
</div>
<div className="d-flex justify-content-center">
<i class="fas fa-map-marker-alt" style={{ transform: 'translate(37px, 6px)'}}></i>
<p>
<span>Constitución 328</span>
San Fernando, Buenos Aires
</p>
</div>
<div className="d-flex justify-content-center">
<i class="fas fa-phone mr-3" style={{ transform: 'translate(20px, 5px)'}}></i>
<p>
<span>(+54 9 11) 6274-3761</span>
</p>
</div>
</div>
<div className="footer-right col-12 col-md-4 p-0 text-center">
<div className="col-12 mb-2" style={{ color: 'rgb(60, 110, 251)', fontSize:'20px'}}>Sobre NALAkids</div>
NalaKids es una empresa con una trayectoria de mas de 30 años dedicada a la fabricacion de indumentaria para chicos.
<div className="footer-icons d-flex justify-content-center mt-3">
<a href="https://www.facebook.com/Nala-Quilmes-1096349540445839/?ref=br_rs" target="_blank" className="icon-footer"><i className="fab fa-facebook-f"></i></a>
<a href="https://www.instagram.com/nalaquilmes/?fbclid=IwAR3Zy-k9ihYTBbi3DurzfMn8s_xQGcYcIZ0HOJ68knEjGVg4xVWybmd4kik" target="_blank" className="icon-footer"><i className="fab fa-instagram"></i></a>
<a href="https://wa.me/5491162743761?text=Hola%20Nala%20queria%20realizar%20una%20consulta" target="_blank" className="icon-footer"><i className="fab fa-whatsapp"></i></a>
</div>
</div>
</div>
);
}
}
if (document.getElementById('footer')) {
ReactDOM.render(<Footer />, document.getElementById('footer'));
}
|
export { resetButtonColour } from "./resetButtonColour"
|
import React, {Component, Fragment} from 'react';
import styled, { css, keyframes } from 'styled-components';
import Plot from 'react-plotly.js';
import data from '../data/realEstate';
import dataCharter from '../data/realEstateCharter';
import timeSpan from '../data/timeSpan'
import { thresholdScott } from 'd3';
import oc from 'open-color';
class LinearMap extends Component {
state = {
selectedArea: this.props.selectedArea,
preArea: this.props.selectedArea,
isNew: false,
layout: {
autosize: false,
width: 420,
height: 280,
margin: {
l: 70,
r: 10,
b: 40,
t: 30,
pad: 4,
},
xaxis: {
color: '#dee2e6'
},
yaxis: {
autorange: true,
color: '#dee2e6',
tickformat: ',d',
},
paper_bgcolor: '#333333',
plot_bgcolor: '#333333',
showlegend: true,
legend: {
orientation: "h",
font: {
size: 10,
color: '#dee2e6'
},
bgcolor: '#333333',
}
}
}
componentDidMount() {
const valueArray = data[this.props.selectedArea];
const valueCArray = dataCharter[this.props.selectedArea];
const maxY = Math.max.apply(null, valueArray);
const minY = Math.min.apply(null, valueCArray);
this.setState({
data: {
x: timeSpan.date,
y: valueArray,
type: 'scatter',
name: "매매가",
mode: 'lines',
line: {
color: '#6741d9',
width: 3
}
},
dataC: {
x: timeSpan.date,
y: valueCArray,
type: 'scatter',
name: "전세가",
mode: 'lines',
line: {
color: '#c2255c',
width: 3
}
},
})
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.selectedArea !== prevState.selectedArea) {
// const transition = {
// duration: 2000,
// easing: 'elastic-in'
// }
return {
selectedArea: nextProps.selectedArea,
preArea: prevState.selectedArea,
isNew: !prevState.isNew,
layout: {
// transition: transition,
// frame: {duration: 2000, redraw: false},
autosize: false,
width: 420,
height: 280,
margin: {
l: 70,
r: 10,
b: 40,
t: 30,
pad: 4,
},
xaxis: {
color: '#dee2e6'
},
yaxis: {
autorange: true,
color: '#dee2e6',
tickformat: ',d',
},
paper_bgcolor: '#333333',
plot_bgcolor: '#333333',
showlegend: true,
legend: {
orientation: "h",
font: {
size: 10,
color: '#dee2e6'
},
bgcolor: '#333333',
}
},
data: {
x: timeSpan.date,
y: data[nextProps.selectedArea],
type: 'scatter',
name: "매매가",
mode: 'lines',
line: {
color: '#6741d9',
width: 3
}
},
dataC: {
x: timeSpan.date,
y: dataCharter[nextProps.selectedArea],
type: 'scatter',
name: "전세가",
mode: 'lines',
line: {
color: '#c2255c',
width: 3
}
}
}
}
return null
}
render() {
const { data, dataC, layout, isNew, preArea } = this.state;
const { selectedArea } = this.props;
const isAnew = selectedArea !== preArea ? true : false;
return(
<Container isNew={isNew} isAnew={isAnew}>
<div className="divContainer">
<div className='infoText'>
{selectedArea} 매매/전세가 추이 <span>[단위: 천원]</span>
</div>
<Plot
data={[data, dataC]}
layout={layout}
graphDiv="graph"
/>
</div>
</Container>
)
}
}
export default LinearMap;
const fadeIn = keyframes`
0% {opacity: 0;}
100% {opacity: 1;}
`;
const Container = styled.div`
@keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
.divContainer {
animation-duration: 2s;
animation-name: fadeIn;
${props => {
if(props.isNew) {
return css`
animation-name: ${fadeIn};
animation-duration: 2s;
`
}
}}
${props => {
if(props.isNew === false) {
return css`
animation-name: ${fadeIn};
animation-duration: 2s;
`
}
}}
}
.infoText {
width: 100%;
text-align:left;
padding-left: 15px;
padding-top: 15px;
font-size: 17px;
color: ${oc.gray[2]};
font-family: 'Noto Sans KR';
span {
font-size: 12px;
}
}
`
|
const imgUrl = "https://dog.ceo/api/breeds/image/random/4"
const breedsUrl = 'https://dog.ceo/api/breeds/list/all'
const dogsDiv = document.querySelector("#dog-image-container")
const dogBreedsUl = document.querySelector("#dog-breeds")
const breedDropMenu = document.querySelector("#breed-dropdown")
// Instead of DOM Content Loaded this program uses defer in the HTML Script Tags
// The fetches triggered upon page load are put inside of functions
// Both the random 4 dogs and breeds list fetches are manually called in the code below
fetchDogs()
function fetchDogs() {
fetch(imgUrl)
.then(response => response.json())
.then(addDogsToDom)
}
function addDogsToDom(data) {
data.message.forEach(dog => {
let dogImg = document.createElement("img")
dogImg.src = `${dog}`
dogsDiv.appendChild(dogImg)
})
fetchBreeds()
}
function fetchBreeds() {
fetch(breedsUrl)
.then(response => response.json())
.then(addBreedsToDom)
}
function addBreedsToDom(data) {
Object.keys(data.message).forEach(breed => {
let dogBreedLi = document.createElement("li")
dogBreedLi.innerHTML = breed
dogBreedsUl.appendChild(dogBreedLi)
})
}
// Dog Breed List Item Color Change Event Listener On Click
dogBreedsUl.addEventListener("click", changeBreedColor)
function changeBreedColor(event) {
event.target.style.color = "blue"
}
// Filter Breeds by Letter
breedDropMenu.addEventListener("change", filterBreeds);
function filterBreeds(event) {
const breedLis = document.querySelectorAll("li");
breedLis.forEach(breed => {
breed.style.dislay = "list-item";
if (breed.innerText[0] !== event.target.value) {
breed.style.display = "none";
}
})
}
|
// ios内
export function isIOS() {
return true
}
// 安卓内
export function isAndroid() {
return true
}
// 微信内
export function isWeChat() {
return true
}
// 叮叮内
export function isDingDing() {
return true
}
// 混合app
export function isHybrid(){
return false
}
// 移动网页
export function isWap(){
return false
}
// pc网页
export function isWeb(){
return false
}
|
const { User } = require('../models/user');
const _ = require('lodash');
const validateRegisterInput = require('../validation/register');
const validateLoginInput = require('../validation/login');
exports.signup = (req, res, next) => {
const body = _.pick(req.body, ['email', 'password', 'confirmation'])
const newUser = new User(body);
newUser.generateAuthToken();
newUser.save()
.then(user => res.json(user.auth.token))
.catch(e => {
let { errors, isValid } = validateRegisterInput(body, e)
if (!isValid) {
return res.status(400).json(errors);
} else {
return res.status(500).json('please try again')
}
})
}
exports.login = (req, res, next) => {
let body = _.pick(req.body, ['email', 'password'])
User.verifyLogin(body.email, body.password)
.then(user => {
console.log(user)
let token = user.generateAuthToken()
user.update({
$set: {
auth: {
token
}
}
}).then(() => res.json(token))
.catch(e => {
console.log(e);
})
})
.catch(verifyError => {
let { errors, isValid } = validateLoginInput(body, verifyError)
if (!isValid) {
return res.status(400).json(errors)
}
})
}
// ________________________________________________________________________
// WITHOUT PASSPORT:
// // const {authenticate} = require('../middleware/authenticate');
// POST /USERS:
// exports.signup = (req, res, next) => {
// const body = _.pick(req.body, ['email', 'password'])
// const newUser = new User(body);
// newUser.generateAuthToken();
// newUser.save()
// .then(user => res.json(user.tokens[0].token))
// .catch(e => res.status(400).send(e))
// }
// // GET /users/me (PRIVATE)
//
// app.get('/users/me', authenticate, (req, res) => {
// var userName = req.user
// res.render(views + '/user', {name : userName});
// });
// // POST /users/login
// app.post('/users/login', (req, res) => {
// body = _.pick(req.body, ['email', 'password']);
// User.findByCredentials(body.email, body.password).then((user) => {
// return user.generateAuthToken().then((token) => {
// res.header('x-auth', token).send(user);
// })
// }).catch((e) => {
// res.status(400).send();
// })
// });
// // DELETE /users/me/token
// app.delete('/users/me/token', authenticate, (req, res) => {
// req.user.removeToken(req.token).then(() => {
// res.status(200).send();
// }), () => {
// res.satus(400).send();
// }
// });
// }
|
'use strict';
describe('frame', () => {
let frame;
beforeEach( () => {
frame = new Frame();
});
it('has starting number of 10 pins', () => {
expect(frame.pins).toEqual(10);
});
});
|
import { motion } from 'framer-motion'
import tw, { styled } from 'twin.macro'
export default function Button(props) {
return (
<ButtonWrapper
css={[props.disabled && tw`opacity-50 cursor-not-allowed`]}
{...props}
/>
)
}
const ButtonWrapper = styled(motion.button)`
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
font-weight: 600;
border: 2px solid var(--border-color);
border-radius: 4px;
background: var(--brown);
&:focus {
outline: none;
background: var(--color-highlight-secondary);
color: white;
}
`
|
$(document).ready(function () {
"use strict";
var av_name = "RemoveUnitFS";
var av = new JSAV(av_name,);
var Frames = PIFRAMES.init(av_name);
var arrow = String.fromCharCode(8594);
var grammar = "[[\"S\",\"→\",\"AB\"],\
[\"A\",\"→\",\"B\"],\
[\"B\",\"→\",\"Bb\"],\
[\"B\",\"→\",\"C\"],\
[\"C\",\"→\",\"A\"],\
[\"C\",\"→\",\"c\"],\
[\"C\",\"→\",\"Da\"],\
[\"D\",\"→\",\"A\"]]";
var grammarArray = JSON.parse(grammar);
var grammarMatrix = new GrammarMatrix( av,grammarArray, {style: "table", left: 10, top: 45});
grammarMatrix.hide();
var grammarMatrix2 = new GrammarMatrix( av,null, {style: "table", left: 250, top: 45});
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.createRow(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.productions.push(["", arrow, ""]);
grammarMatrix2.modifyProduction(0,0,"$S$");
grammarMatrix2.modifyProduction(0,2,"$AB$");
grammarMatrix2.modifyProduction(1,0,"$B$");
grammarMatrix2.modifyProduction(1,2,"$Bb$");
grammarMatrix2.modifyProduction(2,0,"$C$");
grammarMatrix2.modifyProduction(2,2,"$c$");
grammarMatrix2.modifyProduction(3,0,"$C$");
grammarMatrix2.modifyProduction(3,2,"$Da$");
for(var i = 4; i<14; i++)
grammarMatrix2.hideRow(i);
grammarMatrix2.hide();
// Frame 1
av.umsg("Next we will consider Unit Productions. These are productions that simply replace one variable with another, such as $A \\Rightarrow B$. When deriving a string, these seem an unnecessary step. Instead of going from $A$ to $B$ and then replacing $B$ with the RHS of one of its rules (such as $B \\Rightarrow bb$), we could simply go there directly with a rule like $A \\Rightarrow bb$. Of couse, this requires that we also replace every other production that has $B$ on its LHS with an equivalent production that has $A$ on its LHS.");
av.displayInit();
// Frame 2
av.umsg(Frames.addQuestion("which"));
av.step();
// Frame 3
av.umsg(Frames.addQuestion("subst"));
av.step();
// Frame 4
av.umsg(Frames.addQuestion("nounit"));
av.step();
// Frame 5
av.umsg(Frames.addQuestion("fail"));
av.step();
// Frame 6
av.umsg(Frames.addQuestion("lambda"));
av.step();
// Frame 7
av.umsg(Frames.addQuestion("star"));
av.step();
// Frame 8
av.umsg(Frames.addQuestion("graph"));
grammarMatrix.show();
av.step();
// Frame 9
av.umsg(Frames.addQuestion("AB"));
var VDG = new av.ds.FA({left: 10, top: 345, width: 300});
var S = VDG.addNode({value:"S", left: 0, top: 0});
var A = VDG.addNode({value:"A", left: 50, top: 0});
var B = VDG.addNode({value:"B", left:100, top: 0});
var C = VDG.addNode({value:"C",left:25, top: 60});
var D = VDG.addNode({value:"D", left:75, top: 60});
grammarMatrix.highlight(1);
av.step();
// Frame 10
av.umsg(Frames.addQuestion("BC"));
VDG.addEdge(A, B, {weight:" "});
grammarMatrix.unhighlight(1);
grammarMatrix.highlight(3);
VDG.layout();
av.step();
// Frame 11
av.umsg(Frames.addQuestion("CA"));
VDG.addEdge(B, C, {weight:" "});
grammarMatrix.unhighlight(3);
grammarMatrix.highlight(4);
VDG.layout();
av.step();
// Frame 12
av.umsg(Frames.addQuestion("DA"));
VDG.addEdge(C, A, {weight:" "});
grammarMatrix.unhighlight(4);
grammarMatrix.highlight(7);
VDG.layout();
av.step();
// Frame 13
av.umsg(Frames.addQuestion("nonunit"));
VDG.addEdge(D, A, {weight:" "});
grammarMatrix.unhighlight(7);
VDG.layout();
av.step();
// Frame 14
av.umsg(Frames.addQuestion("dfsA"));
grammarMatrix2.show();
av.step();
// Frame 15
av.umsg(Frames.addQuestion("dfsB"));
var V = new av.ds.array(["$A \\stackrel{*}{\\Rightarrow} C$","$A \\stackrel{*}{\\Rightarrow} B$", "", "", "","","","",""], {left: 5, top: 470, indexed: true});
av.step();
// Frame 16
av.umsg(Frames.addQuestion("dfsC"));
V.value(2, "$B \\stackrel{*}{\\Rightarrow} A$");
V.value(3, "$B \\stackrel{*}{\\Rightarrow} C$");
V.layout();
av.step();
// Frame 17
av.umsg(Frames.addQuestion("dfsD"));
V.value(4, "$C \\stackrel{*}{\\Rightarrow} B$");
V.value(5, "$C \\stackrel{*}{\\Rightarrow} A$");
V.layout();
av.step();
// Frame 18
av.umsg(Frames.addQuestion("repAC"));
V.value(6, "$D \\stackrel{*}{\\Rightarrow} C$");
V.value(7, "$D \\stackrel{*}{\\Rightarrow} B$");
V.value(8, "$D \\stackrel{*}{\\Rightarrow} A$");
V.layout();
V.highlight(0);
av.step();
// Frame 19
av.umsg(Frames.addQuestion("repAB"));
V.unhighlight(0);
V.highlight(1);
grammarMatrix2.showRow(4);
grammarMatrix2.showRow(5);
grammarMatrix2.modifyProduction(4,0,"$A$");
grammarMatrix2.modifyProduction(4,2,"$c$");
grammarMatrix2.modifyProduction(5,0,"$A$");
grammarMatrix2.modifyProduction(5,2,"$Da$");
av.step();
// Frame 20
av.umsg(Frames.addQuestion("repBA"));
V.unhighlight(1);
V.highlight(2);
grammarMatrix2.showRow(6);
grammarMatrix2.modifyProduction(6,0,"$A$");
grammarMatrix2.modifyProduction(6,2,"$Bb$");
av.step();
// Frame 21
av.umsg(Frames.addQuestion("repBC"));
V.unhighlight(2);
V.highlight(3);
grammarMatrix2.showRow(7);
grammarMatrix2.showRow(8);
grammarMatrix2.modifyProduction(7,0,"$B$");
grammarMatrix2.modifyProduction(7,2,"$c$");
grammarMatrix2.modifyProduction(8,0,"$B$");
grammarMatrix2.modifyProduction(8,2,"$Db$");
av.step();
// Frame 22
av.umsg(Frames.addQuestion("repCB"));
V.unhighlight(3);
V.highlight(4);
av.step();
// Frame 23
av.umsg(Frames.addQuestion("repCA"));
V.unhighlight(4);
V.highlight(5);
grammarMatrix2.showRow(9);
grammarMatrix2.modifyProduction(9,0,"$C$");
grammarMatrix2.modifyProduction(9,2,"$Bb$");
av.step();
// Frame 24
av.umsg(Frames.addQuestion("repDC"));
V.unhighlight(5);
V.highlight(6);
av.step();
// Frame 25
av.umsg(Frames.addQuestion("repDB"));
V.unhighlight(6);
V.highlight(7);
grammarMatrix2.showRow(10);
grammarMatrix2.showRow(11);
grammarMatrix2.showRow(12);
grammarMatrix2.modifyProduction(10,0,"$D$");
grammarMatrix2.modifyProduction(10,2,"$Bb$");
grammarMatrix2.modifyProduction(11,0,"$D$");
grammarMatrix2.modifyProduction(11,2,"$c$");
grammarMatrix2.modifyProduction(12,0,"$D$");
grammarMatrix2.modifyProduction(12,2,"$Da$");
av.step();
// Frame 26
av.umsg(Frames.addQuestion("repDA"));
V.unhighlight(7);
V.highlight(8);
av.step();
// Frame 27
av.umsg("We have now correctly removed all unit productions.");
V.unhighlight(8);
V.hide();
av.step();
// Frame 28
av.umsg("Congratulations! Frameset completed.");
av.recorded();
});
|
import CursoAluno from '../models/CursoAluno';
class CursoAlunoController {
async create(req, res) {
const novo = req.body;
try {
//VERIFICA SE O CURSO JÁ NÃO ESTÁ ASSOCIADO AO ALUNO
let aluno_curso = await CursoAluno.findAll();
for(var i=0; i<aluno_curso.length; i++) {
let element = aluno_curso[i];
if(element.id_pessoa == novo.id_pessoa && element.id_curso == novo.id_curso) {
return res.status(400).json({
error: "Curso já adicionado para este aluno"
});
}
}
aluno_curso = await CursoAluno.create(novo);
res.json(aluno_curso);
}catch(erro) {
console.log(erro);
return res.status(400).json({
error: erro
});
}
}
}
export default new CursoAlunoController();
|
import * as React from 'react'
import {
Checkbox,
Button,
List,
ListItem,
ListItemIcon,
ListItemSecondaryAction,
ListItemText,
} from '@material-ui/core'
import styled from 'styled-components'
export const Todos = ({ todos, handleDeleteTodo, handleCompleteTodo }) => {
return (
<List>
{todos.map(({ name, key, completed }) => (
<ListItem button key={key}>
{!completed && (
<ListItemIcon>
<Checkbox
edge="start"
checked={completed}
onClick={() => handleCompleteTodo(key)}
/>
</ListItemIcon>
)}
{completed ? (
<CompletedText primary={name} />
) : (
<ListItemText primary={name} />
)}
<ListItemSecondaryAction>
<Button
variant="outlined"
onClick={() => handleDeleteTodo(key)}
>
delete
</Button>
</ListItemSecondaryAction>
</ListItem>
))}
</List>
)
}
const CompletedText = styled(ListItemText)`
text-decoration: line-through;
`
|
import React, { Component } from "react";
import HeaderHome from "../../components/layout/header/HeaderHome";
// import NavBar from './../../shared/components/Navbar/index'
// import UserList from "./UserList/UserList";
// import TopVideo from "./TopVideo/TopVideo";
// import GLOBAL_VARIABLES from "../../config/config";
// import Slider from "../../components/slider/Slider";
import Banner from "../../components/banner/Banner";
import RecentVideo from "../../components/recentVideo/RecentVideo";
import {
getBannerFromDB,
getCurriculumFromDB,
getReviewContentFromDB
} from "./../../database/dal/firebase/curriculumDal";
import { getNotificationsFromDB } from "../../database/dal/firebase/studentDal";
import "./teacher.scss";
class Teacher extends Component {
state = {
userDetails: "",
bannerData: "",
myContent: [],
reviewedContent: [],
pendingContent: []
};
componentWillMount = () => {
this.setState({
userDetails: JSON.parse(localStorage.getItem("userProfile"))
});
};
componentDidMount = () => {
getBannerFromDB().then(querySnapshot => {
let bannerData = [];
querySnapshot.forEach(doc => {
bannerData.push(doc.data());
});
this.setState({ bannerData });
});
getCurriculumFromDB(this.state.userDetails.userId).onSnapshot(
querySnapshot => {
let myContent = [];
querySnapshot.forEach(doc => {
myContent.push(doc.data());
});
this.setState({ myContent });
}
);
getNotificationsFromDB(
this.state.userDetails.userId,
this.state.userDetails.role
).onSnapshot(querySnapshot => {
let content = [];
querySnapshot.forEach(doc => {
content.push(Object.assign({ id: doc.id }, doc.data()));
});
if (content.length > 0) {
this.setState({
pendingContent: content.filter(item => !item.tstatus && item.sstatus),
reviewedContent: content.filter(item => item.tstatus)
});
/* content = content.filter( (list) => {
if(tabKey === 'reviewed') {
return list.sstatus && list.tstatus
} else if(tabKey === 'pendingreview'){
return list.sstatus && !list.tstatus
} else if(tabKey === 'rejected') {
return list.sstatus === false
}
}) */
}
});
// this.setState({ content });
/* this.getReviewContent(
this.state.userDetails.userId,
true,
"reviewedContent"
);
this.getReviewContent(
this.state.userDetails.userId,
false,
"pendingContent"
); */
};
/* getReviewContent = (userId, status, state) => {
console.log(userId, status,state)
getReviewContentFromDB(userId, status).onSnapshot(querySnapshot => {
let content = [];
querySnapshot.forEach(doc => {
content.push(doc.data());
});
console.log(content)
this.setState({ [state]: content });
});
};
*/
render = () => {
const {
bannerData,
myContent,
reviewedContent,
pendingContent
} = this.state;
return (
<div className="container-fluid">
<HeaderHome headeTitle="Teacher Dashboard" />
<div className="content-container main-wrapper">
{bannerData && <Banner bannerRows={bannerData} pageName="teacher" />}
<RecentVideo
isNotVisibleVideoMeta={true}
carousellistNewlyItems={pendingContent}
headeTitle="Video Pending for Review"
/>
<RecentVideo
isNotVisibleVideoMeta={true}
carousellistNewlyItems={reviewedContent}
headeTitle="Video Reviewed"
/>
<RecentVideo
carousellistNewlyItems={myContent}
headeTitle="My Video"
/>
</div>
</div>
);
};
}
export default Teacher;
|
const Koa = require('koa');
const app = new Koa();
const fs = require('fs');
const exec = require('child_process').exec;
const dayjs = require('dayjs');
const ora = require("ora");
const shell = require('shelljs');
app.use(async (ctx, next) => {
let spinner = ora();
let content = ctx.query;
spinner.text = '正在拉取GitHub上的变动!\n';
spinner.start();
shell.exec('git pull', (code, stdout, stderr) => {
if (code !== 0) {
spinner.text = stderr;
spinner.fail("拉取失败,请手动更新代码!");
shell.exit(1);
} else {
spinner.text = stdout;
spinner.succeed("拉取成功!");
const fileName = `${dayjs().format('YYYY-MM')}.md`;
const fileContent = `[${content.title}](${content.link})</br></br>`;
fs.exists('bookmarks', (exists) => {
!exists && fs.mkdirSync('bookmarks');
});
fs.appendFile(`bookmarks\\${fileName}`, fileContent, (error) => {
if (error) {
console.log('文件内容写入失败,请重启程序!');
return false;
}
});
console.log('文件内容写入成功,正在同步至GitHub!');
spinner.text = '正在同步中,请勿中断进程!\n';
spinner.start();
shell.exec(`git add . && git commit -m ${fileName} && git push -u origin master`, (multiCode, multiStdout, multiErr) => {
console.log('执行命令');
if (multiCode !== 0) {
spinner.text = multiErr;
spinner.fail("同步失败!");
shell.exit(1);
} else {
spinner.text = multiStdout;
spinner.succeed("已完成同步!");
}
})
}
});
ctx.body = content;
});
app.listen(3000, () => {
console.log('server is starting at port 3000');
});
|
/**
* Created by amoroz-prom on 16.11.14.
*/
var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('cssconcat',function(){
gulp.src('./css/**/*.css')
.pipe(concat('all.css'))
.pipe(gulp.dest('./dist'));
});
|
/**
* Created by Chris Chang on 2016/4/27.
*/
define('whatInput', [
'avalon',
'text!../../lib/whatInput/whatInput.html',
'css!../../lib/whatInput/whatInput.css',
'css!../../src/css/font-awesome.min.css'
], function (avalon, html, css) {
avalon.component("tsy:input", {
id: "itip",
$init: function (vm, elem) {
//获取将要构建为组件的元素
//vmodel = this
elem = avalon(elem);
//抓取<tsy:whatinput ms-data-id="whatinput">元素内的配置ms-data-id的值
try {
if (elem.data('id') != undefined) {
vm.id = elem.data('id')
}
} catch (err) {
}
//加载组件的方法(所有需要调用VM内部属性的方法,都要在VM上先设置方法例如第56行,然后再这里来加载具体的函数逻辑)
//判断时间,还原状态
function setState(i, tip) {
avalon.mix(vm, {
state: i,
state_icon: i,
tip: tip,
state_last: i
})
}
function default_time(timeout) {
clearTimeout(vm.timeout)
var time = 0;
if (timeout != null) {
time = timeout
}
else {
time = 5000
}
vm.timeout = setTimeout(function () {
vm.state = 0;
}, time);
}
vm.default = function () {
setState(0, '')
}
vm.info = function (tip, timeout) {
//信息(蓝色)
setState(3, tip)
default_time(timeout);
};
vm.warning = function (tip, timeout) {
//警告(橙棕色)
setState(2, tip)
default_time(timeout);
};
vm.error = function (tip, timeout) {
//警告(红色)
setState(1, tip)
default_time(timeout);
};
vm.success = function () {
vm.state_last = 0;
vm.state = 0;
vm.state_icon = 4;
};
//本处监听focus事件
vm.addEventHandler = function (oTarget, sEventType, fnHandler) {
if (oTarget.addEventListener) {
oTarget.addEventListener(sEventType, fnHandler, false);
} else if (oTarget.attachEvent) {
oTarget.attachEvent("on" + sEventType, fnHandler);
} else {
oTarget["on" + sEventType] = fnHandler;
}
};
vm.addEventHandler(elem.element.lastElementChild, 'focus', function () {
vm.state_focus = 1;
setTimeout(vm.tip_not, 2000)
});
vm.addEventHandler(elem.element.lastElementChild, 'blur', function () {
vm.state_focus = 0;
}, false);
vm.addFocus = function () {
if (vm.click_whether === false) {
vm.click_whether = true;
}
else {
vm.click_whether = false;
}
elem.element.lastElementChild.getElementsByTagName('input')[0].focus();
vm.state = vm.state_icon;
};
//state_again方法用来设置vm.state的状态
function set_state(willing_state) {
vm.state = willing_state;
};
//鼠标over时触发本事件
vm.move_on = function () {
setTimeout(function () {
if (vm.state_focus != 1) {
vm.tip_again();
}
}, 5000)
};
//设置state的值,用以重新显示tip
vm.tip_again = function () {
var temp = vm.state_icon;
if (vm.state_icon == 4) {
temp = 0;
}
//非focus状态悬浮才可以显示
set_state(temp);
};
//tip的消失
vm.tip_not = function () {
//clearTimeout(vm.not_settime)
vm.not_settime = setTimeout(function () {
if (vm.state > 0 && vm.state < 4) {
set_state(0)
}
else if (vm.state == 0 && vm.click_whether == false) {
set_state(0)
}
}, 250)
};
//将VM暴露到全局以供调用
if (vm.id != "") {
window[vm.id] = vm
}
},
$ready: function (vm, elem) {
},
$template: html,
core: "",//从外部进来的input
label: "",
sign: "",
//提示文本的内容
tip: "",
timeout: '',
state: 0,
state_last: 0,//保存上一个状态的值,进行持续错误的判断
state_icon: 0,//图标的状态,将保持上一个的状态
state_focus: 0,
click_whether: false,
/*输入框状态:
* 0 —— 默认状态
* 1 —— 失败
* 2 —— 警告
* 3 —— 信息
* 4 —— 成功
* */
//提示弹出的方法
default: function () {
},
info: function () {
//提示(这里是占位的函数,在$init中编写函数用于加载相关的方法)
},
warning: function () {
//警告(这里是占位的函数,在$init中编写函数用于加载相关的方法)
},
error: function () {
//错误(这里是占位的函数,在$init中编写函数用于加载相关的方法)
},
//设置为成功的方法
success: function () {
//成功,
},
//
tip_again: function () {
//持续错误
},
tip_not: function () {
//鼠标移开错误
},
addEventHandler: function () {
},
addFocus: function () {
},
move_on: function () {
}
})
});
|
const projectsData = [
{
title: 'Ditto',
subtitle: 'Declarative JSON-to-JSON mapper .. shape-shift JSON files with Ditto',
description: `When dealing with data integration problems, the need to translate JSON from external formats to adhere to an internal representation become a vital task. Ditto was created to solve the issue of unifying external data representation.
Ditto parses a mapping file (see mapping rules) and produces a JSON output from the input data to match the output definition.`,
href: '/blog/json-ditto',
github: 'https://github.com/BeameryHQ/json-ditto',
},
{
title: 'Code Notes',
subtitle: 'Tool to summarise all code annotation like TODO or FIXME',
description: `code-notes is a node.js version of Rails' "rake notes" functionality. It allows you to put comments in your code and then have them annotated across your whole project`,
href: '/blog/code-notes',
github: 'https://github.com/ahmadassaf/code-notes',
},
{
title: 'Booklight',
subtitle:
'Your Chrome Alfred - An Extension to provide spotlight-like interface for your bookmarks',
description: `If you are: Obsessed with organization; Have a couple hundreds (or thousands) of folders in your bookmarks; You like to keep things tidy and every page has to be in its "perfect" place
then Booklight is a clean Chrome Extension to ease the way of adding a bookmark`,
href: '/blog/booklight',
github: 'https://github.com/ahmadassaf/booklight',
},
{
title: 'Micromanage',
subtitle:
'A Micro-services Helpers Framework | Easily manage multiple repositories and projects',
description: `Developing features affect very often more than one of these repos. Changing branches, syncing and development is hard as you have to keep flipping between multiple terminal tabs to make sure all the repos are in order. Beamery Micro-services Helpers are shell helper functions that will automate and facilitate manipulating micro-services repos and in general any multiple folders in a certain directory.`,
href: '/blog/micromanage',
github: 'https://github.com/BeameryHQ/micromanage',
},
{
title: 'Gaudi',
subtitle:
'A collection of tools and services to boost developers productivity from bash frameworks and tools to OSX widgets and dotfiles',
description: `A collection of tools and services to boost developers productivity from bash frameworks and tools to OSX widgets and dotfiles`,
href: '/blog/gaudi',
github: 'https://github.com/g-udi',
},
{
title: 'Roomba',
subtitle: 'Examine the correctness of Open Data Metadata and build custom dataset profiles',
description: `Roomba is a scalable automatic approach for extracting, validating and generating descriptive linked dataset profiles. This approach applies several techniques to check the validity of the attached metadata as well as providing descriptive and statistical information of a certain dataset as well as a whole data portal. Using our framework on prominent data portals shows that the general state of the Linked Open Data needs attention as most of datasets suffer from bad quality metadata and lack additional informative metrics.`,
href: '/blog/roomba',
github: 'https://github.com/ahmadassaf/openData-checker',
},
{
title: 'KBE',
subtitle:
'Extract the knowledge represented in Google infoboxes (aka Google Knowlege Graph Panel)',
description: `This is a node.js application that aims at extracting the knowledge represented in the Google infoboxes (aka Google Knowlege Graph Panel)`,
href: '/blog/kbe',
github: 'https://github.com/ahmadassaf/KBE',
},
]
export default projectsData
|
import { GraphQLObjectType, GraphQLString } from 'graphql';
const UserType = new GraphQLObjectType({
name: 'User',
fields: {
id: { type: GraphQLString },
email: { type: GraphQLString },
firstName: { type: GraphQLString },
lastName: { type: GraphQLString },
role: { type: GraphQLString },
dob: { type: GraphQLString },
createdAt: { type: GraphQLString },
},
});
export default UserType;
|
(function() {
// 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释
var imports = [
'rd.services.Alert'
];
var extraModules = [ ];
var controllerDefination = ['$scope', 'Alert', 'ButtonTypes', 'EventService', 'EventTypes', main];
function main(scope, Alert, ButtonTypes, EventService, EventTypes) {
var moduleID;
scope.clickHandler = function() {
moduleID = Alert.confirm('信息确认请注意', '确认提示', ButtonTypes.YES + ButtonTypes.NO + ButtonTypes.CANCEL, callbackHandler, false);
}
EventService.register(moduleID, EventTypes.CLOSE, function(event, data){
alert('call close');
});
scope.removeHandler = function(){
Alert.remove(moduleID);
}
function callbackHandler(val) {
if (val == ButtonTypes.YES) {
alert('call back YES');
}
if (val == ButtonTypes.NO) {
alert('call back NO');
}
if (val == ButtonTypes.OK) {
alert('call back OK');
}
if (val == ButtonTypes.CANCEL) {
alert('call back CANCEL');
}
}
}
var controllerName = 'DemoController';
//==========================================================================
// 从这里开始的代码、注释请不要随意修改
//==========================================================================
define(/*fix-from*/application.import(imports)/*fix-to*/, start);
function start() {
application.initImports(imports, arguments);
rdk.$injectDependency(application.getComponents(extraModules, imports));
rdk.$ngModule.controller(controllerName, controllerDefination);
}
})();
|
const style = theme => ({
paper: {
textAlign: 'center',
padding: 15,
color: '#707070'
},
icon: {
width: 60,
height: 60
},
label: {
color: '#A3A3A3',
fontSize: 24
},
timer: {
color: '#707070',
fontSize: '2.5rem',
fontWeight: 300
}
});
export default style;
|
const mongoose = require("mongoose");
var teacherLoginSchema = new mongoose.Schema({
uname: {
type: String
},
passsword: {
type: String
}
});
mongoose.model("TeacherLogin", teacherLoginSchema);
|
let name = 'me';
let number = 21;
let email = 'guigue@live.com.pt';
let address = 'rua da jarda';
const casmurro = 123;
/* jardovki
heyo */
let declar;
console.log(declar);
declar = 'declared';
console.log(declar);
console.log(casmurro);
|
import React from 'react';
import PropTypes from 'prop-types';
import tabsHoc from '../../hoc/tabs-hoc';
import Deposits from '../deposits/deposits';
import Credit from '../credit/credit';
import Insurance from '../insurance/insurance';
import OnlineService from '../online-service/online-service';
const Tabs = ({...props}) => {
const toggleTabs = (index) => {
props.onActiveTabs(index);
};
return (
<section className="tabs">
<h2 className="tabs__title visually-hidden">Услуги</h2>
<div className="tabs__container">
<div className="tabs__triggers">
<a className={props.activeTabs === 1 ? `tabs__triggers-item tabs__triggers-item--active tabs__triggers-item--deposits` : `tabs__triggers-item tabs__triggers-item--deposits`} onClick={() => toggleTabs(1)} href="#deposits-tabs">Вклады</a>
<a className={props.activeTabs === 2 ? `tabs__triggers-item tabs__triggers-item--active tabs__triggers-item--credit` : `tabs__triggers-item tabs__triggers-item--credit`} onClick={() => toggleTabs(2)} href="#credit-tabs">Кредиты</a>
<a className={props.activeTabs === 3 ? `tabs__triggers-item tabs__triggers-item--active tabs__triggers-item--insurance` : `tabs__triggers-item tabs__triggers-item--insurance`} onClick={() => toggleTabs(3)} href="#insurance-tabs">Страхование</a>
<a className={props.activeTabs === 4 ? `tabs__triggers-item tabs__triggers-item--active tabs__triggers-item--online` : `tabs__triggers-item tabs__triggers-item--online`} onClick={() => toggleTabs(4)} href="#online-tabs">Онлайн-сервисы</a>
</div>
<div className="tabs__content">
<div className={props.activeTabs === 1 ? `tabs__content-item tabs__content-item--active` : `tabs__content-item`} id="deposits-tabs">
<Deposits />
</div>
<div className={props.activeTabs === 2 ? `tabs__content-item tabs__content-item--active` : `tabs__content-item`} id="credit-tabs">
<Credit />
</div>
<div className={props.activeTabs === 3 ? `tabs__content-item tabs__content-item--active` : `tabs__content-item`} id="insurance-tabs">
<Insurance />
</div>
<div className={props.activeTabs === 4 ? `tabs__content-item tabs__content-item--active` : `tabs__content-item`} id="online-tabs">
<OnlineService/>
</div>
</div>
</div>
</section>
);
};
Tabs.propTypes = {
activeTabs: PropTypes.number.isRequired,
onActiveTabs: PropTypes.func.isRequired,
};
export default tabsHoc(Tabs);
|
import React from 'react'
import PropTypes from 'prop-types'
import { Tags } from '@tryghost/helpers-gatsby'
//import { readingTime as readingTimeHelper } from '@tryghost/helpers'
import dayjs from 'dayjs'
let relativeTime = require(`dayjs/plugin/relativeTime`)
dayjs.extend(relativeTime)
const AsideCard = ({ post }) => {
let timeNow = dayjs()
let timeAdded = dayjs(post.published_at)
let timeSince = timeNow.to(timeAdded)
//const readingTime = readingTimeHelper(post)
//const publishedAt = dayjs(post.published_at).format(`MMM D, YYYY`)
//const updatedAt = dayjs(post.updated_at).format(`MMM D, YYYY`)
return (
<aside className="aside-card py-lg-3 mb-4">
<header className="post-card-header">
{post.primary_tag && <p className="post-card-tags h6 text-uppercase mb-1">{post.primary_tag.name}</p>}
</header>
<section className="content-body load-external-scripts mb-1" dangerouslySetInnerHTML={{ __html: post.html }} />
<footer className="post-card-footer mt-0">
<div className="post-meta mb-2">
<time className="post-byline-item d-inline-block h6 text-uppercase pe-5" dateTime={post.published_at}>
{timeSince}
</time>
</div>
{post.tags && <div className="post-card-tags h6 text-uppercase mb-1"><span className="sr-only">Posted in:</span> <Tags post={post} visibility="public" autolink={false} /></div>}
<div className="sr-only">
<span>By: { post.primary_author.name }</span>
</div>
</footer>
</aside>
)
}
AsideCard.propTypes = {
post: PropTypes.shape({
slug: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
published_at: PropTypes.string,
updated_at: PropTypes.string,
feature_image: PropTypes.string,
featured: PropTypes.bool,
primary_tag: PropTypes.PropTypes.object,
tags: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
})
),
html: PropTypes.string.isRequired,
excerpt: PropTypes.string.isRequired,
primary_author: PropTypes.shape({
name: PropTypes.string.isRequired,
profile_image: PropTypes.string,
}).isRequired,
}).isRequired,
}
export default AsideCard
|
import React from 'react'
import RaisedButton from 'material-ui/RaisedButton'
import ActionAndroid from 'material-ui/svg-icons/content/forward'
import { red500, fullWhite } from 'material-ui/styles/colors'
import { Link } from 'react-router-dom'
import './style.scss'
const style = {
minWidth: 140,
marginRight: 20,
}
const ButtonMore = () => (
<Link to={'/recipes'} className='button-more'>
<RaisedButton
backgroundColor={red500}
icon={<ActionAndroid color={fullWhite} />}
style={style}
/>
</Link>
)
export default ButtonMore
|
Vue.component('body-component', {
props: ['numberSystems', 'input1', 'input2', 'numberSystemPosition1', 'numberSystemPosition2'],
template: `
<div>
<input-component
input-position = 'first'
:number-system-position = "numberSystemPosition1"
:number-systems="numberSystems"
:input="input1"
placeholder="Enter value 1"
@update-input="$emit('update-input-2', { input: 'one', data: $event })"
@update-number-system="$emit('update-number-system-2', { inputPosition: 'first', dir: $event })"
></input-component>
<input-component
input-position = 'second'
:number-system-position = "numberSystemPosition2"
:number-systems="numberSystems"
:input="input2"
placeholder="Enter value 2"
@update-input="$emit('update-input-2', { input: 'two', data: $event })"
@update-number-system="$emit('update-number-system-2', { inputPosition: 'second', dir: $event })"
></input-component>
</div>
`
});
//child of body-component which is in turn child of the root vue instance of converter-app
Vue.component('input-component', {
props: ['inputPosition', 'numberSystems', 'input', 'placeholder', 'numberSystemPosition'],
template: `
<div class="card-panel blue" style="padding: 10px 0px 0px 0px">
<div class="row" style="margin: 0px">
<button
class="col push-s1 offset-m1 offset-l1 s2 m2 l2 btn orange waves-effect waves-light"
@click="updateNumberSystem('prev')"
>
<i class="material-icons large">chevron_left</i>
</button>
<div
id="number-system-display"
class="offset-s2 offset-m1 offset-l1 col s4 m4 l4 purple darken-3 container"
>
{{ numberSystems[numberSystemPosition] }}
</div>
<button
class="offset-s2 offset-m1 offset-l1 col pull-s1 s2 m2 l2 btn orange waves-effect waves-light"
@click="updateNumberSystem('next')"
>
<i class="material-icons large">chevron_right</i>
</button>
</div>
<div class="row">
<input
class="col offset-s1 offset-m1 offset-l1 s10 m10 l10 white-text"
type="text"
:value="input"
:placeholder="placeholder"
@input="$emit('update-input', $event.target.value)"
>
</div>
</div>
`,
methods: {
updateNumberSystem: function(dir){
this.$emit('update-number-system', dir);
}
}
});
|
define(['apps/system/system.service'],
function (module) {
module.factory("system_module_service", function ($rootScope, Restangular, userApiUrl, userApiVersion) {
var restSrv = Restangular.withConfig(function (configSetter) {
configSetter.setBaseUrl(userApiUrl + userApiVersion);
});
return {
getModules: function (key) {
return restSrv.all("module").getList({ business: (key ? key : $rootScope.currentBusiness.Key) });
},
addModule: function (module, parentKey) {
module.BusinessKey = $rootScope.currentBusiness.Key;
module.ParentKey = parentKey;
return restSrv.all("module").customPOST(module);
},
removeModule: function (key) {
return restSrv.all("module").customDELETE("", { Key: key });
},
updateModule: function (module) {
return restSrv.all("module").customPUT(module);
},
}
});
});
|
import React from 'react';
import PhotoCard from './PhotoCard';
const ListOfPhotoCards = () => {
return (
<ul>
{[1, 2].map((id) => (
<PhotoCard key={id} />
))}
</ul>
);
};
export default ListOfPhotoCards;
|
import { TweenLite } from 'gsap';
import ScrollToPlugin from 'gsap/ScrollToPlugin';
import ScrollMagic from 'scrollmagic';
import $ from 'jquery';
const controller = new ScrollMagic.Controller();
controller.scrollTo((newpos) => {
const navHeight = $('nav').height();
TweenLite.to(
window,
0.5,
{
scrollTo: {
y: newpos,
offsetY: navHeight + 40
}
});
});
export { controller };
|
var a = 1;
debugger;
var b = 2;
console.log(b)
|
'use strict';
angular.module('FEF-Angular-UI.imageLoader', [])
.directive('imageLoader', ['DeviceService', 'Utils', function(DeviceService, Utils) {
return {
scope: {
srcMobile: '@',
srcTablet: '@',
srcDesktop: '@'
},
link: function(scope, element, attrs) {
var device = DeviceService.getDevice(),
srcAttr = 'src' + Utils.capitalise(device),
sequence = ['srcMobile', 'srcTablet', 'srcDesktop'],
srcAttrs = {
srcMobile: 'src-mobile',
srcTablet: 'src-tablet',
srcDesktop: 'src-desktop'
};
for (var c = 0; c < sequence.length; c++) {
if (element.attr(srcAttrs[srcAttr]) !== undefined) {
break;
} else {
srcAttr = nextSrc(srcAttr);
}
}
if (!element.hasClass('hide-'+device)) {
attrs.$observe(srcAttr, function(attrVal) {
element.attr('src', attrVal);
});
}
function nextSrc(srcAttr) {
var i = sequence.indexOf(srcAttr),
next = i+1 < sequence.length ? sequence[i+1] : sequence[0];
return next;
}
}
}
}]);
|
const onClickMyPost = async (user_id) => {
try {
const options = {
url: '/profile/mypage/post/contact/',
method: 'POST',
data: {
user_id: user_id,
}
}
const response = await axios(options)
const responseOK = response && response.status === 200 && response.statusText === 'OK'
if (responseOK) {
const data = response.data
listMyPost(data.contacts)
}
} catch (error) {
console.log(error)
}
}
const listMyPost = (contacts) => {
// local-bar 변경
const postPortfolio = document.querySelector('#post__portfolio');
const postMyPost = document.querySelector('#post__my-post');
const postPortfolioSelected = document.querySelector('#post__portfolio-selected');
const postMyPostSelected = document.querySelector('#post__my-post-selected');
const postMyContact = document.querySelector('#post__my-contact');
const postMyPlace = document.querySelector('#post__my-place');
postPortfolio.className = "";
postMyPost.className = "post__local-bar-selected";
postPortfolioSelected.className = "post__not-selected";
postMyPostSelected.className = "";
postMyContact.className = "post__local-sub-bar-selected";
postMyPlace.className = "";
// 게시글 변경
const postContainer = document.querySelector('.post__container');
postContainer.innerHTML = '';
for (let i = 0; i < contacts.length; i++) {
postContainer.innerHTML += `<div class="post__item">` +
`<a href=/contact/detail/${contacts[i].id}>` +
`<figure class="post__image">` +
`<img src=${contacts[i].thumbnail_url}>` +
`<figcaption>` +
`<div class="post__info">` +
`<p class="post__title">${contacts[i].title}</p>` +
`<div>` +
`<p class="post__comment">` +
`<i class="far fa-comment"></i>` +
`<span>${contacts[i].comment_count}</span>` +
`</p>` +
`<p class="post__bookmark">` +
`<i class="fas fa-bookmark"></i>` +
`<span>${contacts[i].bookmark_count}</span>` +
`</p>` +
`</div>` +
`</div>` +
`</figcaption>` +
`</figure>` +
`</a>` +
`</div>`
}
}
|
import React from 'react';
// import test0 from './asset/512x512.jpg';
// import test1 from './asset/1024x1024.jpg';
// import pdf_en_us from './asset/I am pdf en-us.pdf';
// import pdf_zh_cn from './asset/I am pdf zh-cn.pdf';
import pdf_en_us from './asset/BN-DG-S100006_5cc7fc05784ac2385bdac52c_En.pdf';
import pdf_zh_cn from './asset/BN-DG-S100006_5cc7fc05784ac2385bdac52c_Zh.pdf';
import BrainnowPDFViewer from './BrainnowPDFViewer';
const imgs = [];
for (let i = 0; i < 16; ++i) {
imgs.push(require('./asset/AxialOverlay' + i.toString() + '.jpg'));
}
export default function App() {
return (
<BrainnowPDFViewer pdf_en_us={pdf_en_us} pdf_zh_cn={pdf_zh_cn} imgs={imgs}></BrainnowPDFViewer>
);
};
|
/*
* @Author: jypblue
* @Date: 2016-08-08 13:46:55
* @Last Modified by: jypblue
* @Last Modified time: 2016-08-08 13:50:36
*/
/**
* Q:Given a roman numeral, convert it to an integer.
* Input is guaranteed to be within the range from 1 to 3999.
* 题意:
* 给定一个罗马数字,将它转换为一个阿拉伯数字整数
* 分析:
* 从第一个字符开始,如果当前字符对应的数字比下一个数字大,
* 那么就把结果加上当前字符对应的数字,否则减去当前字符对应数字。
* 注意边界情况,所以在原字符串最后添加一个字符,该字符是原来的最后一个字符。
*/
'use strict';
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
// let map = new Map();
// map.set('I',1);
// map.set('V',5);
// map.set('X',10);
// map.set('L',50);
// map.set('C',100);
// map.set('D',500);
// map.set('M',1000);
var map = {};
map['I'] = 1;
map['V'] = 5;
map['X'] = 10;
map['L'] = 50;
map['C'] = 100;
map['D'] = 500;
map['M'] = 1000;
let res = 0,
n = s.length;
s += s[n - 1];
for (let i = 0; i < n; i++) {
if (map[s[i]] >= map[s[i + 1]])
res += map[s[i]];
else res -= map[s[i]];
}
return res;
};
|
window.onload = () => {
document.getElementById('start-button').onclick = () => {
startGame();
};
function startGame() {
let context = document.querySelector('canvas').getContext('2d');
let imgRoad = new Image();
imgRoad.src = 'images/road.png';
let imgCar = new Image();
imgScale = 200/400;
imgCar.src = 'images/car.png';
context.clearRect(0, 0, 1200, 800);
// context.fillRect(10, 10, 10, 10);
let car = {
posX: 215,
posY: 570
};
imgCar.onload = () => {
context.drawImage(imgRoad, 0, 0, 500, 700);
context.drawImage(imgCar, car.posX, car.posY, 120*imgScale, 120);
};
document.addEventListener('keydown', event => {
if (event.keyCode === 37) {
car.posX -= 5;
} else if (event.keyCode === 39) {
car.posX += 5;
}
console.log(car.posX);
context.clearRect(0, 0, 1200, 800);
context.drawImage(imgRoad, 0, 0, 500, 700);
context.drawImage(imgCar, car.posX, car.posY, 120*imgScale, 120);
});
}
};
|
document.addEventListener("DOMContentLoaded", function() {
const staff_dropdown = document.getElementById("staff_dropdown");
const form = document.querySelector("form");
const request = new XMLHttpRequest();
const addMore = document.getElementById("addMore");
let fieldsets = document.getElementsByTagName("fieldset");
request.open("GET", "http://localhost:3000/api/staff_members");
request.responseType = "json"
request.addEventListener("load", function(e) {
staff = request.response;
staff.forEach(member => {
const node = document.createElement("option");
node.setAttribute("name", member.name);
node.setAttribute("staff_id", member.id);
node.textContent = member.name;
staff_dropdown.append(node);
})
});
request.send();
addMore.addEventListener("click", function(e) {
e.preventDefault();
const nextFieldsetId = fieldsets.length + 1
const fieldset = form.querySelector("fieldset");
const nextFieldset = fieldset.cloneNode(true);
const submit = document.querySelector("input[type=submit]");
nextFieldset.setAttribute("id", "schedule-" + nextFieldsetId);
let textFields = nextFieldset.querySelectorAll("input[type=text]");
[...textFields].forEach(field => field.value = "");
nextFieldset.querySelector("legend").textContent = "Schedule " + nextFieldsetId;
form.insertBefore(nextFieldset, submit);
});
let formDataToJson = function(formData) {
const inputFields = 3
let json = [];
let schedule = {};
let count = 0;
for (let pair of formData.entries()) {
if (count === inputFields) {
json.push(schedule);
schedule = {};
count = 0;
}
schedule[pair[0]] = pair[1];
count++
}
json.push(schedule);
return { schedules: json };
};
form.addEventListener("submit", function(e) {
e.preventDefault();
const request = new XMLHttpRequest();
const formData = new FormData(form);
const json = JSON.stringify(formDataToJson(formData))
request.open("POST", form.action);
request.setRequestHeader("Content-Type", "application/json");
request.addEventListener("load", function(e) {
if (request.status === 201) form.reset();
alert(request.responseText);
});
request.send(json);
})
});
|
const express = require('express')
const router = express.Router();
const db = require('../functions/db')
router.get('/:id', (req,res,next) => {
const id = req.params.id
const originalurl = `http://localhost:3000/${id}`;
console.log(originalurl)
db.findLongUrl(originalurl)
.then(data => {
if(!data){
next();
return;
}
res.writeHead(301, {
Location: data.longUrl
});
res.end();
})
.catch(error => next(error));
});
module.exports = router;
|
class Record {
constructor(name, position) {
this.name = name;
this.position = position;
}
describe() {
return `${this.name} plays ${this.position}.`;
}
}
class Album {
constructor(name) {
this.name = name;
this.record = [];
}
addRecord (record) {
if (record instanceof record) {
this.records.push (record);
} else {
throw new Error ('You can only add an instance of record. Argument is not a record: ${record}');
}
}
describe() {
return `${this.name} has ${this.records.length} records.`;
}
}
class Menu {
constructor() {
this.albums = [];
this.selectedalbum = null;
}
start() {
let selection = this.showMainMenuOptions();
while (selection !=0) {
switch (selection) {
case '1':
this.createAlbum();
break;
case '2':
this.viewAlbum();
break;
case '3':
this.deleteAlbum();
break;
case '4':
this.displayAlbum();
break;
default:
selection = 0;
}
selection = this.showMainMenuOptions ();
}
alert ('Goodbye!');
}
showMainMenuOptions() {
return prompt (`
0) exit
1) create new album
2) view album
3) delete album
4) display all album
`);
}
showAlbumMenuOptions (albumInfo) {
return prompt (`
0) back
1) create record
2) delete record
---------------
${albumInfo}
`);
}
displayAlbums() {
let albumsString = '';
for (let i = 0; i < this.albums.length; i++) {
albumString += i + ')' + this.albums[i].name + '\n';
}
alert(albumString);
}
createAlbum() {
let name = prompt ('Enter name for new album');
this.albums.push(new Album(name));
}
viewAlbums () {
let index = prompt ('Enter the index of the index of album you wish to view:');
if (index > -1 && index < this.albums.length) {
this.selectedAlbum = this.albums [index];
let description = 'Album Name: ' + this.selectedalbum.name + '\n';
for (let i = 0; i < this.selectedAlbum.records.length; i++) {
description += i + ') ' + this.selectedAlbum.records[i].name + ' - ' + this.selectedAlbum.records[i].position + '\n';
}
let selection = this.showAlbumMenuOptions(description);
switch (selection) {
case '1':
this.createRecord ();
break;
case '2':
this.deleterRecord();
}
}
}
deleteAlbum () {
let index = prompt ('Enter the index of the album you wish to delete:');
if (index > -1 && index < this.albums.length) {
this.albums.splice (index, 1);
}
}
createRecord() {
let name = prompt ('Enter name for new record:');
let position = prompt ('Enter position for new record:');
this.selectedAlbum.records.push(new Record(name, position));
}
deleteRecord() {
let index = prompt ('Enter the index of the record you wish to delete:');
if (index > -1 && index < this.selectedAlbum.records.length) {
this.selectedAlbum.recordss.splice(index, 1);
}
}
}
let menu = new Menu ();
menu.start();
|
import React from "react";
const Welcome = function(props) {
return (
<div>
<h1>Welcome ! I am a functional component </h1>
</div>
)
}
export default Welcome;
|
'use strict'
app.config(function($stateProvider){
$stateProvider.state('tour', {
url : '/tour/:id',
templateUrl : 'js/tour/tour.html',
controller: 'TourCtrl',
resolve : {
tourData : function(TourFactory, $state, $stateParams){
return TourFactory.findTour($stateParams.id).catch(function(){
$state.go('home');
});
}
}
});
});
app.controller('TourCtrl', function($scope, tourData){
$scope.tourData = tourData;
console.dir(tourData);
//show and hiding images and map view
$scope.show = false;
$scope.showPics = function(){
$scope.show = !$scope.show;
}
// updateInterval(audio, $scope.tourData.points[0].imagesUrl);
$scope.interval = 5000;
$scope.slides = $scope.tourData.points[0].imagesUrl;
$scope.current = $scope.tourData.points[0].audioUrl;
$scope.$on('slideShow', function(event, data){
for(var i = 0; i < $scope.tourData.points.length; i++){
if($scope.tourData.points[i].latitude === data.latitude && $scope.tourData.points[i].longitude === data.longitude) {
$scope.images = $scope.tourData.points[i].imagesUrl;
$scope.slides = $scope.images;
$scope.$broadcast('pointChanged', {index: i});
// updateInterval(audio, $scope.tourData.points[i].imagesUrl);
break;
}
}
});
function updateInterval(htmlNode, imgArr){
$scope.interval = htmlNode.duration * 1000 / imgArr.length;
}
$scope.$on('tourPause', function(event){
$scope.$broadcast('tourPauseS');
});
$scope.$on('tourPlay', function(event){
$scope.$broadcast('tourPlayS');
});
$scope.$on('tourNext', function(event){
$scope.$broadcast('tourNextS');
});
$scope.$on('tourRewind', function(event){
$scope.$broadcast('tourRewindS');
});
$scope.$on('tourIsEnded', function(event){
$scope.$broadcast('tourIsEndedS');
});
$scope.$on('tourIsPlaying', function(event){
$scope.$broadcast('tourIsPlayingS');
});
$scope.$on('tourIsPaused', function(event){
$scope.$broadcast('tourIsPausedS');
});
});
app.factory('TourFactory', function($http){
return {
createTour : function(data){
return $http.post('api/tours', data).then(function(response){
return response.data;
});
},
findTour : function(id){
console.log(id);
return $http.get('api/tours/' + id).then(function(response){
return response.data;
});
},
updateTour : function(id, data){
return $http.put('api/tours/' + id, data).then(function(response){
return response.data;
});
},
deleteTour : function(id){
return $http.delete('api/tours/'+ id).then(function(response){
return response.data;
});
},
findAllTours : function(){
return $http.get('api/tours').then(function(response){
return response.data;
});
}
}
});
|
let M = {};
M.global_pure_white = "global_pure_white";
M.global_pic_toast_bg = "global_pic_toast_bg";
M.head_mask_png = "global_pic_farmer";
//默认头像
M.user_default0 = "global_pic_farmer"; //默认方形男头像
M.user_default1 = "global_pic_farmer"; //默认方形女头像
M.default_man_icon = "global_pic_man"; //默认圆形男头像
M.default_girl_icon = "global_pic_women"; //默认圆形女头像
M.default_lord_icon = "global_pic_lord"; //地主头像
M.default_farmer_icon = "global_pic_farmer"; //农民头像
M.lord_poker_back = "poker_back";
M.lord_poker_back_other = "poker_back_other";
M.lord_poker_select = "poker_select";
M.poker_bg_big = "poker_bg_big";
M.poker_bg_big1 = "poker_bg_big1";
M.poker_bg_small = "poker_bg_small";
M.lord_poker_f03 = "poker_f03";
M.lord_poker_f04 = "poker_f04";
M.lord_poker_f05 = "poker_f05";
M.lord_poker_f06 = "poker_f06";
M.lord_poker_f07 = "poker_f07";
M.lord_poker_f08 = "poker_f08";
M.lord_poker_f09 = "poker_f09";
M.lord_poker_f10 = "poker_f10";
M.lord_poker_f11 = "poker_f11";
M.lord_poker_f12 = "poker_f12";
M.lord_poker_f13 = "poker_f13";
M.lord_poker_f14 = "poker_f14";
M.lord_poker_f15 = "poker_f15";
M.lord_poker_h03 = "poker_h03";
M.lord_poker_h04 = "poker_h04";
M.lord_poker_h05 = "poker_h05";
M.lord_poker_h06 = "poker_h06";
M.lord_poker_h07 = "poker_h07";
M.lord_poker_h08 = "poker_h08";
M.lord_poker_h09 = "poker_h09";
M.lord_poker_h10 = "poker_h10";
M.lord_poker_h11 = "poker_h11";
M.lord_poker_h12 = "poker_h12";
M.lord_poker_h13 = "poker_h13";
M.lord_poker_h14 = "poker_h14";
M.lord_poker_h15 = "poker_h15";
M.lord_poker_m03 = "poker_m03";
M.lord_poker_m04 = "poker_m04";
M.lord_poker_m05 = "poker_m05";
M.lord_poker_m06 = "poker_m06";
M.lord_poker_m07 = "poker_m07";
M.lord_poker_m08 = "poker_m08";
M.lord_poker_m09 = "poker_m09";
M.lord_poker_m10 = "poker_m10";
M.lord_poker_m11 = "poker_m11";
M.lord_poker_m12 = "poker_m12";
M.lord_poker_m13 = "poker_m13";
M.lord_poker_m14 = "poker_m14";
M.lord_poker_m15 = "poker_m15";
M.lord_poker_r03 = "poker_r03";
M.lord_poker_r04 = "poker_r04";
M.lord_poker_r05 = "poker_r05";
M.lord_poker_r06 = "poker_r06";
M.lord_poker_r07 = "poker_r07";
M.lord_poker_r08 = "poker_r08";
M.lord_poker_r09 = "poker_r09";
M.lord_poker_r10 = "poker_r10";
M.lord_poker_r11 = "poker_r11";
M.lord_poker_r12 = "poker_r12";
M.lord_poker_r13 = "poker_r13";
M.lord_poker_r14 = "poker_r14";
M.lord_poker_r15 = "poker_r15";
M.lord_poker_16 = "poker_16";
M.lord_poker_17 = "poker_17";
M.lord_poker_color_16 = "poker_joker_small";
M.lord_poker_color_17 = "poker_joker_big";
M.lord_poker_color = [
"poker_color_r",
"poker_color_h",
"poker_color_m",
"poker_color_f",
];
M.poker_lord_flag_res = ["table_pic_dizhubiaoqian1", "table_pic_dizhubiaoqian2"];
M.poker_lord_show_res = ["table_pic_mingpaibq1", "table_pic_mingpaibq2"];
M.hall_classic_bg = {
"1": "hall_xs_1",
"2": "hall_cj_1",
"3": "hall_zj_1",
"4": "hall_zj_1",
"5": "hall_zj_1",
};
M.hall_unshuffle_bg = {
"1": "hall_xs_2",
"2": "hall_cj_2",
"3": "hall_zj_2",
"4": "hall_zj_2",
"5": "hall_zj_2",
};
M.competition_level = {
10: "level-global_level_qingtong_small",
20: "level-global_level_baiying_small",
30: "level-global_level_huangjin_small",
40: "level-global_level_bojin_small",
50: "level-global_level_zhuanshi_small",
60: "level-global_level_dashi_small",
70: "level-global_level_wangzhe_small",
80: "level-global_level_wangzhe_small",
90: "level-global_level_wangzhe_small",
100: "level-global_level_wangzhe_small",
110: "level-global_level_wangzhe_small",
120: "level-global_level_wangzhe_small",
130: "level-global_level_wangzhe_small",
140: "level-global_level_wangzhe_small",
};
M.competition_old_level = {
10: "level-global_level_qingtong_small",
20: "level-global_level_qingtong_small",
30: "level-global_level_qingtong_small",
40: "level-global_level_baiying_small",
50: "level-global_level_baiying_small",
60: "level-global_level_baiying_small",
70: "level-global_level_huangjin_small",
80: "level-global_level_huangjin_small",
90: "level-global_level_huangjin_small",
100: "level-global_level_zhuanshi_small",
110: "level-global_level_zhuanshi_small",
120: "level-global_level_zhuanshi_small",
130: "level-global_level_dashi_small",
140: "level-global_level_wangzhe_small",
},
M.lord_land_res = {
call: ["btn_txt-table_txt_jiaodizhu2", "btn_txt-table_txt_bujiao2"],
grab: ["btn_txt-table_txt_qiangdizhu", "btn_txt-table_txt_buqiang"],
buchu: ["btn_txt-table_txt_buchu", "btn_txt-table_txt_unable_buchu"],
chupai: ["btn_txt-table_txt_chupai", "btn_txt-table_txt_unable_chupai"],
one: ["btn_txt-table_txt_onescore", "btn_txt-table_txt_onescore_gray"],
two: ["btn_txt-table_txt_twoscore", "btn_txt-table_txt_twoscore_gray"],
three: ["btn_txt-table_txt_threecore", "btn_txt-table_txt_threecore_gray"],
};
//明牌倍数
M.showCardMultiple2 = "btn_txt-table_txt_mingpaix2";
M.showCardMultiple3 = "btn_txt-table_txt_mingpaix3";
M.showCardMultiple4 = "btn_txt-table_txt_mingpaix4";
M.mainBtnMessReviewed = "main_btn_mess_reviewed";
M.tableMenuExit = "table_btn_exit_menu";
M.tableMenuAuto = "table_btn_auto_menu";
M.tableMenuStand = "table_btn_standup_menu";
M.tableMenuSet = "table_btn_set_menu";
M.tableMenuExitPressed = "table_btn_exit_menu_pressed";
M.tableMenuAutoPressed = "table_btn_auto_menu_pressed";
M.tableMenuStandPressed = "table_btn_standup_menu_pressed";
M.tableMenuSetPressed = "table_btn_set_menu_pressed";
M.table_pic_countNum0 = "table_pic_num0";
M.table_pic_countNum1 = "table_pic_num1";
M.table_pic_countNum2 = "table_pic_num2";
M.table_pic_countNum3 = "table_pic_num3";
M.table_pic_countNum4 = "table_pic_num4";
M.table_pic_fen = "table_pic_fen";
M.chat_face_name = "chat_face_%s";
M.lord_userstatus_img = {
notCall: "btn_txt-table_txt_bujiao2",
oneScore: "btn_txt-table_txt_onescore",
twoScore: "btn_txt-table_txt_twoscore",
threeScore: "btn_txt-table_txt_threecore",
notRob: "btn_txt-table_txt_buqiang",
callLord: "btn_txt-table_txt_jiaodizhu2",
robLord: "btn_txt-table_txt_qiangdizhu",
double: "btn_txt-table_txt_jiabei",
superDouble: "btn_txt-table_txt_othersuperdouble",
notdouble: "btn_txt-table_txt_bujiabei",
notwant: "btn_txt-table_txt_buchu",
};
//互动表情
M.interactphiz_zhadan = "playerinfo_phiz_010"; //炸弹
M.interactphiz_bingtong = "playerinfo_phiz_003"; //冰桶
M.interactphiz_niubei = "playerinfo_phiz_004"; //干杯
M.interactphiz_qinwen = "playerinfo_phiz_008"; //亲吻
M.interactphiz_bixin = "playerinfo_phiz_011"; //比心
M.playerinfo_phiz_rose = "playerinfo_phiz_rose"; //送花
M.global_txt_ljhq = "global_txt_ljhq";
M.common_title_Buzhu = "common_title_Buzhu";
M.common_txt_fxlq = "common_txt_fxlq";
M.common_title_Jinbbz = "common_title_Jinbbz";
M.common_txt_fxjb_2 = "common_txt_fxjb_2";
//小段位内等级
M.result_level_res = {
10: "eventgameover_qingtong_level",
20: "eventgameover_baiyin_level",
30: "eventgameover_huangjin_level",
40: "eventgameover_bojin_level",
50: "eventgameover_zuanshi_level",
};
//大段位动画资源
M.result_seg_res = {
10: ["eventgameover_qingtong_biaoqian", "eventgameover_qingtong_chibang1", "eventgameover_qingtong_chibang2", "eventgameover_qingtong_kuang"],
20: ["eventgameover_baiyin_biaoqian", "eventgameover_baiyin_chibang1", "eventgameover_baiyin_chibang2", "eventgameover_baiyin_kuang"],
30: ["eventgameover_huangjin_biaoqian", "eventgameover_huangjin_chibang1", "eventgameover_huangjin_chibang2", "eventgameover_huangjin_kuang"],
40: ["eventgameover_bojin_biaoqian", "eventgameover_bojin_chibang1", "eventgameover_bojin_chibang2", "eventgameover_bojin_kuang"],
50: ["eventgameover_zuanshi_biaoqian", "eventgameover_zuanshi_chibang1", "eventgameover_zuanshi_chibang2", "eventgameover_zuanshi_kuang"],
60: ["eventgameover_dashi", "eventgameover_dashi_chibang1", "eventgameover_dashi_chibang2", "eventgameover_dashi_kuang"],
70: ["eventgameover_wangzhe_biaoqian", "eventgameover_wangzhe_chibang1", "eventgameover_wangzhe_chibang2", "eventgameover_wangzhe_kuang"],
80: ["eventgameover_wangzhe_biaoqian", "eventgameover_wangzhe_chibang1", "eventgameover_wangzhe_chibang2", "eventgameover_wangzhe_kuang"],
90: ["eventgameover_wangzhe_biaoqian", "eventgameover_wangzhe_chibang1", "eventgameover_wangzhe_chibang2", "eventgameover_wangzhe_kuang"],
100: ["eventgameover_wangzhe_biaoqian", "eventgameover_wangzhe_chibang1", "eventgameover_wangzhe_chibang2", "eventgameover_wangzhe_kuang"],
110: ["eventgameover_wangzhe_biaoqian", "eventgameover_wangzhe_chibang1", "eventgameover_wangzhe_chibang2", "eventgameover_wangzhe_kuang"],
120: ["eventgameover_wangzhe_biaoqian", "eventgameover_wangzhe_chibang1", "eventgameover_wangzhe_chibang2", "eventgameover_wangzhe_kuang"],
130: ["eventgameover_wangzhe_biaoqian", "eventgameover_wangzhe_chibang1", "eventgameover_wangzhe_chibang2", "eventgameover_wangzhe_kuang"],
140: ["eventgameover_wangzhe_biaoqian", "eventgameover_wangzhe_chibang1", "eventgameover_wangzhe_chibang2", "eventgameover_wangzhe_kuang"],
};
M.table_you_lose = "table_you_lose";
M.table_you_win = "table_you_win";
M.table_pic_event_fen = "table_pic_event_fen";
M.btn_danxuan1 = "global_btn_danxuan1";
M.btn_danxuan2 = "global_btn_danxuan2";
M.btn_duoxuan1 = "global_btn_duoxuan1";
M.btn_duoxuan2 = "global_btn_duoxuan2";
M.create_room_selectbg1 = "global_btn_danxuan1"; //立即邀请
M.create_room_selectbg2 = "global_btn_danxuan2"; //领取
M.global_coin = [
"",
"global_coin1",
"global_coin1",
"global_coin2",
"global_coin2",
"global_coin3",
"global_coin3",
"global_coin4",
];
M.global_diamond = [
"",
"global_diamond_1",
"global_diamond_2",
"global_diamond_3",
"global_diamond_4",
"global_diamond_4",
"global_diamond_4",
"global_diamond_4",
];
M.global_btn_new1 = "global_btn_new1";
M.global_btn_middle2 = "global_btn_middle2";
M.global_txt_qued = "global_txt_qued";
M.global_txt_continue = "global_txt_continue";
M.global_txt_qued_2 = "global_txt_qued_2";
M.global_pic_red = "global_pic_red";
M.global_pic_red1 = "global_pic_red1";
//首登内连胜奖励
M.welfare_grayp_big = "welfare_grayp_big";
M.welfare_grayp_small = "welfare_grayp_small";
M.welfare_redp_small = "welfare_redp_small";
M.welfare_redp_big = "welfare_redp_big";
M.welfare_bg_gray = "welfare_bg_gray";
M.welfare_bg_yellow = "welfare_bg_yellow";
M.welfare_bg_white = "welfare_bg_white";
M.welfare_pic_ylw = "welfare_pic_ylw";
M.welfare_btn_qw = "welfare_btn_qw";
M.welfare_btn_tab1 = "welfare_tab_1";
M.welfare_btn_tab2 = "welfare_tab_2";
M.welfare_tab_m_0 = "welfare_tab_m_0";
M.welfare_tab_m_1 = "welfare_tab_m_1";
M.welfare_task_1 = "welfare_t_1";
M.welfare_task_2 = "welfare_t_2";
M.welfare_winstreak_1 = "welfare_s_1";
M.welfare_winstreak_2 = "welfare_s_2";
M.welfare_welfare_1 = "welfare_w_1";
M.welfare_welfare_2 = "welfare_w_2";
M.welfare_txt_double = "welfare_txt_double";
M.welfare_huiselingjiang = "welfare_huiselingjiang";
M.task_rechange = "task_rechange";
M.task_rechange_1 = "task_rechange_1";
M.task_btn_bg = "common_btn_bg";
M.task_getByShare = "common_getByShare";
M.task_getByVideo = "common_getByVideo";
M.task_btn_getByShare = "task_btn_getByShare";
M.task_btn_getByVideo = "task_btn_getByVideo";
M.task_item_pro_3 = "task_item_pro_3";
M.task_item_pro_1 = "task_item_pro_1";
M.task_item_bg = [
"task_item_bg_2",
"task_item_bg_1",
"task_item_bg_3"
];
M.task_item_icon = [
"task_item_icon_2",
"task_item_icon_1",
"task_item_icon_3"
];
M.task_item_1 = [
"",
"task_item_coin_1",
"task_item_redpacket_1",
"task_item_cardcounter_1",
];
M.task_item_2 = [
"",
"task_item_coin_2",
"task_item_redpacket_2",
"task_item_cardcounter_2",
];
M.task_item_coin = [
"",
"task_item_coin_1",
"task_item_coin_2",
"task_item_coin_3",
"task_item_coin_4",
"task_item_coin_5",
"task_item_coin_6",
];
M.table_lucky_reward_icon = [
"",
"table_coin",
"table_redpacket",
"table_cardcounter",
];
M.task_btn_1 = "task_btn_1";
M.task_btn_2 = "task_btn_2";
M.task_btn_3 = "task_btn_3";
M.task_txt_go = "task_txt_go";
M.task_txt_havepick = "task_txt_havepick";
M.task_txt_pick = "task_txt_pick";
export default M;
|
var util = require('util');
var SC = require('./core');
module.SC = SC;
require('./private/observer_set');
require('./mixins/observable');
require('./system/enumerator');
require('./mixins/enumerable');
require('./system/range_observer');
require('./mixins/array');
require('./mixins/comparable');
require('./mixins/copyable');
require('./mixins/delegate_support');
require('./mixins/freezable');
require('./system/set');
require('./system/object');
require('./private/chain_observer');
require('./private/observer_queue');
require('./protocols/observable_protocol');
require('./protocols/sparse_array_delegate');
require('./system/binding');
require('./system/error');
require('./system/index_set');
require('./system/logger');
require('./system/run_loop');
require('./system/selection_set');
require('./system/sparse_array');
exports = module.exports = SC;
|
import {
ADD_ARTICLES,
ADD_ARTICLES_ERROR,
REMOVE_ARTICLE_MESSAGE,
} from '../../../constants';
import { addArticles, addArticlesError, removeArticleMessage } from '..';
describe('Article action creators', () => {
it('Should dispatch ADD_ARTICLE type', () => {
expect(addArticles({}).type).toEqual(ADD_ARTICLES);
});
it('Should dispatch ADD_ARTICLES_ERROR type', () => {
expect(addArticlesError({}).type).toEqual(ADD_ARTICLES_ERROR);
});
it('Should dispatch ADD_ARTICLE type', () => {
expect(removeArticleMessage({}).type).toEqual(REMOVE_ARTICLE_MESSAGE);
});
});
|
const path = require("path")
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
flags: {
DEV_SSR: false,
},
siteMetadata: {
title: `Canberra`,
description: `Ranked as the world’s most liveable city and region, Canberra offers a quality of life incomparable to anywhere else.`,
author: `@avenue`,
siteUrl: "https://canberra.com.au/",
},
plugins: [
`gatsby-plugin-svgr`,
// `gatsby-plugin-offline`,
`gatsby-plugin-force-trailing-slashes`,
`gatsby-plugin-remove-serviceworker`,
`gatsby-plugin-react-helmet`,
{
resolve: `gatsby-plugin-root-import`,
options: {
components: path.join(__dirname, `src/components`),
context: path.join(__dirname, `src/context`),
pages: path.join(__dirname, "src/pages"),
images: path.join(__dirname, `src/images`),
icons: path.join(__dirname, `src/images/icons`),
utils: path.join(__dirname, `src/utils`),
helpers: path.join(__dirname, `src/utils/helpers`),
breakpoints: path.join(__dirname, `src/utils/breakpoints`),
queries: path.join(__dirname, `src/queries`),
hooks: path.join(__dirname, "src/hooks"),
},
},
"gatsby-plugin-remove-console",
{
resolve: `gatsby-plugin-sitemap`,
options: {
sitemapSize: 2000,
},
},
{
resolve: `gatsby-plugin-typography`,
options: {
pathToConfigModule: `src/utils/typography`,
omitGoogleFont: true,
},
},
{
resolve: `gatsby-plugin-create-client-paths`,
options: { prefixes: [`/preview/*`] },
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
},
{
resolve: `gatsby-source-graphql`,
options: {
typeName: `WPGraphQL`,
fieldName: `wpgraphql`,
url: process.env.GATSBY_GRAPHQL_ENDPOINT,
},
},
{
resolve: "gatsby-plugin-google-tagmanager",
options: {
id: "GTM-KCJTG8J",
},
},
{
resolve: `gatsby-plugin-google-fonts`,
options: {
fonts: [`Montserrat\:300,600`],
},
},
{
resolve: `gatsby-plugin-styled-components`,
options: {
displayName: true,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
// this (optional) plugin enables Progressive Web App + Offline functionality
// To learn more, visit: https://gatsby.dev/offline
// `gatsby-plugin-offline`,
],
}
|
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import data from '../api/data';
export default new Vuex.Store({
state: {
students: []
},
getters: {
},
actions: {
getStudens(context) {
context.commit('setStudents')
}
},
mutations: {
setStudents(state) {
state.students = data.getStudents();
}
}
})
|
const Interviewer = require('./Interviewer');
const HiringManager = require('./HiringManager');
class DevelopmentManager extends HiringManager {
makeInterviewer() {
return new Interviewer.Developer()
}
}
class MarketingManager extends HiringManager {
makeInterviewer() {
return new Interviewer.CommunityExecutive()
}
}
module.exports = {
DevelopmentManager,
MarketingManager
}
|
var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var HashTable = require('hashtable');
var MessageSender = require('./message-sender');
function SmartBot(){
this.constructor.apply(this,arguments);
}
SmartBot.prototype.constructor = function(config){
this.config = config;
this.messageSender = new MessageSender(config.pageAccessToken);
this.senderData = new HashTable();
this.steps = new HashTable();
this.startStep = 'start';
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
app.get('/', this.verificationHandler.bind(this));
app.post('/',this.messageHandler.bind(this));
http.createServer(app).listen(app.get('port'), function() {
console.log('Smartbot ready');
console.log('listening on port: ' + app.get('port'));
});
};
SmartBot.prototype.verificationHandler = function(req, res) {
if (req.query['hub.verify_token'] === this.config.verifyToken) {
console.log('verify_token ok, sending hub.challenge back');
console.log(req.query['hub.challenge']);
res.send(req.query['hub.challenge']);
}
console.log('Error, wrong validation token!');
res.send('Error, wrong validation token!');
};
SmartBot.prototype.messageHandler = function(req, res) {
res.send('message received');
req.body.entry.map(this.entryHandler.bind(this));
};
SmartBot.prototype.entryHandler = function(entry) {
entry.messaging.map(this.messagingHandler.bind(this));
};
SmartBot.prototype.messagingHandler = function(messaging) {
var sender_id = messaging.sender.id;
var text = messaging.message.text;
console.log("Message received");
console.log("sender_id: ",sender_id);
console.log("text: ",text);
var data = this.getNextStep(sender_id);
console.log("getNextStep: ",data);
var Step = require("./step/" + data.type);
var step = new Step(data.config,sender_id,text,this.messageSender);
step.run();
};
SmartBot.prototype.addStep = function(id,type,config) {
this.steps.put(id,{
type: type,
config: config
});
};
SmartBot.prototype.getNextStep = function(sender_id) {
var senderData = this.getSenderData(sender_id);
return this.steps.get(senderData.step);
};
SmartBot.prototype.getSenderData = function(sender_id) {
if(!this.senderData.has(sender_id))
{
this.senderData.put(sender_id,{
step: this.startStep
});
}
return this.senderData.get(sender_id);
};
SmartBot.prototype.setStartStep = function(id) {
this.startStep = id;
};
module.exports = SmartBot;
|
import Mock from 'mockjs';
export default Mock.mock('l1B_data', {
"msg": "请求成功",
"data": {
"month|3":[{
"clock|23-89": 1,
"planValue|24545-84545": 1,
"factValue|24545-84545": 1
}],
"year|3": [{
"clock|23-89": 1,
"planValue|556745658-834556856": 1,
"factValue|556745658-834556856": 1
}]
},
"status": "success"
})
|
var Rain = function(game, x, y, maxParticles) {
Phaser.Particles.Arcade.Emitter.call(this, game, x, y, maxParticles);
this.width = game.world.width + (game.world.width);
this.makeParticles('rain');
this.minParticleScale = 0.1;
this.maxParticleScale = 0.5;
this.setYSpeed(480, 680);
this.setXSpeed(-5, 5);
this.setAlpha(0.2, 1, 0);
this.minRotation = 0;
this.maxRotation = 0;
//this.angle = 30; // uncomment to set an angle for the rain.
this.start(false, 2000, 0, 0);
};
Rain.prototype = Object.create(Phaser.Particles.Arcade.Emitter.prototype);
Rain.prototype.constructor = Rain;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.