text stringlengths 7 3.69M |
|---|
import "./styles.css";
const onClickAdd = () => {
//taskの取得とinputの初期化
const inputText = document.getElementById("add-text").value;
//入力確認
if (!inputText) {
alert("TODOを入力してください");
} else {
document.getElementById("add-text").value = "";
// incomplete-listにtaskを追加
createIncompleteList(inputText);
}
};
//incomplete-list作成
const createIncompleteList = (text) => {
const li = document.createElement("li");
const div = document.createElement("div");
div.className = "list-row";
const p = document.createElement("p");
p.className = "todo-sub";
//taskを代入
p.innerText = text;
const compButton = document.createElement("button");
compButton.innerText = "完了";
const deliteButton = document.createElement("button");
deliteButton.innerText = "削除";
// listの雛形を生成
li.appendChild(div);
div.appendChild(p);
div.appendChild(compButton);
div.appendChild(deliteButton);
//incomplite-listに追加
document.getElementById("incomplete-list").appendChild(li);
//完了ボタンが押されたらtaskをcomplete-listに移動
compButton.addEventListener("click", () => {
//完了ボタンが押されたリストをincomplete-listから削除
deliteFromIncompleteList(compButton);
//complete-list作成
const addList = compButton.parentNode.parentNode;
const p = document.createElement("p");
p.className = "todo-sub";
p.innerText = addList.firstElementChild.firstElementChild.innerText;
const backButton = document.createElement("button");
backButton.innerText = "戻す";
//liの雛形を初期化して再利用
addList.firstElementChild.textContent = null;
addList.firstElementChild.appendChild(p);
addList.firstElementChild.appendChild(backButton);
document.getElementById("complete-list").appendChild(addList);
//戻すボタンを押されたらincomplete-listにtaskを戻す
backButton.addEventListener("click", () => {
//戻るボタンが押されたリストをcomplete-listから削除
deliteFromCompleteList(backButton);
// incomplete-listにtaskを追加
const backList = backButton.parentNode.parentNode;
const moveText = backList.firstElementChild.firstElementChild.innerText;
createIncompleteList(moveText);
});
});
//削除ボタンが押されたリストをincomplete-listから削除
deliteButton.addEventListener("click", () => {
deliteFromIncompleteList(deliteButton);
});
};
//リスト削除
const deliteFromIncompleteList = (button) => {
const deliteTarget = button.parentNode.parentNode;
document.getElementById("incomplete-list").removeChild(deliteTarget);
};
const deliteFromCompleteList = (button) => {
const deliteTarget = button.parentNode.parentNode;
document.getElementById("complete-list").removeChild(deliteTarget);
};
document
.getElementById("add-task")
.addEventListener("click", () => onClickAdd());
|
const input = require("fs").readFileSync("/dev/stdin", "utf8")
let cin = input.split(/ |\n/), cid = 0
const next = () => cin[cid++]
const nexts = (n) => cin.slice(cid, cid+=n).map(i=>parseInt(i))
const [X, Y] = nexts(2)
t = (Y - 2 * X) / 2
c = X - t
if (t >= 0 && c >= 0 && t + c == X && 4*t + 2*c == Y && Number.isInteger(t) && Number.isInteger(c)) {
console.log('Yes')
} else {
console.log('No')
}
|
var tracer = {
name: "Tracer",
attack: 35,
counter: 5,
health: 180
};
var winston = {
name: "Winston",
attack: 10,
counter: 8,
health: 400
};
var reinhardt = {
name: "Reinhardt",
attack: 40,
counter: 15,
health: 300
};
var mei = {
name: "Mei",
attack: 25,
counter: 18,
health: 250
};
//Assign objects to respective classes
$(".tracer").data(tracer);
$(".winston").data(winston);
$(".mei").data(mei);
$(".reinhardt").data(reinhardt);
var hero;
var defender;
var num_enemies = 3;
$(".character").one("click", function() {
$(this).removeClass("character");
$(this).addClass("pro");
$(this).appendTo(".hero");
hero = $(this).data();
console.log(hero.attack);
$(".character").addClass("enemy").removeClass("character").off("click");
$(".enemy").appendTo(".enemies");
$(".enemy").one("click", function() {
$(this).addClass("defense");
defender = $(this).data();
console.log(defender.attack);
$(this).appendTo(".defender");
});
});
function attack(){
defender.health -= hero.attack;
hero.health -= defender.counter;
hero.attack += 5;
}
$(".btn_attack").on("click", function() {
attack();
$(".hero .health").html("<br>" + hero.health);
$(".defender .health").html("<br>" + defender.health);
$(".game_desc").html("You attacked " + defender.name + " for " + hero.attack + " damage.<br>" + defender.name + " attacked you back for " + defender.attack + " damage.");
if(hero.health <= 0 && num_enemies > 0){
$(".game_desc").html("You were defeated by " + defender.name + ". Click 'restart' to start a new game!");
document.body.innerHTML += "<div class='row'><button type='button' class='btn btn-secondary btn-sm restart'>Restart</button></div>";
}
else if(defender.health <= 0){
$(".defender").empty();
defender.attack = 0;
$(".game_desc").html("You have defeated " + defender.name);
num_enemies--;
}
if(num_enemies === 0){
alert("Congratulations! You have defeated all the enemies. Click the 'Restart' button to start a new game.");
document.body.innerHTML += "<div class='row'><button type='button' class='btn btn-secondary btn-sm restart'>Restart</button></div>";
}
$(".restart").on("click", function(){
location.reload();
})
console.log(hero.attack);
console.log(defender.health);
});
$(".restart").on("click", function(){
location.reload();
})
|
module.exports = function (creep) {
var freeRepairer = true
if (creep.energy == 0) {
var nearestSpawn = creep.pos.findNearest(Game.MY_SPAWNS,{
filter: function (spawn) {
return spawn.energy > 0;
}
});
if(nearestSpawn){
creep.moveTo(nearestSpawn);
nearestSpawn.transferEnergy(creep);
}
freeRepairer = false;
} else {
var allRoadsAndWalls = creep.room.find(Game.STRUCTURES, {
filter: function (structure) {
return (structure.structureType == "road" || structure.structureType == "constructedWall") && structure.hits < (structure.hitsMax / 1.3);
}
});
var target = creep.pos.findNearest(Game.MY_STRUCTURES, {
filter: function (object) {
// console.log(object.hits+" of "+object.hitsMax+" but "+(object.hitsMax/1.3)+" for "+object.structureType);
return object.hits < (object.hitsMax / 1.3);
}
});
//for (var obj in allRoadsAndWalls) {
// console.log(obj+"-----");
// // console.log(struct.hits+" of "+struct.hitsMax+" for "+struct.structureType);
//}
if (target) {
creep.moveTo(target);
creep.repair(target);
freeRepairer = false;
}
if(allRoadsAndWalls.length){
creep.moveTo(allRoadsAndWalls[0]);
creep.repair(allRoadsAndWalls[0]);
freeRepairer = false;
}
}
return freeRepairer;
} |
const path = require('path')
const autoprefixer = require('autoprefixer')
const webpackMarge = require('webpack-merge')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const paths = {
src: path.join(__dirname, 'src'),
compiled: path.join(__dirname, 'dist')
}
const env = process.env.NODE_ENV || 'development'
let isProduction = false
if (env === 'production') {
isProduction = true
}
console.log('[env]', env, '[isProduction]', isProduction)
module.exports = () => {
const common = {
entry: { app: [path.join(paths.src, 'app', 'index.js')] },
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
},
output: {
path: paths.compiled,
filename: 'app.js'
}
}
const dev = webpackMarge(common, {
module: {
rules: [
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
importLoaders: 2,
modules: true
}
},
{
loader: 'sass-loader',
options: {
outputStyle: 'expanded',
sourceMap: true,
sourceMapContents: true
}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(paths.src, 'index.html'),
filename: 'index.html'
})
]
})
const prod = webpackMarge(common, {
module: {
rules: [
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
modules: true,
minimize: true,
sourceMap: true,
importLoaders: 2,
localIdentName: '[name]__[local]'
}
},
{
loader: 'postcss-loader',
options: {
plugins: (loader) => [
autoprefixer({ browsers: ['last 2 versions', 'ie >= 11'] })
],
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
outputStyle: 'expanded',
sourceMap: true,
sourceMapContents: true
}
}
]
})
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(paths.src, 'index.html'),
filename: 'index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
new CleanWebpackPlugin(paths.compiled, {
exclude: '.gitignore'
}),
new UglifyJsPlugin({
compressor: {
screw_ie8: true,
warnings: false
},
mangle: {
screw_ie8: true
},
output: {
comments: false,
screw_ie8: true
},
sourceMap: true
}),
new ExtractTextPlugin('[name].css')
]
})
return isProduction ? prod : dev
}
|
import React from 'react';
import QaAction from '../qa-action';
export default class QaInput extends QaAction {
action() {
this._update(this._closeQa(this.props.apply));
}
render() {
return (<div
className={'action' +
(this.props.disabled ? ' disabled' : '') +
(this.props.className ? ' ' + this.props.className : '')
} >
{this.props.children}
<button onKeyDown={this.action} onClick={this.action}>APPLY</button>
</div>);
}
}
QaInput.contextTypes = {
handleUpdateClose: React.PropTypes.func,
updateTarget: React.PropTypes.object,
};
|
var res = {
HelloWorld_png : "res/HelloWorld.png",
tile_0 : "res/tile_0.png",
tile_1: "res/tile_1.png",
tile_2: "res/tile_2.png",
tile_3: "res/tile_3.png",
tile_4: "res/tile_4.png",
tile_5: "res/tile_5.png",
tile_6: "res/tile_6.png",
tile_7: "res/tile_7.png",
target_png: "res/target.png",
cover: "res/cover.jpg",
};
var g_resources = [];
for (var i in res) {
g_resources.push(res[i]);
}
|
import React from 'react'
import useForm from '../../hooks/useInputValue.jsx'
import { Form, Input, Title, Error } from './styles'
import { SubmitButton } from '../SubmitButton/index.jsx'
export const UserForm = ({ error, disabled, onSubmit, title }) => {
const { form, handleInput } = useForm({
email: '',
password: ''
})
const handleSubmit = e => {
e.preventDefault()
onSubmit({ email: form.email, password: form.password })
}
return (
<>
<Form disabled={disabled} onSubmit={handleSubmit}>
<Title>{title}</Title>
<Input
type='email'
name='email'
disabled={disabled}
placeholder='Email'
onChange={handleInput}
value={form.email}
/>
<Input
type='password'
name='password'
disabled={disabled}
placeholder='Password'
onChange={handleInput}
value={form.password}
/>
<SubmitButton disabled={disabled}>{title}</SubmitButton>
</Form>
{error && <Error> {error}</Error>}
</>
)
}
|
var StackMembershipView = ControllerView.extend({
/** @class StackMembershipView
* @author drscannell
* @augments ControllerView
* @constructs StackMembershipView object */
tagName: 'option',
className: 'stack',
initialize: function(options) {
this.listenTo(this.model, 'change', this.handleModelChange);
},
setChecked: function(shouldCheck) {
this.options.isChecked = shouldCheck;
},
handleModelChange: function() {
if ( this.model.getDeleted() ) {
this.remove();
} else {
this.render();
}
},
render: function() {
var name = this.model.getName();
var display = name;
if ('isChecked' in this.options && this.options.isChecked) {
display = '+ ' + display;
} else if ('isChecked' in this.options) {
display = '- ' + display;
}
this.$el.attr('value', this.model.getId());
this.$el.html(display);
return this;
}
});
|
// function getDictionary() {
// return {
// }
// }
const SET_SUMMARY = 'SET_SUMMARY';
const SET_USER_NAME = 'SET_FIRST_NAME';
console.log(2); |
import ApiService from '@/services/api.service'
import { API_URL } from '@/services/api.configs'
const RestaurantService = {
query () {
return ApiService.get(API_URL + '/restaurants')
},
get (id) {
return ApiService.get(API_URL + '/restaurants/' + id)
}
}
export default RestaurantService
|
import jwt from 'jsonwebtoken'
import config from '../config/main'
export function isAuthenticated () {
const token = window.localStorage.getItem('token-ea')
if (token === null) {
return false
}
try {
jwt.verify(token, config.secret)
return true
} catch (err) {
window.localStorage.removeItem('token-ea')
console.error(err)
return false
}
} |
import React from "react";
import { Link } from "react-router-dom";
import { Menu } from "antd";
export default class TopMenu extends React.Component {
render() {
return <div>
<Menu theme="dark" mode="horizontal" defaultSelectedKeys={["1"]} style={{ lineHeight: "64px" }}>
<Menu.Item key="1">
<Link to="/app/index">EOS 区块链信息</Link>
</Menu.Item>
<Menu.Item key="2">
<Link to="/app/hash">hash</Link>
</Menu.Item>
<Menu.Item key="3">
<Link to="/app/wallet">钱包</Link>
</Menu.Item>
<Menu.Item key="4">
<Link to="/app/transfer">转账</Link>
</Menu.Item>
<Menu.Item key="5">
<Link to="/app/history">交易记录</Link>
</Menu.Item>
</Menu>
</div>;
}
}
|
function findUniqueElements(arr) {
let xxory = 0;
//find the all element xor
for (let index = 0; index < arr.length; index++) {
xxory = xxory ^ arr[index]; // 5^4^1^3^4^2^5^1 -> 3^1-> 01
}
//getting RSB set via masking // 01 = 01 & 11
let rsbs = xxory & -xxory;
let x = 0; // set bit part
let y = 0; // unset bit part
// Traversing the array again
for (let index = 0; index < arr.length; index++) {
if (arr[index] & (rsbs == true)) {
// if rsb is unset
x = x ^ arr[index];
} else {
//if rsb is set
y = y ^ arr[index];
}
}
console.log(x); //3
console.log(y); //2
}
let arr = [5, 4, 11, 3, 4, 2, 5, 11];
findUniqueElements(arr);
|
const arrUsers = ['Happy User', 'Mary', 'Dima', 'Zhenya Zh.', 'Vika L', 'Nina Art', 'Nika I', 'Vs Ko', 'Ivan ', 'Marta', 'Zhenya H.', 'Sasha', 'Pasha', 'Ira', 'Vero', 'Dima'];
const arrActiveUsers = ['Happy User', 'Dima', 'Zhenya Zh.', 'Sasha', 'Pasha', 'Ira', 'Vero'];
const arr = [
{
id: '1',
text: 'Привет!',
createdAt: new Date('2020-10-11T23:01:10'),
author: 'Иванов Иван',
isPersonal: true,
to: 'Петров Петр',
},
{
id: '2',
text: 'Как дела?',
createdAt: new Date('2020-10-11T23:01:52'),
author: 'Петров Петр',
isPersonal: false,
},
{
id: '3',
text: 'Я думаю приготовить что-нибудь особенное сегодня вечером. Что посоветуете?',
createdAt: new Date('2020-10-12T23:02:15'),
author: 'Happy User',
isPersonal: false,
},
{
id: '4',
text: 'Нужно подумать...',
createdAt: new Date('2020-10-12T23:03:14'),
author: 'Anastasia',
isPersonal: false,
},
{
id: '5',
text: 'ты любишь мясо?',
createdAt: new Date('2020-10-12T23:04:37'),
author: 'Иван Иванович',
isPersonal: true,
to: 'Happy User',
},
{
id: '6',
text: 'Я скорее вегетарианец. Я предпочитаю фрукты и овощи.В особенности мне нравятся блюда из тыквы или цукини. Ещё я люблю фруктовые салаты.',
createdAt: new Date('2020-10-12T23:06:01'),
author: 'Happy User',
isPersonal: true,
to: 'Иван Иванович',
},
{
id: '7',
text: 'Как насчет сезонных салатов? Например, летом мне нравится есть салаты из свежих помидоров и огурцов с луком и различными приправами.',
createdAt: new Date('2020-10-12T23:06:15'),
author: 'Mary',
isPersonal: false,
},
{
id: '8',
text: 'Вкусно получается суп из цукини и салат из свежих овощей с итальянским соусом',
createdAt: new Date('2020-10-12T23:07:41'),
author: 'Sasha',
isPersonal: false,
},
{
id: '9',
text: 'Что лучше приготовить на десерт?',
createdAt: new Date('2020-10-12T23:10:11'),
author: 'Vika',
isPersonal: false,
},
{
id: '10',
text: 'Я бы хотела попробовать торт с корицей и ирландским кремом.',
createdAt: new Date('2020-10-12T23:00:00'),
author: 'Anastasia',
isPersonal: false,
},
{
id: '11',
text: 'Звучит вкусно.',
createdAt: new Date('2020-10-12T23:12:12'),
author: 'Happy User',
isPersonal: false,
},
{
id: '12',
text: 'А у меня сегодня на ужин паста с жареным лососем.',
createdAt: new Date('2020-10-12T23:13:11'),
author: 'Sasha',
isPersonal: false,
},
{
id: '13',
text: 'Ты сама готовила?',
createdAt: new Date('2020-10-12T23:14:16'),
author: 'Happy User',
isPersonal: true,
to: 'Sasha',
},
{
id: '14',
text: 'Да, сама.',
createdAt: new Date('2020-10-12T23:15:18'),
author: 'Sasha',
isPersonal: true,
to: 'Happy user',
},
{
id: '15',
text: 'Круто!',
createdAt: new Date('2020-10-12T23:14:21'),
author: 'Mary',
isPersonal: false,
},
{
id: '16',
text: 'Вау!',
createdAt: new Date('2020-10-12T23:14:02'),
author: 'Vika',
isPersonal: false,
},
{
id: '17',
text: 'Great!',
createdAt: new Date('2020-10-12T23:16:03'),
author: 'Иван Иванович',
isPersonal: false,
},
{
id: '18',
text: 'Да, лосось полезен для здоровья.',
createdAt: new Date('2020-10-12T23:17:05'),
author: 'Sasha',
isPersonal: false,
},
{
id: '19',
text: 'Всем хорошего вечера!',
createdAt: new Date('2020-10-12T23:18:23'),
author: 'Sasha',
isPersonal: false,
},
{
id: '20',
text: 'Пока!',
createdAt: new Date('2020-10-12T23:18:11'),
author: 'Happy User',
isPersonal: false,
},
{
id: '21',
text: 'Привет!',
createdAt: new Date('2020-10-11T23:01:10'),
author: 'Иванов Иван',
isPersonal: true,
},
];
const secret = new WeakMap();
class Messages {
constructor(msg) {
this._createdAt = new Date(msg.createdAt) || new Date(msg._createdAt);
this._id = msg.id || msg._id;
this._author = msg.author || msg._author;
this.text = msg.text;
this.isPersonal = msg.isPersonal;
this.to = msg.to;
}
get id() {
return this._id;
}
get author() {
return this._author;
}
get createdAt() {
return this._createdAt;
}
set id(id) {
this._id = id;
}
set author(author) {
this._author = author;
}
set createdAt(createdAt) {
this._createdAt = createdAt;
}
}
class MessageList {
constructor() {
this._msgList = JSON.parse(localStorage.getItem('msgStorage'), (key, value) => {
if (key === 'createdAt' || key === '_createdAt') {
return new Date(value);
} return value;
}).map((item) => new Messages(item));
this._user = JSON.parse(localStorage.getItem('user'));
this.results = [];
this.item = null;
this.messagesId = {};
this.messagesError = [];
}
get user() {
return this._user;
}
set user(user) {
this._user = user;
}
get msgList() {
return this._msgList;
}
set msgList(msgList) {
this._msgList = msgList;
}
static validate(msg) {
if (typeof msg.text === 'string'
&& msg.text.length <= 200
&& typeof msg.isPersonal === 'boolean'
&& ((msg.isPersonal === true && typeof msg.to === 'string')
|| (msg.isPersonal === false && typeof msg.to === 'undefined'))) {
return true;
}
return false;
}
addAll() {
for (const item of this._arrMsg) {
if (this.constructor.validate(item) === true) {
this._id = item.id;
this.text = item.text;
this._createdAt = item.createdAt;
this._author = item.author;
this.isPersonal = item.isPersonal;
this.to = item.to;
this.msgList.push(item);
localStorage.setItem('msgStorage', JSON.stringify(this.msgList));
} else {
this.messagesError.push(item);
}
}
return this.messagesError;
}
clear() {
this._arrMsg = [];
return this._arrMsg;
}
pag(skip, top, results) {
if (this.results.length > top) {
this.results = this.results.sort((a, b) => b.createdAt - a.createdAt).slice(skip, skip + top);
return this.results.sort((a, b) => a.createdAt - b.createdAt);
}
this.results = this.results.sort((a, b) => b.createdAt - a.createdAt).slice(skip, skip + top);
return this.results.sort((a, b) => a.createdAt - b.createdAt);
}
getPage(skip = 0, top = 10, filterConfig) {
this.results = Object.assign([], this.msgList);
if (filterConfig !== undefined) {
for (const key in filterConfig) {
if (filterConfig?.author) {
this.results = this.results.filter((name) => (name.author.toLowerCase().includes(filterConfig.author.toLowerCase())));
}
if (filterConfig?.text) {
this.results = this.results.filter((name) => (name.text.toLowerCase().includes(filterConfig.text.toLowerCase())));
}
if (filterConfig?.dataTo) {
this.results = this.results.filter((name) => name.createdAt < filterConfig.dataTo);
}
if (filterConfig?.dataFrom) {
this.results = this.results.filter((name) => name.createdAt > filterConfig.dataFrom);
}
} this.results.sort((a, b) => b.createdAt - a.createdAt);
}
if (filterConfig === undefined || filterConfig === null) {
this.results = this.results.sort((a, b) => -b.createdAt - a.createdAt);
}
if (this._user !== undefined || '') {
this.results = this.results.filter((name) => name.author === this._user
|| name.to === this._user
|| name.to === undefined);
} else {
this.results = this.results.filter((name) => name.to === undefined);
}
return this.pag(skip, top, this.results);
}
get(id) {
this.messagesId = this.msgList.find((name) => name.id == id);
return this.messagesId.text;
}
save() {
localStorage.setItem('msgStorage', JSON.stringify(this.msgList));
}
add(msg) {
if (this._user && MessageList.validate(msg)) {
msg.id = `${+new Date()}`;
msg.createdAt = new Date();
msg.author = this._user;
const newMsg = new Messages(msg);
this.msgList.push(newMsg);
this.save();
return true;
} return false;
}
edit(id, element) {
const index = this.mesgList.findIndex((item) => item.id == id);
if (this._user === this.mesgList[index].author) {
if (element?.text !== undefined) {
if (index > -1) {
console.log('Текст сообщения до редактирования:', this.mesgList[index].text);
if (this.constructor.validate(this.mesgList[index])) {
this.mesgList[index].text = element.text;
console.log('Текст сообщения после редактирования:', this.mesgList[index].text);
return true;
}
}
} if (element?.isPersonal !== undefined) {
if (index > -1) {
if (element.isPersonal === true && element.to !== undefined) {
console.log('Данные сообщения до редактирования:', this.mesgList[index].isPersonal, this.mesgList[index].to);
this.mesgList[index].isPersonal = element.isPersonal;
this.mesgList[index].to = element.to;
if (this.constructor.validate(this.mesgList[index])) {
console.log('Данные сообщения после редактирования:', this.mesgList[index].isPersonal, this.mesgList[index].to);
return true;
} return false;
}
if (element.isPersonal == false) {
console.log('Данные сообщения до редактирования: isPersonal =', this.mesgList[index].isPersonal, 'to =', this.mesgList[index].to);
this.mesgList[index].isPersonal = element.isPersonal;
delete this.mesgList[index].to;
if (this.constructor.validate(this.mesgList[index])) {
console.log('Данные сообщения после редактирования: isPersonal =', this.mesgList[index].isPersonal);
return true;
} return false;
} return false;
}
}
} else {
return false;
}
}
remove(id) {
const index = this.mesgList.findIndex((item) => item.id == id);
if (this._user === this.mesgList[index].author && index > -1) {
this.mesgList.splice(index, 1);
return true;
} return false;
}
}
class UserList {
constructor(users, activeUsers) {
this._users = JSON.parse(localStorage.getItem('allUser'));
this._activeUsers = activeUsers;
}
get users() {
return this._users;
}
get activeUsers() {
return this._activeUsers;
}
}
|
const Main = (input) => {
tmp = input.split(' ')
const N = tmp[0]
const Y = parseInt(tmp[1])
return calculate(N,Y)
}
const calculate = (n, y) => {
for (i = 0; i <= n; i++) {
remain = n - i
for (j = 0; j <= remain; j++) {
k = remain - j
if (1e3 * (10 * i + 5 * j + k) === y) {
console.log('%d %d %d', i, j, k)
return
}
}
}
console.log('-1 -1 -1')
return
}
//*この行以降は編集しないでください(標準入出力から一度に読み込み、mainを呼び出します)
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
|
/*/////////////////////////////////////////////////////////////////////////////
/// @summary Implements the entry point of a real-time JavaScript application.
/// @author Russell Klenk (russ@ninjabirdstudios.com)
///////////////////////////////////////////////////////////////////////////80*/
/// An object storing the global application state.
var State = {
/// The handle returned by window.requestAnimationFrame.
updateHandle : 0,
/// The computed desired presentation time step, in seconds.
frameTimeStep : 0.0,
/// The computed desired simulation time step, in seconds.
logicTimeStep : 0.0,
/// The amount of simulation time for the current frame, in seconds.
simulationTime : 0.0,
/// The amount of simulation time left over from the last frame, in seconds.
timeAccumulator : 0.0,
/// The number of simulation ticks on the current frame.
simulationCount : 0,
/// The DOM element monitored by window.requestAnimationFrame.
domElement : null,
/// The global application real-time clock state.
clock : null
};
/// Constants representing limit values. We enforce limits on the minimum
/// and maximum rates of simulation and presentation ticks. Generally, the
/// monitor refresh rate (and the browser's window.requestAnimationFrame
/// method) are limited to 60Hz, so we choose this as our minimum and
/// maximum presentation rate; however, the browser may select any suitable
/// presentation interval. Timing-wise we are limited to a resolution of
/// one millisecond, so our simulation rate minimum and maximum are set
/// accordingly. Override the application presentation, simulation and frame
/// request rate here.
var constants = {
/// The maximum reportable tick duration. If a clock tick duration exceeds
/// this value, the duration is clamped to this value.
MAXIMUM_TICK_DURATION : 1.0 / 2.0,
/// The minimum reportable tick duration. If a clock tick duration is less
/// than this value, this value is reported.
MINIMUM_TICK_DURATION : 1.0 / 1000.0,
/// The minimum number of simulation ticks per-second.
MINIMUM_SIMULATION_RATE : 1.0,
/// The maximum number of simulation ticks per-second.
MAXIMUM_SIMULATION_RATE : 1000.0,
/// The minimum number of presentation ticks per-second.
MINIMUM_PRESENTATION_RATE : 60.0,
/// The maximum number of presentation ticks per-second.
MAXIMUM_PRESENTATION_RATE : 60.0,
/// The number of presentation ticks per-second.
PRESENTATION_RATE : 60.0,
/// The number of simulation ticks per-second.
SIMULATION_RATE : 60.0,
/// The frame request rate of 60 frames per-second.
FRAME_REQUEST_RATE : 1000.0 / 60.0
};
/// Implements a fallback function based on window.setTimeout() for use
/// in cases where window.requestAnimationFrame() is not available.
/// @param callback A function (time:DOMTimeStamp) : void. The time
/// parameter is not supplied by all browsers.
/// @param element The DOM element being updated. This parameter is unused.
/// @return A handle value that can be used to cancel the timeout before
/// it fires.
function setTimeoutFallback(callback, element)
{
return window.setTimeout(callback, constants.FRAME_REQUEST_RATE);
}
/// Store a reference to the supported implementation of the new API
/// http://www.w3.org/TR/animation-timing/#requestAnimationFrame
/// Prototype: handle request_animation_frame(callback, element)
/// The callback takes a single parameter, the current timestamp.
var requestFrame = (function ()
{
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
setTimeoutFallback;
})();
/// Store a reference to the supported implementation of the new API
/// http://www.w3.org/TR/animation-timing/#cancelRequestAnimationFrame
/// Prototype: void cancelAnimationFrame(handle)
var cancelFrame = (function ()
{
return window.cancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.clearTimeout;
})();
/// Callback invoked when Bitstorm.js emits the 'dom:ready' event. The global
/// State object is initialized here.
/// @param bitstorm A reference to the global Bitstorm.js state.
function init(bitstorm)
{
var mind = constants.MINIMUM_TICK_DURATION;
var maxd = constants.MAXIMUM_TICK_DURATION;
var expd = 1.0 / constants.PRESENTATION_RATE;
var dom = document.getElementById('canvas');
var now = Date.now();
State.clock = bitstorm.createClock(expd, mind, maxd, now);
State.frameTimeStep = 1.0 / constants.PRESENTATION_RATE;
State.logicTimeStep = 1.0 / constants.SIMULATION_RATE;
State.simulationTime = 0.0;
State.timeAccumulator = 0.0;
State.simulationCount = 0;
State.domElement = dom;
}
/// Callback invoked when Bitstorm.js emits the 'window:ready' event. This
/// starts the real-time update loop.
/// @param bitstorm A reference to the global Bitstorm.js state.
function start(bitstorm)
{
// request notification when it's time to generate the next frame.
// this starts the real-time update loop. we continue until the
// caller-supplied tick callback returns false.
State.updateHandle = requestFrame(frameCallback, State.domElement);
}
/// The default runtime driver module tick callback function. The driver
/// tick callback is invoked every time an animation frame is requested.
/// @param elapsedTime The elapsed time since the last tick, in seconds.
/// @param currentTime The current absolute time value, in seconds.
/// @return true to execute the simulation and presentation portions of the
/// tick, or false to cancel the tick.
function tick(elapsedTime, currentTime)
{
return true;
}
/// The default runtime driver module presentation callback function. The
/// presentation callback is invoked exactly once per requested animation
/// frame, as long as simulation data is available.
/// @param elapsedTime The elapsed time since the last tick, in seconds.
/// @param currentTime The current absolute time value, in seconds.
/// @param tickTime A normalized time value in [0, 1] representing how far
/// into the current tick the driver is at the time of the call.
function present(elapsedTime, currentTime, tickTime)
{
/* empty */
}
/// The default runtime river module simulation callback function. The
/// simulation callback may be invoked one or more times per-frame.
/// @param elapsedTime The elapsed time since the last tick, in seconds.
/// @param currentTime The current absolute time value, in seconds.
function simulate(elapsedTime, currentTime)
{
/* empty */
}
/// Internal callback invoked when the system requests the next frame.
/// @param currTime The current timestamp value, in milliseconds. This
/// value is not supplied by all browsers.
function frameCallback(currTime)
{
// some browsers do not specify the current time.
if (!currTime)
{
// Date.now() returns the current time in milliseconds, which is
// the same as the value that would be passed in as currTime.
currTime = Date.now();
}
// cache all of our global state values into local variables.
var bitstorm = Bitstorm;
var clockState = State.clock;
var logicStep = State.logicTimeStep;
var frameStep = State.frameTimeStep;
var currentTime = 0.0;
var elapsedTime = 0.0;
// immediately schedule the next update. this lets us stay as close
// to 60 Hz as possible if we're forced to use the setTimeout fallback.
State.updateHandle = requestFrame(frameCallback, State.domElement);
// indicate the start of a new tick on the clock.
bitstorm.updateClock(clockState,currTime);
currentTime = clockState.clientTime;
elapsedTime = clockState.tickDuration;
// always execute the tick callback.
if (!tick(elapsedTime, currentTime))
{
// the tick callback returned false. cancel this frame.
return cancelFrame(State.updateHandle);
}
// execute the logic callback. the callback may execute zero times,
// one time, or more than one time depending on the update rate. the
// simulation logic always executes with a fixed time step.
//
// start out will all of the time from the current tick
// plus any left over time from the prior tick(s). step
// at a fixed rate until we have less than one timestep
// remaining. at each step, we call the simulate callback.
State.timeAccumulator += elapsedTime;
while (State.timeAccumulator >= logicStep)
{
simulate(logicStep, State.simulationTime);
State.simulationTime += logicStep;
State.timeAccumulator -= logicStep;
State.simulationCount += 1;
}
// execute the presentation callback. we do this only if
// the simulation callback is non-null, which means that
// we should have valid presentation state data.
if (State.simulationCount > 0)
{
// we may have some unused portion of time remaining
// in the timeAccumulator variable, which means that
// what gets presented is not quite up-to-date. the
// solution is to provide an interpolation factor we
// can use to interpolate between the last steps'
// simulation state and the current steps' state. This
// prevents temporal aliasing from occurring. See:
// http://gafferongames.com/game-physics/fix-your-timestep/
var t = State.timeAccumulator / logicStep; // in [0, 1].
present(elapsedTime, currentTime, t);
}
}
|
export default class AudioHandler {
/**
* This class is responsible for preloading sound clips, and playing them as requested.
* @class AudioHandler
* @author Martiens Kropff
* @returns {void}
*/
constructor() {
/**
* A list of audio files.
* @author Martiens Kropff
* @memberOf AudioHandler
* @type {object}
*/
this.audioFiles = {};
/**
* This object will keep track of what volume sounds should be played at if sound is muted, in case it gets unmuted again.
* @author Martiens Kropff
* @memberOf AudioHandler
* @type {object}
*/
this.muteVolumes = {};
/**
* Determines if audio should be muted or not.
* @author Martiens Kropff
* @memberOf AudioHandler
* @type {object}
*/
this.muted = false;
/**
* True if all audio clips have been preloaded.
* @author Martiens Kropff
* @memberOf AudioHandler
* @type {boolean}
*/
this.ready = false;
/**
* Keeps track of how many audio clips have been loaded.
* @author Martiens Kropff
* @memberOf AudioHandler
* @type {number}
*/
this.fileCounter = 0;
/*
*for (const i in this.audioFiles) {
* this.preload(i, this.audioFiles[i]);
*}
*/
this.loadedEvent = new Event('clip_loaded');
}
/**
* This function preloads an audio clip. Is called from the constructor.
* @author Martiens Kropff
* @memberOf AudioHandler
* @param {string} clip The clip that should be loaded.
* @param {string} url The clip's URL.
* @returns {void}
*/
preload(clip, url) {
this.audioFiles[clip] = url;
const audio = new Audio();
audio.addEventListener('canplaythrough', this.loaded(clip, url));
audio.src = url;
}
/**
* Once an audio clip has been loaded this function will create an HTML5 audio element that can be used to play or pause the specific clip.
* Once all the clips have been loaded this element sets the 'ready' class member to true.
* @author Martiens Kropff
* @memberOf AudioHandler
* @param {string} clip The clip that has been loaded.
* @param {string} url The clip's URL.
* @returns {void}
*/
loaded(clip, url) {
this.fileCounter += 1;
const audio = new Audio();
audio.loop = true;
const source = document.createElement('source');
source.type = 'audio/mpeg';
source.src = url;
audio.appendChild(source);
audio.volume = 0;
this.audioFiles[clip] = audio;
if (this.fileCounter === Object.keys(this.audioFiles).length) {
this.ready = true;
document.dispatchEvent(this.loadedEvent);
}
}
/**
* Plays and audio clip.
* @author Martiens Kropff
* @memberOf AudioHandler
* @param {string} clip The clip that should be played.
* @param {decimal} volume The volume that the clip should be played at.
* @returns {void}
*/
play(clip, volume = 1) {
if (typeof this.audioFiles[clip] !== 'undefined') {
if (!this.muted) {
this.audioFiles[clip].volume = volume;
} else {
this.muteVolumes[clip] = volume;
this.audioFiles[clip].volume = 0;
}
this.audioFiles[clip].play();
this.audioFiles[clip].currentTime = 0;
}
}
/**
* Sets the volume of an audio clip.
* @author Martiens Kropff
* @memberOf AudioHandler
* @param {string} clip The clip with the offensive volume.
* @param {decimal} volume The volume that the clip should be played at.
* @returns {void}
*/
volume(clip, volume) {
if (typeof this.audioFiles[clip] !== 'undefined') {
if (!this.muted) {
this.audioFiles[clip].volume = volume;
} else {
this.muteVolumes[clip] = volume;
this.audioFiles[clip].volume = 0;
}
}
}
/**
* Pauses and audio clip.
* @author Martiens Kropff
* @memberOf AudioHandler
* @param {string} clip The clip that should be paused.
* @returns {void}
*/
pause(clip) {
typeof this.audioFiles[clip] !== 'undefined' && this.audioFiles[clip].pause();
}
/**
* Sets the repeat property of a sound clip.
* @author Martiens Kropff
* @memberOf AudioHandler
* @param {string} clip The sound clip to be modified.
* @param {boolean} repeat Set to true if the sound should be repeated, false if not.
* @returns {void}
*/
repeat(clip, repeat) {
if (typeof this.audioFiles[clip] !== 'undefined') {
this.audioFiles[clip].loop = repeat;
}
}
/**
* Mutes all audio
* @author Martiens Kropff
* @memberOf AudioHandler
* @returns {void}
*/
mute() {
for (const i in this.audioFiles) {
this.muteVolumes[i] = this.audioFiles[i].volume;
this.audioFiles[i].volume = 0;
}
this.muted = true;
}
/**
* Unmutes audio.
* @author Martiens Kropff
* @memberOf AudioHandler
* @returns {void}
*/
unmute() {
for (const i in this.audioFiles) {
this.audioFiles[i].volume = this.muteVolumes[i];
}
this.muted = false;
}
}
|
import styled from "styled-components";
export const ImageContainer = styled.div`
@media (max-width: ${({ theme }) => theme.md}) {
display: none;
}
`;
|
exports.addKeyListeners = function(keyPressed) {
Object.assign(keyPressed, {left: 0, right: 0, up: 0, down: 0});
const keyCodeMapping = {
38: "up",
37: "left",
40: "down",
39: "right"
}
function onKey(event) {
const keyName = keyCodeMapping[event.keyCode];
keyPressed[keyName] = event.type == "keydown" ? 1 : 0;
}
document.addEventListener('keydown', onKey);
document.addEventListener('keyup', onKey);
}
exports.random = function(min, max) {
return min + Math.random()*(max-min);
} |
import Header from './Header';
import Footer from './Footer';
import Theme from './Theme';
import PhotoCard from './PhotoCard';
const common = {
Header,
Footer,
Theme,
PhotoCard,
};
export default common;
|
const { MongoClient } = require('mongodb');
const { MONGODB_URL } = require('../config');
const dbs = {};
const getConnection = (dbName, cb) => {
const mongodbConnectionUrl = `${MONGODB_URL}/${dbName}`;
if (dbs[mongodbConnectionUrl]) {
cb(null, dbs[mongodbConnectionUrl]);
} else {
MongoClient.connect(mongodbConnectionUrl, (err, db) => {
if (!err) {
dbs[mongodbConnectionUrl] = db;
db.on('close', () => {
delete dbs[mongodbConnectionUrl];
});
cb(null, dbs[mongodbConnectionUrl]);
return;
}
cb(err, null);
});
}
};
module.exports = getConnection;
|
import React, {Component} from 'react';
import {
Text,
View
} from 'react-native';
import EditItem from '../components/EditItem';
import styles from '../styles/Edit';
import common from '../styles/Common';
import lang from '../lang';
export default class EditScren extends Component {
static navs = {
'single': {screen: 'meowrental.EditSingle', title: lang.editSingle},
'house': {screen: 'meowrental.EditByHouse', title: lang.editByHouse},
'water': {screen: 'meowrental.EditByWater', title: lang.editByWater},
'power': {screen: 'meowrental.EditByPower', title: lang.editByPower},
'net': {screen: 'meowrental.EditByNet', title: lang.editByNet},
'preview': {screen: 'meowrental.Preview', title: lang.previewRental},
};
constructor(props) {
super(props);
}
navTo(navKey) {
let nav = EditScren.navs[navKey];
if (!nav) return;
this.props.navigator.push({
screen: nav.screen,
title: nav.title,
passProps: {},
navigatorStyle: {
tabBarHidden: true,
navBarHidden: false,
}
});
}
render() {
return (
<View style={common.container}>
<EditItem navTo={this.navTo.bind(this)} navKey='single' text={lang.editSingle} />
<EditItem navTo={this.navTo.bind(this)} navKey='house' text={lang.editByHouse} />
<EditItem navTo={this.navTo.bind(this)} navKey='water' text={lang.editByWater} />
<EditItem navTo={this.navTo.bind(this)} navKey='power' text={lang.editByPower} />
<EditItem navTo={this.navTo.bind(this)} navKey='net' text={lang.editByNet} />
<EditItem navTo={this.navTo.bind(this)} navKey='preview' text={lang.previewRental} />
</View>
);
}
}
|
import styled from "styled-components"
export const NavContainer = styled.div`
ul {
display: flex;
list-style-type: none;
flex-direction: row;
margin: 0;
padding: 0;
li {
margin-right: 10px;
}
a {
&:hover {
border-bottom: 3px solid #c2392a;
}
}
.active {
border-bottom: 3px solid #c2392a;
}
}
`
|
var PunchDetailsTable;
$(document).ready(function () {
navigateTo(ATTENDANCE);
PunchDetailsTable = $('#punchTable').DataTable({
"pageLength": 7, "bFilter": true, "bInfo": true,
"bLengthChange": false, "ordering": true,
"searching": false, responsive: true
});
});
$('#lblNoResults').show();
$('#ResultTableDiv').hide();
$("#LoadPage").hide();
function checkpunchInfo() {
clearValues();
clearErrors();
}
function clearValues() {
$('#PunchStartDate').val("");
$('#PunchEndDate').val("");
$('#ResultTableDiv').hide();
$('#notesField').val('');
}
function convertTimeLocal(serverTime){
var date = new Date(serverTime + " UTC");
return date.toLocaleString();
}
function getEmpPunchDetails(){
showLoadreport("#imgProgAtt",".attnCntDiv");
$('#notesField').val('');
$.ajax({
url: "/user/GetEmpPunchDetails",
type:"POST",
success:function(data){
if(data){
var response = data.punchInfo;
if (stringIsNull(response)) {
$('#punchInBtn').show();
$('#punchdInDiv').hide();
$('#punchOutBtn').hide();
$('#punchdOutDiv').hide();
}
else if (!stringIsNull(response[0]["PunchinTime"]) && !stringIsNull(response[0]["PunchoutTime"])) {
$('#punchInBtn').show();
$('#punchOutBtn').hide();
$('#punchdInDiv').hide();
$('#punchdOutDiv').hide();
}
else if (!stringIsNull(response[0]["PunchinTime"]) && stringIsNull(response[0]["PunchoutTime"])) {
$('#attId').val(response[0]["ID"]);
$('#punchInBtn').hide();
$('#punchOutBtn').show();
//var date = new Date(response[0]["PunchinTime"] +" UTC");
$('#PunchedInTime').text(convertTimeLocal(response[0]["PunchinTime"]));
$('#punchdInDiv').show();
$('#punchdOutDiv').hide();
}
}
HideLoadreport("#imgProgAtt",".attnCntDiv");
},
error:function(data){
console.log(data.responseText);
},
complete: function (data) {
HideLoadreport("#imgProgAtt",".attnCntDiv");
}
});
}
function punchIn() {
showLoadreport("#imgProgAtt", ".attnCntDiv");
var AddAttendance = {};
AddAttendance.url = "/user/AddAttendance";
AddAttendance.type = "POST";
AddAttendance.data = JSON.stringify({ punchInTime: null, punchOutTime: null, type: 1,notes:$('#notesField').val() });
AddAttendance.datatype = "json";
AddAttendance.contentType = "application/json";
AddAttendance.success = function (data) {
setCurrentDateTime();
$('#notesField').val('');
HideLoadreport("#imgProgAtt", ".attnCntDiv");
if (stringIsNull(data)) {
showMessageBox(ERROR, "An Unexpected Error Occured!!");
}
else if (data.status == "OK") {
$('#attId').val(data.attId);
$('#punchInBtn').hide();
$('#punchOutBtn').show();
// var date = new Date(data.punchInTime +" UTC");
$('#PunchedInTime').text(convertTimeLocal(data.punchInTime));
$('#punchdInDiv').show();
$('#punchdOutDiv').hide();
}
else{
showMessageBox(ERROR, "An Unexpected Error Occured!!");
}
};
AddAttendance.error = function () {
HideLoadreport("#imgProgAtt", ".attnCntDiv");
showMessageBox(ERROR, "An Unexpected Error Occured!!");
};
$.ajax(AddAttendance);
}
function punchOut() {
setCurrentDateTime();
showLoadreport("#imgProgAtt", ".attnCntDiv");
var pin = $('#PunchedInTime').text();
var AddAttendance = {};
AddAttendance.url = "/user/AddAttendance";
AddAttendance.type = "POST";
AddAttendance.data = JSON.stringify({ attId:$('#attId').val(), punchInTime: pin, punchOutTime: null, type: 2
,notes:$('#notesField').val()});
AddAttendance.datatype = "json";
AddAttendance.contentType = "application/json";
AddAttendance.success = function (data) {
setCurrentDateTime();
$('#notesField').val('');
HideLoadreport("#imgProgAtt", ".attnCntDiv");
if (stringIsNull(data)) {
showMessageBox(ERROR, "An Unexpected Error Occured!!");
}
else if (data.status == "OK") {
$('#punchInBtn').show();
$('#punchOutBtn').hide();
$('#punchdInDiv').hide();
$('#punchdOutDiv').hide();
}
else {
showMessageBox(ERROR, "An Unexpected Error Occured!!");
}
};
AddAttendance.error = function () {
HideLoadreport("#imgProgAtt", ".attnCntDiv");
showMessageBox(ERROR, "An Unexpected Error Occured!!");
};
$.ajax(AddAttendance);
}
$('#PunchStartDate').on('change keyup paste', function () {
if (this.value.toString().length == 0) {
$('#PunchStartDate').css('border-color', 'red');
$('#lblstartDate').text('Select Start Date !')
$('#lblstartDate').show();
}
else {
$('#PunchStartDate').css('border-color', '');
$('#lblstartDate').hide();
}
});
$('#PunchEndDate').on('change keyup paste', function () {
if (this.value.toString().length == 0) {
}
else {
$('#PunchEndDate').css('border-color', '');
$('#lblstartDate').hide();
}
});
function getAttendanceData() {
$('#lblNoResults').hide();
// $('#ResultTableDiv').show();
// HideLoadreport("#LoadPageAttnRprt", "#attnRprtDiv");
// PunchDetailsTable = $('#punchTable').DataTable({
// "pageLength": 7, "processing": true, "serverSide": true,
// "paging": true, "bLengthChange": false, "searching": false,
// "bInfo": true,
// "ajax": {
// "url": "/User/SearchPunchDetails",
// "type": "POST",
// "dataType": "JSON",
// "data": function (d) {
// d.EmpId = empId;
// d.StartDate = $('#PunchStartDate').val();
// d.EndDate = $('#PunchEndDate').val();
// d.timeoffset = offset;
// }
// }
// ,"columnDefs": [
// {
// "render": function ( data, type, row ) {
// return row["PunchinTime"].split(' ')[0]
// },
// "targets": 0
// }
// ]
// , "columns": [
// { "data": "PunchinTime" },
// { "data": "PunchinTime" },
// { "data": "PunchoutTime" },
// { "data": "Duration" }
// ]
// , "language":
// {
// "processing": "<div class='row text-center waitIconDiv'><img alt='Progress' src='../Content/images/wait_icon.gif' width='50' height='50'/></div>"
// }
// });
$.ajax({
url: "/user/SearchPunchDetails",
type:"POST",
datatype:"json",
contentType :"application/json",
data:JSON.stringify({ StartDate: $('#PunchStartDate').val(), EndDate: $('#PunchEndDate').val() }),
success:function(data){
HideLoadreport("#LoadPageAttnRprt", "#attnRprtDiv");
try {
if (data) {
var response = data.searchData;
if(response.length > 0){
$('#ResultTableDiv').show();
PunchDetailsTable.clear().draw();
for (var i = 0; i <= response.length - 1 ; i++) {
PunchDetailsTable.row.add({
0: (response[i].PunchinTime).split(' ')[0],
1: (response[i].PunchinTime)?convertTimeLocal(response[i].PunchinTime):'',
2: (response[i].PunchoutTime)?convertTimeLocal(response[i].PunchoutTime):'',
3: response[i].Duration?response[i].Duration:""
}).draw();
}
}
else {
$('#ResultTableDiv').hide();
$('#lblNoResults').show();
}
}
else {
$('#ResultTableDiv').hide();
$('#lblNoResults').show();
}
}
catch (ex) {
showMessageBox(ERROR, "An Unexpected Error Occured!!");
}
},
error:function(data){
HideLoadreport("#LoadPageAttnRprt", "#attnRprtDiv");
showMessageBox(ERROR, "An Unexpected Error Occured!!");
},
complete: function (data) {
HideLoadreport("#LoadPageAttnRprt", "#attnRprtDiv");
}
});
}
function SearchAttendance() {
clearErrors();
var startDate = $('#PunchStartDate').val();
var endDate = $('#PunchEndDate').val();
var sDate = new Date(startDate);
var eDate = new Date(endDate);
var currentDate = new Date();
var flag = false;
if ((startDate.length == 0 && endDate.length == 0) || (startDate.length == 0 && endDate.length != 0)) {
$('#PunchStartDate').css('border-color', 'red');
$('#lblstartDate').text('Select Start date !!');
$('#lblstartDate').show();
flag = true;
}
else if (sDate > eDate) {
$('#PunchStartDate').css('border-color', 'red');
$('#lblstartDate').text('Start date must be less than or equal to End date !!');
$('#lblstartDate').show();
flag = true;
}
else if (eDate > currentDate) {
$('#PunchEndDate').css('border-color', 'red');
$('#lblEndDate').text('End date must be less than or equal to Current Date !!');
$('#lblEndDate').show();
flag = true;
}
if (!flag) {
showLoadreport("#LoadPageAttnRprt", "#attnRprtDiv");
//blockNumber = 1;
getAttendanceData();
}
} |
var temp = require('./user');
module.exports = temp; |
function ShowDatePopup(event) {
// alert(111);
// получить объект событие.
// В браузерах, работающих по рекомендациям W3C, объект события всегда передается в обработчик первым параметром.
// В IE существует глобальный объект window.event, который хранит в себе информацию о последнем событии.
// А первого аргумента обработчика просто нет.
event = event || window.event;
// кросс-браузерно получить target
// В Internet Explorer у объекта window.event для этого есть свойство srcElement,
// в остальных браузерах, работающих по рекомендациям W3C, для этого используется event.target.
var t = event.target || event.srcElement;
t.control.Owner.togglePopup();
}
function ShowCommonRSForm(event) {
event = event || window.event;
var t = event.target || event.srcElement;
var rsNumber = parseInt(t.innerText);
OpenML(rsNumber);
event.cancelBubble = true;
event.returnValue = false;
if (event.stopPropagation) {
event.stopPropagation();
event.preventDefault();
}
}
function OpenML(numML) {
var fso, tfolder, tmpPath, app, sourcePath;
try {
fso = new ActiveXObject("Scripting.FileSystemObject");
tfolder = fso.GetSpecialFolder(2); // Временная папка
tmpPath = fso.BuildPath(tfolder, "ML.mdb");
sourcePath = "\\\\comcor\\comcor\\Общая\\Navigator\\navsql\\Dev_\\ML.mdb";
if (fso.FileExists(sourcePath)) {
if (!fso.FileExists(tmpPath)) {
fso.CopyFile(sourcePath, tmpPath, true);
}
app = new ActiveXObject("Access.Application");
app.OpenCurrentDatabase(tmpPath);
app.Run("SelectForm", numML);
app.visible = true;
} else {
alert("Не смогли найти " + sourcePath);
}
} catch (e) {
alert((e.number & 0xFFFF).toString() + " " + e.message + "\n" + e.description);
}
}
|
/**
* Created by WangChong on 16/3/4.
*/
var MyDebug;
(function (MyDebug) {
MyDebug.text = "";
var count = 1;
/**
* 设置密道
*/
function GetPoint(_x, _y) {
console.warn(_x + " " + _y);
if (count > 6) {
return;
}
switch (count) {
case 1:
if (_x < 320 && _y < 480) {
count++;
}
break;
case 2:
if (_x < 320 && _y < 480) {
count++;
}
break;
case 3:
if (_x > 320 && _y < 480) {
count++;
}
break;
case 4:
if (_x < 320 && _y > 480) {
count++;
}
break;
case 5:
if (_x < 320 && _y > 480) {
count++;
}
break;
case 6:
if (_x > 320 && _y > 480) {
count++;
Show();
}
break;
}
}
MyDebug.GetPoint = GetPoint;
function Show() {
}
function MyLog(_log) {
console.log(_log);
//if (DialogManager.hint == null)
//{
// text += _log;
// text += '\n';
//}
}
MyDebug.MyLog = MyLog;
})(MyDebug || (MyDebug = {}));
|
import React from 'react';
const Spinner = () => (
<svg
width="16px"
height="16px"
viewBox="30 30 40 40"
preserveAspectRatio="xMidYMid"
style={{
background: 'none',
}}
>
<g transform="rotate(0 50 50)">
<rect
x="48"
y="30"
rx="3.84"
ry="2.4"
width="4"
height="12"
fill="currentColor"
>
<animate
attributeName="opacity"
values="1;0"
dur="0.6s"
begin="-0.525s"
repeatCount="indefinite"
/>
</rect>
</g>
<g transform="rotate(45 50 50)">
<rect
x="48"
y="30"
rx="3.84"
ry="2.4"
width="4"
height="12"
fill="currentColor"
>
<animate
attributeName="opacity"
values="1;0"
dur="0.6s"
begin="-0.45s"
repeatCount="indefinite"
/>
</rect>
</g>
<g transform="rotate(90 50 50)">
<rect
x="48"
y="30"
rx="3.84"
ry="2.4"
width="4"
height="12"
fill="currentColor"
>
<animate
attributeName="opacity"
values="1;0"
dur="0.6s"
begin="-0.375s"
repeatCount="indefinite"
/>
</rect>
</g>
<g transform="rotate(135 50 50)">
<rect
x="48"
y="30"
rx="3.84"
ry="2.4"
width="4"
height="12"
fill="currentColor"
>
<animate
attributeName="opacity"
values="1;0"
dur="0.6s"
begin="-0.3s"
repeatCount="indefinite"
/>
</rect>
</g>
<g transform="rotate(180 50 50)">
<rect
x="48"
y="30"
rx="3.84"
ry="2.4"
width="4"
height="12"
fill="currentColor"
>
<animate
attributeName="opacity"
values="1;0"
dur="0.6s"
begin="-0.225s"
repeatCount="indefinite"
/>
</rect>
</g>
<g transform="rotate(225 50 50)">
<rect
x="48"
y="30"
rx="3.84"
ry="2.4"
width="4"
height="12"
fill="currentColor"
>
<animate
attributeName="opacity"
values="1;0"
dur="0.6s"
begin="-0.150s"
repeatCount="indefinite"
/>
</rect>
</g>
<g transform="rotate(270 50 50)">
<rect
x="48"
y="30"
rx="3.84"
ry="2.4"
width="4"
height="12"
fill="currentColor"
>
<animate
attributeName="opacity"
values="1;0"
dur="0.6s"
begin="-0.075s"
repeatCount="indefinite"
/>
</rect>
</g>
<g transform="rotate(315 50 50)">
<rect
x="48"
y="30"
rx="3.84"
ry="2.4"
width="4"
height="12"
fill="currentColor"
>
<animate
attributeName="opacity"
values="1;0"
dur="0.6s"
begin="0s"
repeatCount="indefinite"
/>
</rect>
</g>
</svg>
);
export default Spinner;
|
import React from 'react'
import FeedbackImg from 'assets/img/Feedback.png'
import { Link } from 'react-router-dom'
import { useInitScrollTop } from 'utils/customHooks';
const Feedback = () => {
useInitScrollTop();
return (
<div className='contactus-feedback'>
<div>
<img src={FeedbackImg} alt='Thank you for your feedback' />
</div>
<h2>Thanks for reaching out. <br />We’ll get back to you!</h2>
<button>
<Link to='/'>Back Home</Link>
</button>
</div>
)
}
export default Feedback |
// Returns a function that then calculates whether a given trip is within range.
// For example, produceDrivingRange(10) returns a function that will return false
// if the trip is over 10 blocks distance and true if the distance is within range.
// So produceDrivingRange returns a function that we can then use to calculate
// if a trip is too large for a driver.
// We recommend referencing the test/indexTest.js for more details.
function produceDrivingRange(blockRange){
return function(startingBlock, endingBlock){
let start = parseInt(startingBlock);
let end = parseInt(endingBlock);
let distanceToTravel = Math.abs(end - start);
let dif = blockRange - distanceToTravel;
if( dif > 0){
return `within range by ${dif}`}
else {
return `${Math.abs(dif)} blocks out of range`
}
}
}
function produceTipCalculator(percentage){
return function(rideFare){
return rideFare*percentage;
}
}
function createDriver(){
let driverId = 0
return class {
constructor(name){
this.id = ++driverId
this.name = name
}
}
}
|
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const QuizzesSchema = new Schema(
{
quiz_title: { type: String },
quiz_desc: { type: String },
quiz_code: { type: String },
quiz_current: { type: Number, default: 0 },
quiz_questions: [{ type: Schema.Types.ObjectId, ref: "Questions" }],
quiz_players: [{ type: Schema.Types.ObjectId, ref: "Players" }],
},
{
collection: "Quizzes",
timestamps: { createdAt: "created_at", updatedAt: "updated_at" },
}
);
const QuizzesModel = mongoose.model("Quizzes", QuizzesSchema);
module.exports = QuizzesModel;
|
async function count() {
await setTimeout(()=>{console.log("finish")}, 2000);
console.log("first");
}
function Name() {
count();
console.log("second");
}
Name();
function Like(){
for(var i=0; i<5; i++) {
console.log(i)
}
console.log(i)
}
Like();
|
const uniqueSlug = require("unique-slug");
const fs = require("fs");
const sharp = require("sharp");
const uploadURI = process.env.UPLOADS_DIR;
// Saves the image and returns the filename that will be saved to db
const saveImage = async (image) => {
// Original image
let fname = uniqueSlug() + ".png";
const path = `${uploadURI}${fname}`;
let stream = image.file.createReadStream();
await stream.pipe(fs.createWriteStream(path));
// Thumbnail
const transformer = sharp().resize({
width: 480,
fit: sharp.fit.cover,
position: sharp.strategy.entropy,
});
const tnFilename = `tn${fname}`;
const tnPath = `${uploadURI}${tnFilename}`;
const tnStream = image.file.createReadStream();
tnStream.pipe(transformer).pipe(fs.createWriteStream(tnPath));
return fname;
};
const deleteFile = (img) => {
console.log(img);
if (img.toString() != "default.png") {
fs.unlink(`${uploadURI}${img}`, (err) => {
if (err) throw err;
// if no error, file has been deleted successfully
console.log("File deleted!");
});
fs.unlink(`${uploadURI}tn${img}`, (err) => {
if (err) throw err;
// if no error, file has been deleted successfully
console.log("File thumbnail deleted!");
});
}
};
module.exports = { saveImage, deleteFile };
|
import store from "../store";
import urlUtils from "./urlUtils";
import Client from "../js/sdk/client";
export default {
getAll() {
return store.state.cache.cache.businessUserMap;
},
getOneByImUid(imUid) {
let id = parseInt(imUid);
if (this.getAll().has(id)) {
return this.getAll().get(id);
}
return {};
},
getMe() {
let id = parseInt(Client.getInstance().account);
if (this.getAll().has(id)) {
return this.getAll().get(id);
}
return {};
},
isMe(imUid) {
let id = parseInt(imUid);
if (this.getAll().has(id)) {
let businessUser = this.getAll().get(id);
let me = this.getMe();
if (me && businessUser.imUid == me.imUid) {
return true;
}
}
return false;
},
}
|
import React, { Component } from 'react';
import './App.css';
import Animal from './Animal'
class App extends Component {
state = {
animals: [
{name: 'panda', color:'white'},
{name: 'tiger', color:'yellow'},
{name:'bat', color:'black'},
{name:'possum', color:'brown'},
{name:'cat', color:'orange'},
{name:'rat', color:'dark grey'},
//ocutpuse needs to be here
]
}
deleteAnimal = (i) => {
let newAnimalList = [...this.state.animals] //copy state
newAnimalList.splice(i,1) //slice index
this.setState({
animals:newAnimalList
})
}
addAnimal = (animal) => {
console.log('add animal',animal)
let animalCopy = [...this.state.animals]
animalCopy.push(animal)
this.setState({
animals:animalCopy
})
}
render() { /**Put javascript in here */
//this.doSomething('cool') This is on page load
return (
<div>
<ul>
<Animal
animalProps={ this.state.animals }
deleteTheAnimal= {this.deleteAnimal}
addTheAnimal= {this.addAnimal}
/>
</ul>
</div>
);
}
}
export default App;
|
import styled from 'styled-components';
export const Container = styled.div`
width:100%;
height:100%;
display:flex;
flex-direction:column;
justify-content:flex-end;
`;
export const MapDiv = styled.div`
width:100%;
height:80%;
background-color:#fff;
`; |
'use strict';
var app = app;
app.factory('Auth', function Auth ($location, $rootScope, Session, $cookieStore, $http, $q) {
// $rootScope.currentUser = $cookieStore.get('user') || null;
//$cookieStore.remove('user');
return {
login: function(user, callback) {
console.log("Nemam Amma Bhagavan Sharanam -- Calling the login auth service" + user.username + user.password);
var cb = callback || angular.noop;
$http.post('/api/auth/session', {
username: user.username,
password: user.password,
rememberMe: true
})
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$rootScope.currentUser = data.user.name;
$cookieStore.put('user', data.user.name);
console.log("Nemam Amma Bhagavan Sharanam -- Successfully logged in using passport + User:" + $cookieStore.get('user'));
return cb();
}) // success promise
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
//return cb(err.data);
console.log("Nemam Amma Bhagavan Sharanam -- Error");
}); // Error promise
}, // login factory method
logout: function() {
// Remove the user from cookieStore and passport to keep server in sync
$cookieStore.remove('user');
console.log("Nemam Amma Bhagavan Sharanam -- logging out");
$rootScope.currentUser = null;
//return;
} // logout
} // return block
}); // Auth factory declaration
|
/*
* @description: JS Controller of CalculateCertificationComp
* @author: MadsPascua(Xero)
* @history:
* 21May2018 MadsPascua(Xero): Initial version
*/
({
calculateCertification: function(component, event, helper) {
var recordId = component.get("v.recordId");
//console.log("recordId: " + recordId);
helper.calculateCertificationHelper(component, event, helper, recordId);
},
closeWindow: function(component, event, helper){
$A.get("e.force:closeQuickAction").fire();
}
}) |
import {isConnected} from "./ethNode";
async function checkNodeConnection(req, res, next){
const connected = await isConnected();
if(!connected){
res.status(500);
res.json({
"message": "Unable to connect to ethereum node"
});
return;
}
console.log("Node connection okay");
next();
}
module.exports = checkNodeConnection;
|
class Area {
componentDidMount() {
var node = React.findDOMNode(this)
var cards = Draggable.create('.card-wrapper', {
bounds: '#table',
zIndexBoost: false,
})
cards.map( c => c.disable())
Draggable.create(node, {
trigger: node,
bounds: '#table',
onPress: (event) => {
cards.map( c => {
var items = new Set(c.target.classList)
if (items.has(this.props.name)) { c.enable().startDrag(event) }
})
},
onRelease: function(){ node.style.zIndex = '0' },
edgeResistance: 0.8
})
// var node = React.findDOMNode(this)
// var cards = document.querySelectorAll('.card-wrapper.'+this.props.name)
// Draggable.create(node, {
// bounds: '#table',
// onPress: (event) => {
// for (var i = cards.length; i--;) {
// var d = Draggable.get(cards[i])
// d.vars.zIndexBoost = false
// d.enable().startDrag(event)
// }
// },
// onRelease: function(){ node.style.zIndex = '0' },
// edgeResistance: 0.8
// })
}
static dropoff(card, area) {
card.classList.remove(area.id)
// TODO there is a bug here where a card can have overlap and get 2 classes added
if (Draggable.hitTest(area, card, '20%')) {
var plusOrMinus = Math.random() < 0.5 ? -1 : 1,
toppish = Math.floor(Math.random() * 10) * plusOrMinus,
leftish = Math.floor(Math.random() * 10) * plusOrMinus,
spin = Math.floor(Math.random() * 20) * plusOrMinus
var d = Draggable.get('#'+area.id),
x = parseInt(area.dataset.x) + d.x,
y = parseInt(area.dataset.y) + d.y,
r = parseInt(area.dataset.rotation)+spin+'_short'
var ah0 = area.offsetHeight,
ay0 = area.offsetTop + d.y,
ch0 = card.offsetHeight,
cy1 = ay0+(ah0-ch0)/2
if (area.classList.contains('current-user')) {
TweenLite.to(card, 0.3, {rotation: '0_short', y: cy1})
} else {
TweenLite.to(card, 0.3, {x: x+leftish, y: y+toppish, rotation: r})
}
card.classList.add(area.id)
}
}
render() {
var areaClass = ['area']
if (this.props.face_up) { areaClass.push('face-up') }
var t = this.props.position_y
var l = this.props.position_x
var br = this.props.border_radius_px * 1.2
return (
<div className={areaClass.join(' ')}
id={this.props.name}
style={{top: t,
left: l,
width: this.props.width_px * 1.2,
height: this.props.height_px * 1.2,
borderRadius: br}}
data-x={l+this.props.width_px*0.1}
data-y={t+this.props.height_px*0.1}
data-rotation={0}>
<p className='name'>{this.props.name}</p>
</div>
)
}
}
|
import {
getOne,
getAll,
elShow,
elRemove,
elHide,
ajaxGet,
maskingName,
createElementFunc,
addClass,
hasClass,
removeClass
} from './util';
import { tweenEvent } from './tweenEvent';
class ListData {
constructor() {
this.setVars();
this.init();
}
setVars() {
this.list = getOne('.list');
this.listWrap = getOne('#list-wrap');
this.detail = getOne('#detail');
this.loader = getOne('.lds-ring');
this.listBtn = getOne('#list-btn');
this.paging = getOne('.paging');
this.wrapper = getOne('#wrapper');
this.closeList = getOne('#close-list');
this.header = getOne('header');
}
getDataOnClick() {
this.listBtn.addEventListener('click', () => {
tweenEvent.cloudMotionPause();
tweenEvent.scrollTopSet();
tweenEvent.footerHide();
this.headerAddClass();
this.getData();
});
}
// 참여 현황보기 리스트 데이터 검색
getData(page = 1) {
const url = `http://ifd.kr/board/bbs/boardout4.php?bo_table=unicef&page=${page}`;
elShow(this.loader);
this.list.innerHTML = '';
ajaxGet(url, null, data => {
const xmlDom = new DOMParser().parseFromString(data, 'text/xml');
this.getDataCallbackSuccess(xmlDom);
elHide(this.loader);
});
}
getDataCallbackSuccess(data) {
const text = data.getElementsByTagName('item'),
paging = data.querySelector('paging');
this.paging.innerHTML = paging.textContent;
if (getOne('.pg_next')) getOne('.pg_next').innerText = '';
if (getOne('.pg_prev')) getOne('.pg_prev').innerText = '';
getOne('.pg_wrap .pg').addEventListener('click', e => {
const t = e.target;
e.preventDefault();
/**
* 다음, 이전 화살표 클릭 이벤트
* href의 page부분 값을 가져와서 검색
*/
if (hasClass(t, 'pg_next') || hasClass(t, 'pg_prev')) {
const pageNumber = t
.getAttribute('href')
.split('page')[1]
.replace('=', '');
tweenEvent.scrollTopSet();
this.getData(pageNumber);
}
if (t.className === 'pg_page') {
tweenEvent.scrollTopSet();
this.getData(t.innerText);
}
});
this.getItem(text);
elRemove(getAll('.sound_only, .pg_end, .pg_start'));
elHide(this.wrapper);
elShow(this.listWrap);
}
getItem(text) {
elRemove(getAll('.list li'));
this.createItems(Array.from(text));
}
closeListOnClick() {
this.closeList.addEventListener('click', () => {
elShow(this.wrapper);
elHide(this.listWrap);
this.headerRemoveClass();
tweenEvent.cloudMotionResume();
tweenEvent.footerShow();
});
}
// 검색해온 리스트 데이터로 참여 현황 DOM 생성
createItems(target) {
if (target.length) {
addClass(this.list, 'active');
}
target.forEach(el => {
const li = this.makeListLi(el),
img = this.makeThumbImage(el);
let p = createElementFunc('p');
p.appendChild(img);
li.appendChild(p);
p = this.makeUserData(el);
li.appendChild(p);
this.list.appendChild(li);
});
}
makeThumbImage(el) {
const thumbImage = el.childNodes[21].textContent.trim();
const src = thumbImage.split('"')[1];
const img = createElementFunc('img', { src: src });
return img;
}
makeListLi(el) {
const id = el.childNodes[3].textContent.trim();
const li = createElementFunc('li', { id: id });
li.addEventListener('click', () => {
this.headerRemoveClass();
this.getDetail(id);
});
return li;
}
makeUserData(el) {
const name = el.childNodes[15].textContent.trim();
const dateTime = el.childNodes[13].textContent.trim();
const p = createElementFunc('p', { id: 'user-name' });
p.innerHTML =
'<span id="user-name-name">' +
this.maskingNamed(name) +
'</span>' +
'<br />' +
'<span id="user-name-date">' +
dateTime.substr(0, dateTime.length - 3) +
'</span>';
return p;
}
// 이름이 너무 9글자보다 길면 ...처리
maskingNamed(name) {
return name.length > 9 ? maskingName(name).substr(0, 9 - 2) + '...' : maskingName(name);
}
getDetail(id) {
const url = `http://ifd.kr/board/bbs/unicef_list.php?bo_table=unicef&wr_id=${id}`;
elHide(this.listWrap);
elShow(this.loader);
ajaxGet(url, null, data => {
this.getDetailCallBackSuccess(data);
});
}
getDetailCallBackSuccess(data) {
const doc = new DOMParser().parseFromString(data, 'text/html').body.firstElementChild;
this.detail.appendChild(doc);
getOne('#detail-in-upload-btn').addEventListener('click', () => tweenEvent.uploadFormShow());
getOne('#close-detail').addEventListener('click', _ => this.detailClose());
getOne('#bo_v_img img').onload = () => {
elShow(this.detail);
elHide(this.loader);
};
}
detailClose() {
this.detail.innerHTML = '';
this.headerAddClass();
elHide(this.detail);
elShow(this.listWrap);
}
headerRemoveClass() {
removeClass(this.header, 'list-active');
}
headerAddClass() {
addClass(this.header, 'list-active');
}
init() {
this.closeListOnClick();
this.getDataOnClick();
}
}
export const listData = new ListData();
|
;(function(){
//扫描二维码变大;
$(".sao").hover(function(){
$(".wx").css("transform","scale(2)");
},function(){
$(".wx").css("transform","scale(1)");
})
//当前时间
var nowtime=new Date();
var nowyear=nowtime.getFullYear();
$(".nowtime").html(nowyear);
//初始化class名
$('.class_list').each(function(){
$(this).find('li:first').addClass('active').siblings('li').removeClass('active');
})
$(".tab_box:first").show();
$('.tab_box').each(function(){
$(this).find('.xilie_tab:first').show().siblings('.xilie_tab').hide()
})
var cityIndex=0;
// 左侧悬浮窗城市选择
$(".tc li").click(function(e){
var self = $(this);
var text = self.text();
cityIndex = self.index();
$(".city_select").text(text);
self.addClass("active").siblings("li").removeClass("active");
$(".site_list li").removeClass("active");
$(".site_list li").eq(cityIndex).addClass("active");
$(".main_change").hide();
$(".main_change").eq(cityIndex).show();
main_func();
e.stopPropagation();
})
//点击选择城市
$(".site_list li").click(function(){
$(".site_list li").removeClass("active");
$(this).addClass("active");
cityIndex=$(this).index();
var text = $(this).text();
$(".city_select").text(text);
$(".tc li").removeClass("act");
$(".tc li").eq(cityIndex).addClass("act");
$(".main_change").hide();
$(".main_change").eq(cityIndex).show();
main_func();
})
//点击选择城市课程系列
// $(".class_list li").click(function(){
// $(".class_list").eq(cityIndex).find("li").removeClass("active");
// $(this).addClass("active");
// $(".tab_box").eq(cityIndex).find(".xilie_tab").hide();
// $(".tab_box").eq(cityIndex).find(".xilie_tab").eq($(this).index()).show();
// })
//等你来区域切换
$(".wait_list li").click(function(){
$(".wait_list li").removeClass("active");
$(this).addClass("active");
$(".wait_box").hide();
$(".wait_box").eq($(this).index()).show();
})
// 底部城市选择
$(".area_box .city li").removeClass("act");
$(".area_box .city li").eq(0).addClass("act");
$(".locate_box").each(function() {
$(this).find("ul li").removeClass("act");
$(this).find("ul li").eq(0).addClass("act");
$(this).find(".detail_box").hide();
$(this).find(".detail_box").eq(0).show();
});
$(".locate_box").hide();
$(".locate_box").eq(0).show();
$(".locate_box .detail_box").each(function() {
var self = $(this);
self.find("ul").hide();
self.find("ul").eq(0).show();
});
$(".area_box .city").on("click", "li", function() {
var self = $(this);
index = self.index();
self.siblings("li").removeClass("act");
self.addClass("act");
$(".locate_box").hide();
$(".locate_box").eq(index).show();
});
$(".locate_box").on("click", "ul li", function() {
var self = $(this);
index = self.index();
self.siblings("li").removeClass("act");
self.addClass("act");
$(".locate_box:visible .detail_box").hide();
$(".locate_box:visible .detail_box").eq(index).show();
});
//返回顶部
$(".top").click(function(){$("html,body").animate({scrollTop:"0px"},800);})
// 左侧悬浮窗
$(".mao").click(function(){
var sc_top=$(".maodian"+$(this).index(".left_fix .mao")+"").offset().top;
$("body,html").animate({
scrollTop:sc_top
},500);
})
var timer=null;
$(".mao3").hover(function(){
clearInterval(timer);
$(".shang,.city_tc").show();
},function(){
timer= setInterval(function(){
$(".shang,.city_tc").hide();
},200);
})
$(".close").click(function(){
$(".left_fix").hide();
$(".zhida").show();
})
$(".zhida").click(function(){
$(this).hide();
$(".left_fix").show();
})
// ..............................................................................
main_func();
function main_func() {
$('.class_list').eq(cityIndex).find("li").click(function(){
$(this).addClass('active').siblings('li').removeClass('active');
$('.main_change').eq(cityIndex).find(".tab_wrap").hide();
$('.main_change').eq(cityIndex).find(".tab_wrap").eq($(this).index()).show();
});
$('.main_change:visible').find(".tab_wrap").each(function(index, element) {
// console.log(index)
// var index1 = $(this).index();
$(this).find('.xiaoban li').each(function(index) {
$(this).click(function(){
$(this).addClass('active').siblings('li').removeClass('active');
// console.log($(".main_change").eq(cityIndex))
$(this).parents(".tab_wrap").find(".tab_box").hide();
$(this).parents(".tab_wrap").find(".tab_box").eq($(this).index()).show();
// $(".main_change").eq(cityIndex).find(".tab_wrap").eq(index1).find(".tab_box").hide();
// $(".main_change").eq(cityIndex).find(".tab_wrap").eq(index1).find(".tab_box").eq($(this).index()).show();
})
});
});
}
})();
|
import axios from "axios";
export const startGame = () =>
axios.get("/api/random", { Accept: "application/json" });
export const sendGuess = (body) =>
axios.post("/api/guess", body, {
"Content-Type": "application/json",
Accept: "application/json",
});
export const sendGiveUp = (body) =>
axios.post("/api/giveup", body, { Accept: "application/json" });
|
export default {
update (el, binding) {
console.log(binding)
document.title = binding.value
}
}
9 |
(function(app) {
var m = app.add_module("code");
m.elements({
gists: $('#gists')
});
m.actions = function() {
script.defaults.defer = true;
script.defaults.base = 'http://gist.github.com';
get_all_gists();
};
m.handle_all_gists = function(gists) {
m.set_data({
gist_template: new Template('#gist-template'),
gists: []
});
m.elements('gists').empty();
_(gists.data).each(function(gist) {
var i = 0;
var file;
var f;
var furl;
for (f in gist.files) {
if (i === 1) {
break;
}
file = f;
furl = gist.files[f].raw_url;
}
gist.file = file;
m.elements('gists').append(m.data.gist_template.render(gist));
script({ src: gist.id + '.js', append: 'gist-' + gist.id });
app.global.open_external_links_in_new_tabs();
});
m.elements('gists').removeClass('loading');
m.elements('gists').find('.gist-container').show();
};
m.handle_get_gist = function(gist) {
console.log(gist);
};
m.run();
function get_all_gists() {
if (!m.elements('gists').hasClass('loading')) {
m.elements('gists').addClass('loading');
}
$.ajax({
type: 'get',
url: 'https://api.github.com/users/daytonn/gists',
data: 'callback=dn.code.handle_all_gists',
dataType: 'jsonp',
error: handle_ajax_error
});
}
function embed_gists() {
var gists = m.elements('gists').find('.gist-container');
_(gists).each(function(gist, i) {
console.log(gist);
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://gist.github.com/' + gist.id + '.js';
gist.appendChild(script);
});
}
function handle_ajax_error(response) {
console.log(response.status + ' ' + response.statusText);
}
})(dn);
|
/*
* @Descripttion: api接口调用统一出口
* @Author: 王月
* @Date: 2020-09-16 13:43:40
* @LastEditors: 王月
* @LastEditTime: 2020-09-16 13:48:33
*/
export * from './demo'; |
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var { read } = require('./helper/');
const port = 3003;
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type");
res.setHeader("Access-Control-Allow-Credentials", true);
next();
});
app.get('/products', (req, res) => {
read('./models/products.json', function(error, data) {
console.log(error, 'erroe');
res
.send(data)
});
});
app.listen(port, function () {
// говорим на каком порту запускать нашу NODE_JS программу.
console.log(`Example app listening on port http://localhost:${port}/`);
});
|
webpackJsonp([77], {
238: function(r, n, a) {
(function(n) {
r.exports = n["MessageFormat"] = a(239);
}).call(n, a(7));
},
239: function(r, n, a) {
var e;
var e;
(function(n) {
if (true) r.exports = n();
else if ("function" === typeof define && define.amd) define([], n);
else {
var a;
if ("undefined" !== typeof window) a = window;
else if ("undefined" !== typeof global) a = global;
else if ("undefined" !== typeof self) a = self;
else a = this;
a.MessageFormat = n();
}
})(function() {
var r, n, a;
return function r(n, a, t) {
function i(l, c) {
if (!a[l]) {
if (!n[l]) {
var u = "function" == typeof e && e;
if (!c && u) return e(l, !0);
if (o) return o(l, !0);
var d = new Error("Cannot find module '" + l + "'");
throw d.code = "MODULE_NOT_FOUND", d;
}
var f = a[l] = {
exports: {}
};
n[l][0].call(f.exports, function(r) {
var a = n[l][1][r];
return i(a ? a : r);
}, f, f.exports, r, n, a, t);
}
return a[l].exports;
}
var o = "function" == typeof e && e;
for (var l = 0; l < t.length; l++) i(t[l]);
return i;
}({
1: [function(r, n, a) {
n.exports = {
number: {
decimal: {
style: "decimal"
},
integer: {
style: "decimal",
maximumFractionDigits: 0
},
currency: {
style: "currency",
currency: "USD"
},
percent: {
style: "percent"
},
default: {
style: "decimal"
}
},
date: {
short: {
month: "numeric",
day: "numeric",
year: "2-digit"
},
medium: {
month: "short",
day: "numeric",
year: "numeric"
},
long: {
month: "long",
day: "numeric",
year: "numeric"
},
full: {
month: "long",
day: "numeric",
year: "numeric",
weekday: "long"
},
default: {
month: "short",
day: "numeric",
year: "numeric"
}
},
time: {
short: {
hour: "numeric",
minute: "numeric"
},
medium: {
hour: "numeric",
minute: "numeric",
second: "numeric"
},
long: {
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZoneName: "short"
},
full: {
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZoneName: "short"
},
default: {
hour: "numeric",
minute: "numeric",
second: "numeric"
}
}
};
}, {}],
2: [function(r, n, a) {
"use strict";
var e = r("format-message-formats");
var t = r("lookup-closest-locale");
var i = r("./plurals");
n.exports = function r(n, a) {
return o(n, a);
};
n.exports.closestSupportedLocale = function(r) {
return t(r, i);
};
function o(r, n, a) {
n = n.map(function(n) {
return l(r, n, a);
});
if (1 === n.length) return n[0];
return function r(a) {
var e = "";
for (var t = 0, i = n.length; t < i; ++t) e += "string" === typeof n[t] ? n[t] : n[t](a);
return e;
};
}
function l(r, n, a) {
if ("string" === typeof n) return n;
var e = n[0];
var t = n[1];
var i = n[2];
var o = 0;
var l;
if ("#" === e) {
e = a[0];
t = "number";
o = a[2];
i = null;
}
switch (t) {
case "number":
case "ordinal":
case "spellout":
case "duration":
return u(r, e, o, i);
case "date":
case "time":
return d(r, e, t, i);
case "plural":
case "selectordinal":
o = n[2];
l = n[3];
return f(r, e, t, o, l);
case "select":
return s(r, e, i);
default:
return h(e);
}
}
function c(r, n, a) {
var t = e[r][n] || e[r].default;
var i = t.cache || (t.cache = {});
var o = i[a] || (i[a] = "number" === r ? Intl.NumberFormat(a, t).format : Intl.DateTimeFormat(a, t).format);
return o;
}
function u(r, n, a, e) {
a = a || 0;
var t = c("number", e, r);
return function r(e) {
return t(+v(n, e) - a);
};
}
function d(r, n, a, e) {
var t = c(a, e, r);
return function r(a) {
return t(v(n, a));
};
}
function f(r, n, a, e, l) {
var c = [n, a, e];
var u = {};
Object.keys(l).forEach(function(n) {
u[n] = o(r, l[n], c);
});
var d = t(r, i);
var f = "selectordinal" === a ? i[d].ordinal : i[d].cardinal;
if (!f) return u.other;
return function r(a) {
var t = u["=" + +v(n, a)] || u[f(v(n, a) - e)] || u.other;
if ("string" === typeof t) return t;
return t(a);
};
}
function s(r, n, a) {
var e = {};
Object.keys(a).forEach(function(n) {
e[n] = o(r, a[n], null);
});
return function r(a) {
var t = e[v(n, a)] || e.other;
if ("string" === typeof t) return t;
return t(a);
};
}
function h(r) {
return function n(a) {
return "" + v(r, a);
};
}
function v(r, n) {
if (void 0 !== n[r]) return n[r];
var a = r.split(".");
if (a.length > 1) {
var e = 0;
var t = a.length;
var i = n;
for (e; e < t; e++) {
i = i[a[e]];
if (void 0 === i) return;
}
return i;
}
}
}, {
"./plurals": 3,
"format-message-formats": 1,
"lookup-closest-locale": 4
}],
3: [function(r, n, a) {
"use strict";
var e = [function(r) {
var n = +r;
return 1 === n ? "one" : "other";
}, function(r) {
var n = +r;
return 0 <= n && n <= 1 ? "one" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = +r;
return 0 === n || 1 === a ? "one" : "other";
}, function(r) {
var n = +r;
return 0 === n ? "zero" : 1 === n ? "one" : 2 === n ? "two" : 3 <= n % 100 && n % 100 <= 10 ? "few" : 11 <= n % 100 && n % 100 <= 99 ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
return 1 === n && 0 === a ? "one" : "other";
}, function(r) {
var n = +r;
return n % 10 === 1 && n % 100 !== 11 ? "one" : 2 <= n % 10 && n % 10 <= 4 && (n % 100 < 12 || 14 < n % 100) ? "few" : n % 10 === 0 || 5 <= n % 10 && n % 10 <= 9 || 11 <= n % 100 && n % 100 <= 14 ? "many" : "other";
}, function(r) {
var n = +r;
return n % 10 === 1 && n % 100 !== 11 && n % 100 !== 71 && n % 100 !== 91 ? "one" : n % 10 === 2 && n % 100 !== 12 && n % 100 !== 72 && n % 100 !== 92 ? "two" : (3 <= n % 10 && n % 10 <= 4 || n % 10 === 9) && (n % 100 < 10 || 19 < n % 100) && (n % 100 < 70 || 79 < n % 100) && (n % 100 < 90 || 99 < n % 100) ? "few" : 0 !== n && n % 1e6 === 0 ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
var e = +(r + ".").split(".")[1];
return 0 === a && n % 10 === 1 && n % 100 !== 11 || e % 10 === 1 && e % 100 !== 11 ? "one" : 0 === a && 2 <= n % 10 && n % 10 <= 4 && (n % 100 < 12 || 14 < n % 100) || 2 <= e % 10 && e % 10 <= 4 && (e % 100 < 12 || 14 < e % 100) ? "few" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
return 1 === n && 0 === a ? "one" : 2 <= n && n <= 4 && 0 === a ? "few" : 0 !== a ? "many" : "other";
}, function(r) {
var n = +r;
return 0 === n ? "zero" : 1 === n ? "one" : 2 === n ? "two" : 3 === n ? "few" : 6 === n ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = +("" + r).replace(/^[^.]*.?|0+$/g, "");
var e = +r;
return 1 === e || 0 !== a && (0 === n || 1 === n) ? "one" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
var e = +(r + ".").split(".")[1];
return 0 === a && n % 100 === 1 || e % 100 === 1 ? "one" : 0 === a && n % 100 === 2 || e % 100 === 2 ? "two" : 0 === a && 3 <= n % 100 && n % 100 <= 4 || 3 <= e % 100 && e % 100 <= 4 ? "few" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
return 0 === n || 1 === n ? "one" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
var e = +(r + ".").split(".")[1];
return 0 === a && (1 === n || 2 === n || 3 === n) || 0 === a && n % 10 !== 4 && n % 10 !== 6 && n % 10 !== 9 || 0 !== a && e % 10 !== 4 && e % 10 !== 6 && e % 10 !== 9 ? "one" : "other";
}, function(r) {
var n = +r;
return 1 === n ? "one" : 2 === n ? "two" : 3 <= n && n <= 6 ? "few" : 7 <= n && n <= 10 ? "many" : "other";
}, function(r) {
var n = +r;
return 1 === n || 11 === n ? "one" : 2 === n || 12 === n ? "two" : 3 <= n && n <= 10 || 13 <= n && n <= 19 ? "few" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
return 0 === a && n % 10 === 1 ? "one" : 0 === a && n % 10 === 2 ? "two" : 0 === a && (n % 100 === 0 || n % 100 === 20 || n % 100 === 40 || n % 100 === 60 || n % 100 === 80) ? "few" : 0 !== a ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
var e = +r;
return 1 === n && 0 === a ? "one" : 2 === n && 0 === a ? "two" : 0 === a && (e < 0 || 10 < e) && e % 10 === 0 ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = +("" + r).replace(/^[^.]*.?|0+$/g, "");
return 0 === a && n % 10 === 1 && n % 100 !== 11 || 0 !== a ? "one" : "other";
}, function(r) {
var n = +r;
return 1 === n ? "one" : 2 === n ? "two" : "other";
}, function(r) {
var n = +r;
return 0 === n ? "zero" : 1 === n ? "one" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = +r;
return 0 === a ? "zero" : (0 === n || 1 === n) && 0 !== a ? "one" : "other";
}, function(r) {
var n = +(r + ".").split(".")[1];
var a = +r;
return a % 10 === 1 && (a % 100 < 11 || 19 < a % 100) ? "one" : 2 <= a % 10 && a % 10 <= 9 && (a % 100 < 11 || 19 < a % 100) ? "few" : 0 !== n ? "many" : "other";
}, function(r) {
var n = (r + ".").split(".")[1].length;
var a = +(r + ".").split(".")[1];
var e = +r;
return e % 10 === 0 || 11 <= e % 100 && e % 100 <= 19 || 2 === n && 11 <= a % 100 && a % 100 <= 19 ? "zero" : e % 10 === 1 && e % 100 !== 11 || 2 === n && a % 10 === 1 && a % 100 !== 11 || 2 !== n && a % 10 === 1 ? "one" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
var e = +(r + ".").split(".")[1];
return 0 === a && n % 10 === 1 || e % 10 === 1 ? "one" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
var e = +r;
return 1 === n && 0 === a ? "one" : 0 !== a || 0 === e || 1 !== e && 1 <= e % 100 && e % 100 <= 19 ? "few" : "other";
}, function(r) {
var n = +r;
return 1 === n ? "one" : 0 === n || 2 <= n % 100 && n % 100 <= 10 ? "few" : 11 <= n % 100 && n % 100 <= 19 ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
return 1 === n && 0 === a ? "one" : 0 === a && 2 <= n % 10 && n % 10 <= 4 && (n % 100 < 12 || 14 < n % 100) ? "few" : 0 === a && 1 !== n && 0 <= n % 10 && n % 10 <= 1 || 0 === a && 5 <= n % 10 && n % 10 <= 9 || 0 === a && 12 <= n % 100 && n % 100 <= 14 ? "many" : "other";
}, function(r) {
var n = +r;
return 0 <= n && n <= 2 && 2 !== n ? "one" : "other";
}, function(r) {
var n = (r + ".").split(".")[1].length;
var a = +r;
return 1 === a && 0 === n ? "one" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
return 0 === a && n % 10 === 1 && n % 100 !== 11 ? "one" : 0 === a && 2 <= n % 10 && n % 10 <= 4 && (n % 100 < 12 || 14 < n % 100) ? "few" : 0 === a && n % 10 === 0 || 0 === a && 5 <= n % 10 && n % 10 <= 9 || 0 === a && 11 <= n % 100 && n % 100 <= 14 ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = +r;
return 0 === n || 1 === a ? "one" : 2 <= a && a <= 10 ? "few" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = +(r + ".").split(".")[1];
var e = +r;
return 0 === e || 1 === e || 0 === n && 1 === a ? "one" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
var a = (r + ".").split(".")[1].length;
return 0 === a && n % 100 === 1 ? "one" : 0 === a && n % 100 === 2 ? "two" : 0 === a && 3 <= n % 100 && n % 100 <= 4 || 0 !== a ? "few" : "other";
}, function(r) {
var n = +r;
return 0 <= n && n <= 1 || 11 <= n && n <= 99 ? "one" : "other";
}, function(r) {
var n = +r;
return 1 === n || 5 === n || 7 === n || 8 === n || 9 === n || 10 === n ? "one" : 2 === n || 3 === n ? "two" : 4 === n ? "few" : 6 === n ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
return n % 10 === 1 || n % 10 === 2 || n % 10 === 5 || n % 10 === 7 || n % 10 === 8 || n % 100 === 20 || n % 100 === 50 || n % 100 === 70 || n % 100 === 80 ? "one" : n % 10 === 3 || n % 10 === 4 || n % 1e3 === 100 || n % 1e3 === 200 || n % 1e3 === 300 || n % 1e3 === 400 || n % 1e3 === 500 || n % 1e3 === 600 || n % 1e3 === 700 || n % 1e3 === 800 || n % 1e3 === 900 ? "few" : 0 === n || n % 10 === 6 || n % 100 === 40 || n % 100 === 60 || n % 100 === 90 ? "many" : "other";
}, function(r) {
var n = +r;
return (n % 10 === 2 || n % 10 === 3) && n % 100 !== 12 && n % 100 !== 13 ? "few" : "other";
}, function(r) {
var n = +r;
return 1 === n || 3 === n ? "one" : 2 === n ? "two" : 4 === n ? "few" : "other";
}, function(r) {
var n = +r;
return 0 === n || 7 === n || 8 === n || 9 === n ? "zero" : 1 === n ? "one" : 2 === n ? "two" : 3 === n || 4 === n ? "few" : 5 === n || 6 === n ? "many" : "other";
}, function(r) {
var n = +r;
return n % 10 === 1 && n % 100 !== 11 ? "one" : n % 10 === 2 && n % 100 !== 12 ? "two" : n % 10 === 3 && n % 100 !== 13 ? "few" : "other";
}, function(r) {
var n = +r;
return 1 === n ? "one" : 2 === n || 3 === n ? "two" : 4 === n ? "few" : 6 === n ? "many" : "other";
}, function(r) {
var n = +r;
return 1 === n || 5 === n ? "one" : "other";
}, function(r) {
var n = +r;
return 11 === n || 8 === n || 80 === n || 800 === n ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
return 1 === n ? "one" : 0 === n || 2 <= n % 100 && n % 100 <= 20 || n % 100 === 40 || n % 100 === 60 || n % 100 === 80 ? "many" : "other";
}, function(r) {
var n = +r;
return n % 10 === 6 || n % 10 === 9 || n % 10 === 0 && 0 !== n ? "many" : "other";
}, function(r) {
var n = Math.floor(Math.abs(+r));
return n % 10 === 1 && n % 100 !== 11 ? "one" : n % 10 === 2 && n % 100 !== 12 ? "two" : (n % 10 === 7 || n % 10 === 8) && n % 100 !== 17 && n % 100 !== 18 ? "many" : "other";
}, function(r) {
var n = +r;
return 1 === n ? "one" : 2 === n || 3 === n ? "two" : 4 === n ? "few" : "other";
}, function(r) {
var n = +r;
return 1 <= n && n <= 4 ? "one" : "other";
}, function(r) {
var n = +r;
return 1 === n ? "one" : n % 10 === 4 && n % 100 !== 14 ? "many" : "other";
}, function(r) {
var n = +r;
return (n % 10 === 1 || n % 10 === 2) && n % 100 !== 11 && n % 100 !== 12 ? "one" : "other";
}, function(r) {
var n = +r;
return n % 10 === 3 && n % 100 !== 13 ? "few" : "other";
}];
n.exports = {
af: {
cardinal: e[0]
},
ak: {
cardinal: e[1]
},
am: {
cardinal: e[2]
},
ar: {
cardinal: e[3]
},
as: {
cardinal: e[2],
ordinal: e[35]
},
asa: {
cardinal: e[0]
},
ast: {
cardinal: e[4]
},
az: {
cardinal: e[0],
ordinal: e[36]
},
be: {
cardinal: e[5],
ordinal: e[37]
},
bem: {
cardinal: e[0]
},
bez: {
cardinal: e[0]
},
bg: {
cardinal: e[0]
},
bh: {
cardinal: e[1]
},
bn: {
cardinal: e[2],
ordinal: e[35]
},
br: {
cardinal: e[6]
},
brx: {
cardinal: e[0]
},
bs: {
cardinal: e[7]
},
ca: {
cardinal: e[4],
ordinal: e[38]
},
ce: {
cardinal: e[0]
},
cgg: {
cardinal: e[0]
},
chr: {
cardinal: e[0]
},
ckb: {
cardinal: e[0]
},
cs: {
cardinal: e[8]
},
cy: {
cardinal: e[9],
ordinal: e[39]
},
da: {
cardinal: e[10]
},
de: {
cardinal: e[4]
},
dsb: {
cardinal: e[11]
},
dv: {
cardinal: e[0]
},
ee: {
cardinal: e[0]
},
el: {
cardinal: e[0]
},
en: {
cardinal: e[4],
ordinal: e[40]
},
eo: {
cardinal: e[0]
},
es: {
cardinal: e[0]
},
et: {
cardinal: e[4]
},
eu: {
cardinal: e[0]
},
fa: {
cardinal: e[2]
},
ff: {
cardinal: e[12]
},
fi: {
cardinal: e[4]
},
fil: {
cardinal: e[13],
ordinal: e[0]
},
fo: {
cardinal: e[0]
},
fr: {
cardinal: e[12],
ordinal: e[0]
},
fur: {
cardinal: e[0]
},
fy: {
cardinal: e[4]
},
ga: {
cardinal: e[14],
ordinal: e[0]
},
gd: {
cardinal: e[15]
},
gl: {
cardinal: e[4]
},
gsw: {
cardinal: e[0]
},
gu: {
cardinal: e[2],
ordinal: e[41]
},
guw: {
cardinal: e[1]
},
gv: {
cardinal: e[16]
},
ha: {
cardinal: e[0]
},
haw: {
cardinal: e[0]
},
he: {
cardinal: e[17]
},
hi: {
cardinal: e[2],
ordinal: e[41]
},
hr: {
cardinal: e[7]
},
hsb: {
cardinal: e[11]
},
hu: {
cardinal: e[0],
ordinal: e[42]
},
hy: {
cardinal: e[12],
ordinal: e[0]
},
is: {
cardinal: e[18]
},
it: {
cardinal: e[4],
ordinal: e[43]
},
iu: {
cardinal: e[19]
},
iw: {
cardinal: e[17]
},
jgo: {
cardinal: e[0]
},
ji: {
cardinal: e[4]
},
jmc: {
cardinal: e[0]
},
ka: {
cardinal: e[0],
ordinal: e[44]
},
kab: {
cardinal: e[12]
},
kaj: {
cardinal: e[0]
},
kcg: {
cardinal: e[0]
},
kk: {
cardinal: e[0],
ordinal: e[45]
},
kkj: {
cardinal: e[0]
},
kl: {
cardinal: e[0]
},
kn: {
cardinal: e[2]
},
ks: {
cardinal: e[0]
},
ksb: {
cardinal: e[0]
},
ksh: {
cardinal: e[20]
},
ku: {
cardinal: e[0]
},
kw: {
cardinal: e[19]
},
ky: {
cardinal: e[0]
},
lag: {
cardinal: e[21]
},
lb: {
cardinal: e[0]
},
lg: {
cardinal: e[0]
},
ln: {
cardinal: e[1]
},
lt: {
cardinal: e[22]
},
lv: {
cardinal: e[23]
},
mas: {
cardinal: e[0]
},
mg: {
cardinal: e[1]
},
mgo: {
cardinal: e[0]
},
mk: {
cardinal: e[24],
ordinal: e[46]
},
ml: {
cardinal: e[0]
},
mn: {
cardinal: e[0]
},
mo: {
cardinal: e[25],
ordinal: e[0]
},
mr: {
cardinal: e[2],
ordinal: e[47]
},
mt: {
cardinal: e[26]
},
nah: {
cardinal: e[0]
},
naq: {
cardinal: e[19]
},
nb: {
cardinal: e[0]
},
nd: {
cardinal: e[0]
},
ne: {
cardinal: e[0],
ordinal: e[48]
},
nl: {
cardinal: e[4]
},
nn: {
cardinal: e[0]
},
nnh: {
cardinal: e[0]
},
no: {
cardinal: e[0]
},
nr: {
cardinal: e[0]
},
nso: {
cardinal: e[1]
},
ny: {
cardinal: e[0]
},
nyn: {
cardinal: e[0]
},
om: {
cardinal: e[0]
},
or: {
cardinal: e[0]
},
os: {
cardinal: e[0]
},
pa: {
cardinal: e[1]
},
pap: {
cardinal: e[0]
},
pl: {
cardinal: e[27]
},
prg: {
cardinal: e[23]
},
ps: {
cardinal: e[0]
},
pt: {
cardinal: e[28]
},
"pt-PT": {
cardinal: e[29]
},
rm: {
cardinal: e[0]
},
ro: {
cardinal: e[25],
ordinal: e[0]
},
rof: {
cardinal: e[0]
},
ru: {
cardinal: e[30]
},
rwk: {
cardinal: e[0]
},
saq: {
cardinal: e[0]
},
sdh: {
cardinal: e[0]
},
se: {
cardinal: e[19]
},
seh: {
cardinal: e[0]
},
sh: {
cardinal: e[7]
},
shi: {
cardinal: e[31]
},
si: {
cardinal: e[32]
},
sk: {
cardinal: e[8]
},
sl: {
cardinal: e[33]
},
sma: {
cardinal: e[19]
},
smi: {
cardinal: e[19]
},
smj: {
cardinal: e[19]
},
smn: {
cardinal: e[19]
},
sms: {
cardinal: e[19]
},
sn: {
cardinal: e[0]
},
so: {
cardinal: e[0]
},
sq: {
cardinal: e[0],
ordinal: e[49]
},
sr: {
cardinal: e[7]
},
ss: {
cardinal: e[0]
},
ssy: {
cardinal: e[0]
},
st: {
cardinal: e[0]
},
sv: {
cardinal: e[4],
ordinal: e[50]
},
sw: {
cardinal: e[4]
},
syr: {
cardinal: e[0]
},
ta: {
cardinal: e[0]
},
te: {
cardinal: e[0]
},
teo: {
cardinal: e[0]
},
ti: {
cardinal: e[1]
},
tig: {
cardinal: e[0]
},
tk: {
cardinal: e[0]
},
tl: {
cardinal: e[13],
ordinal: e[0]
},
tn: {
cardinal: e[0]
},
tr: {
cardinal: e[0]
},
ts: {
cardinal: e[0]
},
tzm: {
cardinal: e[34]
},
ug: {
cardinal: e[0]
},
uk: {
cardinal: e[30],
ordinal: e[51]
},
ur: {
cardinal: e[4]
},
uz: {
cardinal: e[0]
},
ve: {
cardinal: e[0]
},
vo: {
cardinal: e[0]
},
vun: {
cardinal: e[0]
},
wa: {
cardinal: e[1]
},
wae: {
cardinal: e[0]
},
xh: {
cardinal: e[0]
},
xog: {
cardinal: e[0]
},
yi: {
cardinal: e[4]
},
zu: {
cardinal: e[2]
},
lo: {
ordinal: e[0]
},
ms: {
ordinal: e[0]
},
vi: {
ordinal: e[0]
}
};
}, {}],
4: [function(r, n, a) {
n.exports = function r(n, a) {
if (a[n]) return n;
var e = [].concat(n || []);
for (var t = 0, i = e.length; t < i; ++t) {
var o = e[t].split("-");
while (o.length) {
if (o.join("-") in a) return o.join("-");
o.pop();
}
}
return "en";
};
}, {}],
5: [function(r, n, a) {
"use strict";
n.exports = function r(n) {
if ("string" !== typeof n) throw new w("Pattern must be a string");
return m({
pattern: n,
index: 0
}, "message");
};
function e(r) {
return "0" === r || "1" === r || "2" === r || "3" === r || "4" === r || "5" === r || "6" === r || "7" === r || "8" === r || "9" === r;
}
function t(r) {
var n = r && r.charCodeAt(0);
return n >= 9 && n <= 13 || 32 === n || 133 === n || 160 === n || 6158 === n || n >= 8192 && n <= 8205 || 8232 === n || 8233 === n || 8239 === n || 8287 === n || 8288 === n || 12288 === n || 65279 === n;
}
function i(r) {
var n = r.pattern;
var a = n.length;
while (r.index < a && t(n[r.index])) ++r.index;
}
function o(r, n) {
var a = r.pattern;
var e = a.length;
var i = "plural" === n || "selectordinal" === n;
var o = "style" === n;
var l = "";
var c;
while (r.index < e) {
c = a[r.index];
if ("{" === c || "}" === c || i && "#" === c || o && t(c)) break;
else if ("'" === c) {
c = a[++r.index];
if ("'" === c) {
l += c;
++r.index;
} else if ("{" === c || "}" === c || i && "#" === c || o && t(c)) {
l += c;
while (++r.index < e) {
c = a[r.index];
if ("''" === a.slice(r.index, r.index + 2)) {
l += c;
++r.index;
} else if ("'" === c) {
++r.index;
break;
} else l += c;
}
} else l += "'";
} else {
l += c;
++r.index;
}
}
return l;
}
function l(r) {
var n = r.pattern;
if ("#" === n[r.index]) {
++r.index;
return ["#"];
}++r.index;
var a = c(r);
var e = n[r.index];
if ("}" === e) {
++r.index;
return [a];
}
if ("," !== e) p(r, ",");
++r.index;
var t = u(r);
e = n[r.index];
if ("}" === e) {
if ("plural" === t || "selectordinal" === t || "select" === t) p(r, t + " message options");
++r.index;
return [a, t];
}
if ("," !== e) p(r, ",");
++r.index;
var i;
var o;
if ("plural" === t || "selectordinal" === t) {
o = f(r);
i = s(r, t);
} else if ("select" === t) i = s(r, t);
else i = d(r);
e = n[r.index];
if ("}" !== e) p(r, "}");
++r.index;
return "plural" === t || "selectordinal" === t ? [a, t, o, i] : [a, t, i];
}
function c(r) {
i(r);
var n = r.pattern;
var a = n.length;
var e = "";
while (r.index < a) {
var o = n[r.index];
if ("{" === o || "#" === o) p(r, "argument id");
if ("}" === o || "," === o || t(o)) break;
e += o;
++r.index;
}
if (!e) p(r, "argument id");
i(r);
return e;
}
function u(r) {
i(r);
var n = r.pattern;
var a;
var e = ["number", "date", "time", "ordinal", "duration", "spellout", "plural", "selectordinal", "select"];
for (var t = 0, o = e.length; t < o; ++t) {
var l = e[t];
if (n.slice(r.index, r.index + l.length) === l) {
a = l;
r.index += l.length;
break;
}
}
if (!a) p(r, e.join(", "));
i(r);
return a;
}
function d(r) {
i(r);
var n = o(r, "style");
if (!n) p(r, "argument style name");
i(r);
return n;
}
function f(r) {
i(r);
var n = 0;
var a = r.pattern;
var t = a.length;
if ("offset:" === a.slice(r.index, r.index + 7)) {
r.index += 7;
i(r);
var o = r.index;
while (r.index < t && e(a[r.index])) ++r.index;
if (o === r.index) p(r, "offset number");
n = +a.slice(o, r.index);
i(r);
}
return n;
}
function s(r, n) {
i(r);
var a = r.pattern;
var e = a.length;
var t = {};
var o = false;
while (r.index < e && "}" !== a[r.index]) {
var l = h(r);
i(r);
t[l] = v(r, n);
o = true;
i(r);
}
if (!o) p(r, n + " message options");
if (!("other" in t)) p(r, null, null, '"other" option must be specified in ' + n);
return t;
}
function h(r) {
var n = r.pattern;
var a = n.length;
var e = "";
while (r.index < a) {
var o = n[r.index];
if ("}" === o || "," === o) p(r, "{");
if ("{" === o || t(o)) break;
e += o;
++r.index;
}
if (!e) p(r, "selector");
i(r);
return e;
}
function v(r, n) {
var a = r.pattern[r.index];
if ("{" !== a) p(r, "{");
++r.index;
var e = m(r, n);
a = r.pattern[r.index];
if ("}" !== a) p(r, "}");
++r.index;
return e;
}
function m(r, n) {
var a = r.pattern;
var e = a.length;
var t;
var i = [];
if (t = o(r, n)) i.push(t);
while (r.index < e) {
if ("}" === a[r.index]) {
if ("message" === n) p(r);
break;
}
i.push(l(r, n));
if (t = o(r, n)) i.push(t);
}
return i;
}
function p(r, n, a, t) {
var i = r.pattern;
var o = i.slice(0, r.index).split(/\r?\n/);
var l = r.index;
var c = o.length;
var u = o.slice(-1)[0].length;
if (!a)
if (r.index >= i.length) a = "end of input";
else {
a = i[r.index];
while (++r.index < i.length) {
var d = i[r.index];
if (!e(d) && d.toUpperCase() === d.toLowerCase()) break;
a += d;
}
}
if (!t) t = g(n, a);
t += " in " + i.replace(/\r?\n/g, "\n");
throw new w(t, n, a, l, c, u);
}
function g(r, n) {
if (!r) return "Unexpected " + n + " found";
return "Expected " + r + " but " + n + " found";
}
function w(r, n, a, e, t, i) {
Error.call(this, r);
this.name = "SyntaxError";
this.message = r;
this.expected = n;
this.found = a;
this.offset = e;
this.line = t;
this.column = i;
}
w.prototype = Object.create(Error.prototype);
n.exports.SyntaxError = w;
}, {}],
6: [function(r, n, a) {
/*!
* Intl.MessageFormat prollyfill
* Copyright(c) 2015 Andy VanWagoner
* MIT licensed
**/
"use strict";
var e = r("format-message-parse");
var t = r("format-message-interpret");
var i = t.closestSupportedLocale;
function o(r, n) {
if (!(this instanceof o)) return new o(r, n);
var a = t(r, e(n));
this._internal = {
locale: i(r),
format: "string" === typeof a ? function r() {
return a;
} : a
};
}
n.exports = o;
Object.defineProperties(o.prototype, {
resolvedOptions: {
configurable: true,
writable: true,
value: function r() {
return {
locale: this._internal.locale
};
}
},
format: {
configurable: true,
get: function() {
return this._internal.format;
}
},
_internal: {
configurable: true,
writable: true,
value: {
locale: "en",
format: function r() {
return "";
}
}
}
});
Object.defineProperties(o, {
supportedLocalesOf: {
configurable: true,
writable: true,
value: function r(n) {
return [].concat(n || []).filter(function(r, n, a) {
var e = i(r);
return e === r.slice(0, e.length) && a.indexOf(r) === n;
});
}
}
});
}, {
"format-message-interpret": 2,
"format-message-parse": 5
}]
}, {}, [6])(6);
});
},
7: function(r, n) {
var a;
a = function() {
return this;
}();
try {
a = a || Function("return this")() || (0, eval)("this");
} catch (r) {
if ("object" === typeof window) a = window;
}
r.exports = a;
}
}, [238]);
|
import React, { Component } from 'react'
import { deleteSupervisor, deleteUser, getUserForRole } from '../services/ApiService'
import { Link as RouterLink,withRouter, Redirect } from 'react-router-dom';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Divider from '@material-ui/core/Divider';
import GetAppIcon from '@material-ui/icons/GetApp';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import AccountBoxIcon from '@material-ui/icons/AccountBox';
import { Container, Grid, TextField } from '@material-ui/core';
import SearchIcon from '@material-ui/icons/Search';
import VisibilityIcon from '@material-ui/icons/Visibility';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import EditIcon from '@material-ui/icons/Edit';
import DeleteIcon from '@material-ui/icons/Delete';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import Typography from '@material-ui/core/Typography';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import Switch from '@material-ui/core/Switch';
import localStorageService from '../services/localStorageService';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
class UserList extends Component {
state = {
users: '',
open: false,
deleteopen:false,
deletingUser:null,
}
userRole(role){
switch(role) {
case 'ROLE_admin':
return 'Administator';
case 'ROLE_hr':
return 'HR';
case 'ROLE_supervisor':
return 'Supervisor';
case 'ROLE_secretary':
return 'Secretary';
case 'ROLE_director':
return 'Director';
default:
return '';
}
}
async componentDidMount() {
await getUserForRole(localStorageService.getItem('role')).then(data => {
const results = data.data;
this.setState({
users: results
})
}).catch(
)
console.log(this.state.users)
}
handelAgree =() =>{
deleteUser(this.state.deletingUser.username).then(data=>{}).catch();
let temp= this.state.users.filter(item => item.username !== this.state.deletingUser.username);
this.setState({users:temp})
this.setState({ deleteopen: false });
// this.componentDidMount()
}
handleDeleteOpen = (user) => {
this.setState({deletingUser:user})
this.setState({ deleteopen: true });
};
handleDeleteClose = () => {
this.setState({ deleteopen: false });
};
// deleteById =(id) =>{
// deleteTrainee(id).then(data=>{}).catch();
// }
render() {
let filtred = this.state.users.slice();
return (
<div>
<Grid container spacing={3}>
<Grid item xs={12} sm={3}>
</Grid>
<Grid item xs={12} sm={3}>
</Grid>
<Grid item xs={12} sm={3}></Grid>
<Grid item xs={12} sm={3}>
<div style={{textAlign:'right', marginTop:'15px'}}><Button variant="outlined" color="primary" onClick={()=>this.props.history.push("/addUser")}> Create New</Button></div>
</Grid>
</Grid>
<br></br>
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead >
<TableRow>
<TableCell align="left"><h4>First Name</h4></TableCell>
<TableCell align="left"><h4>Last Name</h4></TableCell>
<TableCell align="left"><h4>User Name</h4></TableCell>
<TableCell align="left"><h4>Role</h4></TableCell>
<TableCell align="right"></TableCell>
</TableRow>
</TableHead>
<TableBody>
{
this.state.users && filtred.map((user, index) => (
<TableRow hover key={index}>
<TableCell align="left">{user.firstName}</TableCell>
<TableCell align="left">{user.lastName}</TableCell>
<TableCell align="left">{user.username}</TableCell>
<TableCell align="left">{this.userRole(user.role)}</TableCell>
<TableCell align="right">
{ user.role!=="ROLE_admin" &&
<IconButton edge="start" color="secondary" onClick={e=>this.handleDeleteOpen(user)} aria-label="menu">
<DeleteIcon />
</IconButton>
}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<Dialog
open={this.state.deleteopen}
onClose={this.handleDeleteClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{"Use Google's location service?"}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Do you want the delete the user?
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.handleDeleteClose} color="primary">
Disagree
</Button>
<Button onClick={this.handelAgree} color="primary" autoFocus>
Agree
</Button>
</DialogActions>
</Dialog>
</div>
)
}
}
export default withRouter(UserList);
|
import configureContainer from '../../container';
function makeDeliveryLambdaExtendJobLock({
extendJobLockByJobKey,
getLogger,
}) {
return async function delivery(input) {
const logger = getLogger();
logger.addContext('input', input);
logger.debug('start');
const {
jobStatic: {
key: jobKey,
},
jobExecution: {
name: jobExecutionName,
},
callbackResult: {
progress,
},
} = input;
const updatedJob = await extendJobLockByJobKey({
jobExecutionName,
jobKey,
progress,
});
return updatedJob;
};
}
export const delivery = configureContainer().build(
makeDeliveryLambdaExtendJobLock,
);
|
import bookshelf from '../config/bookshelf';
import Hospital from './hospital.model';
import Order from './order.model';
/**
* Order Status model.
*/
class OrderStatus extends bookshelf.Model {
get tableName() {
return 'order_status';
}
get hasTimestamps() {
return true;
}
Orders() {
return this.hasMany(Order, "Status_Id");
}
}
export default OrderStatus; |
const stream = require("stream");
function MyReadable(){
}
MyReadable.prototype = stream.Readable();
var myRead = new MyReadable();
myRead.push("abcdefghijklmnopqrstuvwxyz");
myRead.push(null);
myRead.pipe(process.stdout);
|
/* global module require __dirname */
const path = require('path');
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const Handlebars = require('handlebars');
const { validate } = require('./config-validator');
const { init, handleRoute } = require('./router/server');
const config = require('./web/config');
const basePath = path.join(__dirname, './');
const readFile = (basePath, filePath) => {
try {
// Attempt reading file contents
return fs.readFileSync(
path.join(basePath, filePath),
'utf8'
);
} catch (e) {
// Return error string
return config.genericErrorText;
}
};
const serveRequest = ({ headers, url }, res) => {
if (config.redirects[url]) {
// Use the known redirect
res.redirect(config.redirects[url]);
} else if (url === '/sw.js') {
// Serve the service worker script
res.set('Content-Type', 'text/javascript');
res.send(readFile(basePath, `public${url}`));
} else if (config.exceptionsForStaticDirectory.indexOf(url) > -1) {
// Serve the file and end the response
res.send(readFile(basePath, `public${url}`));
} else {
// Gather landing HTML page string components
const landingPageTemplate = readFile(basePath, 'public/index.html');
const bodyTemplate = Handlebars.compile(readFile(basePath, 'web/body.html'));
const parentPageDomString = landingPageTemplate.replace(
'<!--body-tag-placeholder-->',
bodyTemplate()
);
// Handle route with server router
handleRoute(url, parentPageDomString, res, basePath);
}
};
module.exports = portNumber => {
// Validate configs
if (!validate(config)) {
return;
}
// Create web-app and perform init
const app = express();
init(config);
// Setup statics
app.use(`/${config.staticPath}`, express.static(path.join(basePath, 'public')));
app.use(bodyParser.json());
// Start the web server
app.listen(
portNumber,
() => {
console.log(config.appName, 'started on', portNumber);
}
);
// Host all Web API handlers
config.webApis.forEach(
({ url, handler }) => {
app.post(
url,
(req, res) => {
res.send(handler(req));
}
);
}
);
// Serve index page
app.get('*', serveRequest);
};
|
import React from 'react';
import Rating from './Rating';
const DriverCard = ({name,rating,img,car})=>{
const image = {backgroundImage:`url(${img})`}
return(
<div className="DriveCard-container">
<div className="DriveCard-content">
<div className="DriveCard-img" style={image}/>
<div className="DriveCard-info">
<p className="DriveCard-name">{name}</p>
<Rating
rate={Math.round(rating)}
color="white"
/>
<p className="DriveCard-carDescription">{`${car.model} - ${car.licensePlate}`}</p>
</div>
</div>
</div>
)
};
export default DriverCard
|
X.define("modules.system.systemlogList",["model.systemLogModel","common.layer","modules.common.routerHelper"],function (systemLogModel,layer,routerHelper) {
//初始化视图对象
var view = X.view.newOne({
el: $(".xbn-content"),
url: X.config.systemLog.tpl.systemlogList
});
//初始化控制器
var ctrl = X.controller.newOne({
view: view
});
ctrl.rendering = function () {
view.render({},function(){
activeTabLiInfo = route.getRoute() || activeTabLiInfo;
ctrl.initPage()
});
};
var header = (function () {
return {
"tabAll": [
{
field: {
name: "backendUserName",
title: "操作人",
type: "string"
},
width: "5%",
className: "tL"
},
{
field: {
name: "operationDetail",
title: "行为",
type: "string"
},
width: "15%"
},
{
field: {
name: "createDate",
title: "时间",
type: "string"
},
width: "9%"
},
{
field: {
name: "ipAddress",
title: "IP",
type: "string"
},
width: "6%"
},
{
field: {
name: "",
title: "操作",
type: "operation"
},
itemRenderer: {
render: function (data, field, index, grid) {
return $("<i class='iconfont icon-lajitong'></i>")
.on("click", function (event) {
var deldata =[];
deldata.push(data.operationLogId);
layer.successConfirm('确认删除?', function(index){
systemLogModel.systemLogDelete(deldata,function(){
layer.successMsg('删除成功',function(){
layer.closeIt();
});
lists["tabAll"].loadData();
});
});
})[0];
}
},
width: "10%",
className: "operation_main"
}
]
}
})();
var formatSearchData = function(data){
var createDateRange = data.query.createDateRange;
if(createDateRange){
createDateRanges=createDateRange.split("@");
beginTime=createDateRanges[0]+" 00:00:00";
endTime=createDateRanges[1]+" 23:59:59";
data.query.createDateRange ={beginTime:beginTime,endTime:endTime};
}
return data;
};
var getRoute = function () {
var route = {panel:activeTabLiInfo,ldata:lists[activeTabLiInfo].val()};
return route;
};
var schemas = (function(){
var schemas = {
"tabAll" : {
searchMeta: {
schema: {
simple:[
{
name:"backendUserName",
title:"操作人",
ctrlType:"TextBox",
placeholder :"请输入操作人姓名"
},
{
name:"createDateRange",
title:"操作时间",
ctrlType:"DateRangePicker",
placeholder:"2015/6/22-2016/2/16"
},
{
name:"ipAddress",
title:"IP",
ctrlType:"TextBox",
placeholder :"输入IP地址"
},
{
name:"operationId",
title:"功能模块",
ctrlType:"ComboBox",
refUrl : X.config.systemLog.api.operationModules,
refKey : "operationId",
refValue : "operationName"
}
]
},
search: {
onSearch : function (data,searcher,click) {
if(click){
route.setRoute(getRoute());
}
return formatSearchData(data);
}
},
reset :{
show:true
}
},
gridMeta :{
columns : header["tabAll"],
primaryKey:systemLogModel.option.idAttribute,
orderMode : 1
},
pageInfo : {
pageSize : '10',
totalPages : '10',
pageNo: '1',
smallPapogation: {
isShow: false,
elem: '.js_small_papogation1'
}
},
url : X.config.systemLog.api.operationLogListByPage,
toolbar : {
items: [
{
ctrlType:"ToolbarButton",
name:"csvFile",
title:"导出",
icon:"icon-daochu",
click:function (item) {
//var url = X.config.systemLog.api.csvFile;
var pageInfo = schemas.tabAll.pageInfo,
option = {
data: lists[activeTabLiInfo].condition,
callback: function(result) {
var blob = new Blob(['\ufeff' + result], {type: 'text/cfv'}),
url = URL.createObjectURL(blob),
link = ctrl.view.el.find('.listButton.js-csvFile'),
href = $('<a href="'+url+'" class="chk" download="操作日志.csv"></a>')
link.after(href);
href[0].click();
href.remove();
}
};
systemLogModel.export(option);
//ctrl.view.el.find(".js-spreadDownload").attr("src",url);
}
}
]
}
}
};
return schemas;
})();
var lists = {};
var activeTabLiInfo = "tabAll";
function initTabPage($elem,schema,tabPage) {
var list = X.controls.getControl("List",$elem,schema);
list.init();
lists[tabPage] = list;
}
ctrl.initPage =function (){
var tabPannel = X.controls.getControl("TabPanel",$('.js_tabPannel1'), {
activeTabInfo: activeTabLiInfo,
beforeChangeTab: function (tabLiInfo, targetLi, index, tabPage) {
activeTabLiInfo = tabLiInfo;
// 刊登状态 不同
var page = $(tabPage);
if(!page.data("hasInited")){
var schema = schemas[tabLiInfo];
if(schema){
initTabPage(page,schema,tabLiInfo);
}
page.data("hasInited",true);
}
// 为了样式效果,把当前选中的前一个加上样式名
targetLi.prev().removeClass('tab_lineNone');
return true;
},
afterChangeTab: function (tabLiInfo, targetLi, index, tabPage) {
activeTabLiInfo = tabLiInfo;
activeTabLi = targetLi;
// 为了样式效果,把当前选中的前一个加上样式名
targetLi.prev().addClass('tab_lineNone');
}
});
};
ctrl.load = function (para) {
ctrl.rendering();
};
var route = new routerHelper("system.systemlogList",schemas,getRoute);
return ctrl;
});
|
const browserWaits = require('../../../support/customWaits')
class CaseDetailsBasicView{
constructor(){
this.container = $('ccd-case-basic-access-view')
this.bannerMessageContainer = $('ccd-case-basic-access-view .hmcts-banner__message')
this.requestAccessButton = $('ccd-case-basic-access-view button')
}
async isRowDisplayedWithAttribute(key){
const e = element(by.xpath(`//div[contains(@class,'govuk-summary-list__row')]/dt[contains(text(),'${key}')]`))
return await e.isPresent()
}
async getAttributeValues(key){
const e = element(by.xpath(`//div[contains(@class,'govuk-summary-list__row')]/dt[contains(text(),'${key}')]/../dd`))
return await e.getText()
}
}
module.exports = new CaseDetailsBasicView();
|
'use strict';
// Declare app level module which depends on views, and components
var project_X = angular.module('project_X', [
'ui.router',
'project_X.prediction',
'project_X.graphs',
'project_X.training'
]).
config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/training');
}])
.controller('rootController', ['$scope', '$http', '$location', function($scope, $http, $location) {
var rootCtrl = this;
rootCtrl.active = ($location.path().split("/")[1] == undefined) ? "training" : $location.path().split("/")[1];
rootCtrl.setActive = function(item) {
rootCtrl.active = item;
}
}]); |
import React from 'react'
import {connect} from 'react-redux'
import * as actions from '../action/ItemActions'
import Item from '../components/Item'
export default connect((state, props) => ({
_id : props.todo.get('_id'),
text : props.todo.get('text'),
active : props.todo.get('active'),
error : props.todo.get('viewParams').get('error')
}), actions)(Item)
|
/**
* some JavaScript code for this blog theme
*/
/* jshint asi:true */
/////////////////////////header////////////////////////////
/**
* clickMenu
*/
(function () {
if (window.innerWidth <= 770) {
var menuBtn = document.querySelector('#headerMenu')
var nav = document.querySelector('#headerNav')
menuBtn.onclick = function (e) {
e.stopPropagation()
if (menuBtn.classList.contains('active')) {
menuBtn.classList.remove('active')
nav.classList.remove('nav-show')
} else {
nav.classList.add('nav-show')
menuBtn.classList.add('active')
}
}
document.querySelector('body').addEventListener('click', function () {
nav.classList.remove('nav-show')
menuBtn.classList.remove('active')
})
}
}());
//////////////////////////back to top////////////////////////////
(function () {
var backToTop = document.querySelector('.back-to-top')
var backToTopA = document.querySelector('.back-to-top a')
// console.log(backToTop);
window.addEventListener('scroll', function () {
// 页面顶部滚进去的距离
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop)
if (scrollTop > 200) {
backToTop.classList.add('back-to-top-show')
} else {
backToTop.classList.remove('back-to-top-show')
}
})
// backToTopA.addEventListener('click',function (e) {
// e.preventDefault()
// window.scrollTo(0,0)
// })
}());
//////////////////////////scrollPos//////////////////////////////
(function () {
if (document.getElementById('content-side')) {
var $navs = document.getElementById('content-side').querySelectorAll('a'), // 导航
$sections = document.querySelector('.left').querySelectorAll('h2,h3,h4,h5'); // 模块 h1为文章标题
window.onscroll = function (e) {
e.stopPropagation()
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
function getOffset(el) {
const box = el.getBoundingClientRect();
return {
top: box.top + window.pageYOffset - document.documentElement.clientTop,
left: box.left + window.pageXOffset - document.documentElement.clientLeft
}
}
for (let i = 0; i < $navs.length ; i++) {
var that = $sections[i];
if (scrollTop >= getOffset(that).top - 50) {
// 高亮目录
$navs.forEach(function (e) {
e.closest('li').classList.remove('current')
})
$navs[i].closest('li').classList.add('current')
// 右边目录根据滚动定位
var navATop = $navs[i].offsetTop // 高亮目录距离顶部的距离
navBox = document.getElementById('content-side'),
navBoxClientHeight = navBox.clientHeight, // 目录容器可见区域的高度
navBoxScrollTop = navBox.scrollTop; // 目录容器顶部被隐藏的高度
// navBoxScrollHeight = navBox.scrollHeight; // 目录容器总高度
if (navATop >= navBoxClientHeight) {
navBox.scrollTop = navATop - navBoxClientHeight / 2 // 保证高亮目录在目录容器可见区域的中间位置
} else {
navBox.scrollTop = 0
}
}
}
}
}
}());
// 设置图片说明宽度
(function () {
var img_instructions = document.querySelectorAll('.img-instructions');
var timer = setInterval(function () {
var imgLoadComplete = true; // 图片是否全部加载完成
for (var i = 0; i < img_instructions.length; i++) {
var img = img_instructions[i].previousElementSibling.querySelectorAll('img')[0];
if (img.complete) {
var imgBoxWidth = img.clientWidth;
img_instructions[i].style.width = imgBoxWidth - 10 + 'px';
} else {
imgLoadComplete = false;
}
}
if (imgLoadComplete) {
clearInterval(timer)
}
}, 500)
})() |
import React from 'react'
import { View, Alert } from 'react-native'
import { LoginButton, AccessToken } from 'react-native-fbsdk'
import { connect } from 'react-redux'
import firebase from 'firebase'
import { loginFacebookUser } from '../actions'
const onLoginFinished = (err, result) => {
if (err) {
Alert.alert('Facebook Error', `Error logging into Facebook: ${err}`)
console.error(`Login response has error: ${err}`)
} else if (result.isCanceled) {
console.log('Login was canceled')
} else {
AccessToken.getCurrentAccessToken()
.then(data => {
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken)
firebase.auth().signInWithCredential(credential)
.then(user => loginFacebookUser({ user }))
.catch(err => {
console.error('Firebase authentication error with Facebook', err)
Alert.alert('Firebase Error', `Firebase authentication error: ${err}`)
})
})
}
}
const FacebookButton = () => (
<View style={{flex: 1}}>
<View style={{alignSelf: 'center'}}>
<LoginButton
publishPermissions={['publish_actions']}
onLoginFinished={onLoginFinished}
onLogoutFinished={() => firebase.auth().signOut()}
/>
</View>
</View>
)
export default connect(null, { loginFacebookUser })(FacebookButton)
|
import {DefaultLogger as winston} from '@dracul/logger-backend';
import RoleModel from '../models/RoleModel'
import {UserInputError} from 'apollo-server-express'
export const fetchRolesInName = function (roleNames) {
return new Promise((resolve, reject) => {
RoleModel.find({name: {$in: roleNames }}).exec((err, res) => {
if(err){
winston.error("RoleService.fetchRolesInName ", err)
reject(err)
}
winston.debug('RoleService.fetchRolesInName successful')
resolve(res)
});
})
}
export const findRoles = function (roles = []) {
return new Promise((resolve, reject) => {
let qs = {}
if (roles && roles.length) {
qs._id = {$in: roles}
}
RoleModel.find(qs).isDeleted(false).exec((err, res) => {
if(err){
winston.error("RoleService.findRoles ", err)
reject(err)
}
winston.debug('RoleService.findRoles successful')
resolve(res)
});
})
}
export const findRole = function (id) {
return new Promise((resolve, reject) => {
RoleModel.findOne({ _id: id }).exec((err, res) => {
if(err){
winston.error("RoleService.findRole ", err)
reject(err)
}
winston.debug('RoleService.findRole successful')
resolve(res)
});
})
}
export const findRoleByName = function (roleName) {
return new Promise((resolve, reject) => {
RoleModel.findOne({ name: roleName }).exec((err, res) => {
if(err){
winston.error("RoleService.findRoleByName ", err)
reject(err)
}
winston.debug('RoleService.findRoleByName successful')
resolve(res)
});
})
}
export const deleteRole = function (id) {
return new Promise((resolve, rejects) => {
findRole(id).then((doc) => {
doc.softdelete(function (err) {
if(err){
winston.error("RoleService.deleteRole ", err)
reject(err)
}
winston.info('RoleService.deleteRole successful')
resolve({ id: id, success: true })
});
})
})
}
export const createRole = function ({ name, childRoles, permissions }) {
const newRole = new RoleModel({
name,
childRoles,
permissions
})
newRole.id = newRole._id;
return new Promise((resolve, rejects) => {
newRole.save((error => {
if (error) {
if (error.name == "ValidationError") {
winston.warn("RoleService.createRole.ValidationError ", error)
rejects(new UserInputError(error.message, {inputErrors: error.errors}));
}else{
winston.error("RoleService.createRole ", error)
}
rejects(error)
} else {
winston.info('RoleService.createRole successful')
resolve(newRole)
}
}))
})
}
export const updateRole = async function (id, { name, childRoles, permissions = [] }) {
return new Promise((resolve, rejects) => {
RoleModel.findOneAndUpdate({ _id: id },
{ name, childRoles, permissions },
{ new: true, runValidators: true, context: 'query' },
(error, doc) => {
if (error) {
if (error.name == "ValidationError") {
winston.warn("RoleService.updateRole.ValidationError ", error)
rejects(new UserInputError(error.message, { inputErrors: error.errors }));
}else{
winston.error("RoleService.updateRole ", error)
}
rejects(error)
}
winston.info('RoleService.updateRole successful')
resolve(doc)
})
})
}
|
import React from "react";
import {
View,
StyleSheet,
ScrollView,
Dimensions,
Text,
SafeAreaView
} from "react-native";
import LinearGradient from "react-native-linear-gradient";
import Header from "../components/Header";
import Tabs from "../components/Tabs";
import ItemCard from "../components/ItemCard";
import ButtonRound from "../components/ButtonRound";
import EngineComponent from "../components/EngineComponent";
import InputWithLabel from "../components/InputWithLabel";
const CalculatorMechanical = (props) => {
const {
main,
page,
linearGradient,
resultsScrollMain,
resultsScroll,
resultsScrollInner,
resultsScrollText,
calResult,
suggestedProducts,
submintBtn,
bold,
redcolor,
row,
col
} = styles;
return (
<LinearGradient
start={{ x: 0, y: 0.3 }}
end={{ x: 2, y: 0.3 }}
colors={["#d13139", "#560004", "#560004"]}
style={linearGradient}
>
<View style={main}>
<Header
iconImageRight={require("./../assets/img/bookmarkBorderMaterial.png")}
title="Mechanical"
/>
<View horizontal style={resultsScrollMain}>
<View style={resultsScroll}>
<View style={resultsScrollInner}>
<Text style={resultsScrollText}>HP-AC</Text>
</View>
</View>
</View>
<ScrollView style={{ backgroundColor: "rgb(249, 249, 252)" }}>
<View style={page}>
<View>
<Text style={calResult}>39.66</Text>
</View>
<View style={suggestedProducts}>
<ButtonRound
buttoncolor="#fff"
textcolor="rgb(209, 49, 57)"
bordercolorstyle="rgb(209, 49, 57)"
ButtonText="Suggested Products"
height={46.9}
fontSize={16.4}
/>
</View>
<View>
<EngineComponent />
<View>
<InputWithLabel
leftIcon={require("./../assets/img/torqueDark.png")}
labelText="Torque"
/>
<InputWithLabel
leftIcon={require("./../assets/img/clock.png")}
labelText="RPM"
/>
</View>
</View>
<View style={submintBtn}>
<ButtonRound
buttoncolor="rgb(209, 49, 57)"
textcolor="#fff"
bordercolorstyle="rgb(209, 49, 57)"
ButtonText="Submit"
height={54.5}
fontSize={18.8}
/>
</View>
</View>
</ScrollView>
</View>
</LinearGradient>
);
};
const styles = StyleSheet.create({
linearGradient: {
flex: 1
},
page: {
paddingBottom: 50,
minHeight: Dimensions.get("window").height - 80
},
bold: {
fontFamily: "OpenSans-Bold",
fontWeight: "600"
},
resultsScrollMain: {
backgroundColor: "rgb(0, 83, 138)"
},
resultsScroll: {
width: "100%"
},
resultsScrollInner: {
paddingVertical: 11,
paddingHorizontal: 16,
flexDirection: "row",
textAlign: "center"
},
resultsScrollText: {
fontFamily: "OpenSans-Bold",
fontSize: 16.4,
fontWeight: "600",
fontStyle: "normal",
lineHeight: 21.1,
letterSpacing: 0,
color: "#fff"
},
list: {
flexDirection: "row",
flexWrap: "wrap"
},
ScrollHeading: {
paddingHorizontal: 18,
paddingVertical: 15
},
ScrollHeadingText: {
fontSize: 16,
fontWeight: "normal",
fontStyle: "normal",
letterSpacing: 0,
color: "#4a4a4a"
},
suggestedProducts: {
width: 200,
alignSelf: "center"
},
submintBtn: {
marginTop: 40,
width: 210,
alignSelf: "center"
},
calResult: {
fontFamily: "OpenSans-Bold",
fontSize: 64.5,
fontWeight: "bold",
fontStyle: "normal",
letterSpacing: 0,
textAlign: "center",
color: "rgb(0, 83, 138)"
}
});
export default CalculatorMechanical;
|
import { createAppContainer, createSwitchNavigator } from "react-navigation";
import {
creatStackNavigator,
createStackNavigator
} from "react-navigation-stack";
import LoginScreen from "./screen/LoginScreen";
import LoadingScreen from "./screen/LoadingScreen";
//import RegisterScreen from "./screens/RegisterScreen";
import HomeScreen from "./screen/Home";
import { stopYellow } from "./FirebaseApi";
//initFirebase();
stopYellow();
const AppStack = createStackNavigator({
Home: HomeScreen
});
const AuthStack = createStackNavigator({
Login: LoginScreen
});
export default createAppContainer(
createSwitchNavigator(
{
Loading: LoadingScreen,
App: AppStack,
Auth: AuthStack
},
{
initialRouteName: "Loading"
}
)
);
|
window.onload = function() {
var box = document.getElementsByClassName('sliderImg')[0];
var imgs = box.getElementsByTagName('img');
//获取单张img宽度
var imgWidth = imgs[0].offsetWidth;
var exposeWidth = imgWidth * 0.6;
//console.log(imgWidth);
//设置box总宽度
boxWidth = imgWidth + (imgs.length -1) * exposeWidth;
box.style.width = boxWidth + 'px';
function setPos () {
for (var i = 1, len = imgs.length; i < len; i++) {
imgs[i].style.left = imgWidth + exposeWidth * (i - 1) + 'px';
}
};
setPos();
//计算展开距离
var tranForm = imgWidth * 0.4;
//每张图片展开
for (var i = 0, len = imgs.length; i < len; i++) {
//console.log(i);
(function(i) {
imgs[i].onmouseover = function() {
setPos();
for (var j = 1; j <= i; j++) {
(function frame (j) {
var moveDistance = parseInt(imgs[j].style.left, 10) - tranForm;
imgs[j].style.left = moveDistance + 'px';
})(j);
}
};
})(i);
}
} |
app.controller('brandController',function ($scope,$controller,brandService) {
$controller('baseController',{$scope:$scope});//继承
$scope.findAll=function () {
brandService.findAll().success(
function (response) {
$scope.list = response;
});
};
// //重新加载列表 数据
// $scope.reloadList=function(){
// //切换页码
// // $scope.findPage( $scope.paginationConf.currentPage, $scope.paginationConf.itemsPerPage);
// //由于查询更改重新加载数据的方法
// $scope.search($scope.paginationConf.currentPage,$scope.paginationConf.itemsPerPage);
// }
//分页控件配置 currentPage:当前页 totalItems:总记录数 itemsPerPage:每页记录数 perPageOptions:分页选项 onchange:当页码变更时,自动触发方法
// $scope.paginationConf = {
// currentPage: 1,
// totalItems: 10,
// itemsPerPage: 10,
// perPageOptions: [10, 20, 30, 40, 50],
// onChange: function(){
// $scope.reloadList();//重新加载
// }
// };
//分页
$scope.findPage =function (page,rows) {
brandService.findPage(page,rows).success(function (response) {
$scope.list = response.rows;
$scope.paginationConf.totalItems = response.total;//更新总记录数
})
};
//添加
$scope.add = function () {
// var methodName = "add";
var object = null;
if($scope.entity.id != null){
object=brandService.update($scope.entity);
}else{
object=brandService.add($scope.entity);
}
object.success(function (response) {
if(response.success){
$scope.reloadList();
}
else{
alert(response.message);
}
})
};
//查询实体
$scope.findOne = function (id) {
brandService.findOne(id).success(function (response) {
$scope.entity = response;
})
};
// $scope.selectIds = [];//选中的ID集合
// //更新复选
// $scope.updateSelectction = function ($event,id) {
//
// if($event.target.checked){//如果被选中则添加到数组中
// $scope.selectIds.push(id);
// }else{
// var idx = $scope.selectIds.indexOf(id);
// $scope.selectIds.splice(idx,1);//删除
// }
// }
//批量删除
$scope.dele = function () {
//获取选中的复选框
brandService.dele($scope.selectIds).success(function (response) {
if(response.success){
$scope.reloadList();
}
})
};
$scope.searchEntity = {};//定义搜索对象
//条件查询
$scope.search = function (page,rows) {
brandService.search(page,rows,$scope.searchEntity).success(
function (response) {
$scope.paginationConf.totalItems = response.total;
$scope.list =response.rows;
}
);
}
}); |
var Dinosaur = function(type, numberOffspringYearly) {
this.type = type;
this.offspringPerYear = numberOffspringYearly;
}
module.exports = Dinosaur; |
import { useEffect, useContext } from "react";
import { useHistory } from "react-router-dom";
import { Row, Col, Spin } from "antd";
import { LoadingOutlined } from '@ant-design/icons';
import { requestOrderDetail } from "../actions"
import { StoreContext } from "../store";
export default function OrderCard({ orderId }) {
const { state: { orderDetail: { loading, order } }, dispatch } = useContext(StoreContext);
const { orderItems } = order;
const history = useHistory()
const antIcon = <LoadingOutlined style={{ fontSize: 80 }} spin />;
const paymentRequest = {
apiVersion: 2,
apiVersionMinor: 0,
allowedPaymentMethods: [
{
type: "CARD",
parameters: {
allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
allowedCardNetworks: ["MASTERCARD", "VISA"]
},
tokenizationSpecification: {
type: "PAYMENT_GATEWAY",
parameters: {
gateway: "example"
}
}
}
],
merchantInfo: {
merchantId: "12345678901234567890",
merchantName: "Demo Merchant"
},
transactionInfo: {
totalPriceStatus: "FINAL",
totalPriceLabel: "Total",
totalPrice: String(order.totalPrice),
currencyCode: "USD",
countryCode: "US"
}
};
useEffect(() => {
requestOrderDetail(dispatch, orderId)
}, [orderId])
const getTotalAtk = () => {
return (orderItems.length > 0)
? orderItems.reduce((sum, item) => sum + item.atk, 5)
: 0;
};
const pingfeng = (getTotalAtk) => {
if (getTotalAtk >= 90000) {
return "SS"
}
else if (getTotalAtk >= 70000 && getTotalAtk < 90000) {
return "S"
}
else if (getTotalAtk >= 50000 && getTotalAtk < 70000) {
return "A"
}
else if (getTotalAtk >= 30000 && getTotalAtk < 50000) {
return "B"
}
else {
return "C"
}
}
return (
<>
{loading
? (
<div className="spinner-wrap">
<Spin indicator={antIcon} className="spinner" />
</div>
) : (
<div className="card card-body">
<div className="cardpos">
<h2 className="cardtext">已儲存隊伍至:</h2>
<h2 className="cardid">{orderId}</h2>
</div>
{orderItems.length === 0 ? (
<div className="checkout">快去選擇喜歡的餅乾吧!</div>
) : (<div>
<div className="cooline">
{orderItems.map(item => (
<li key={item.id} className="cart-item">
<div className="cart-image">
<img src={item.image} alt={item.name} />
<div className="cart-item-content">
<div className="cart-name">{item.name}</div>
</div>
</div>
</li>
))}</div>
<div className="cart-total-atk-wrap">
<div className="cart-total-atk">總戰力:{getTotalAtk()}</div>
<div className="cart-total-comment">{pingfeng(getTotalAtk())}級評分</div>
</div>
</div>
)}
</div>
)
}
</>
);
}
|
import { parse } from 'css';
import { convert, sanitizeSelector } from './lib/transformer';
import {
getErrorMessages,
getWarnMessages,
resetMessage
} from './lib/promptMessage';
import { debugMini, debugObj } from './lib/debug';
import { requiredParam } from './lib/roro';
// import transformer from './lib/transformer';
const RULE = 'rule';
const FONT_FACE_RULE = 'font-face';
const MEDIA_RULE = 'media';
const REG_USELESS_CHAR = /[\s;]/g;
/**
* 清理
* selector 有可能是下列这种情形,需要清理 `;\n\t` 这些字符:
*
* "selector": ";\n\t\t\t\t .header \t"
*
* @param {string} [selector=''] 选择器
*/
function cleanSelector(selector = '') {
return selector.replace(REG_USELESS_CHAR, '');
}
function parseRules({
rules = requiredParam('rules'),
transformDescendantCombinator = false
}) {
let styles = {};
let fontFaceRules = [];
let mediaRules = [];
debugObj('rules: ', JSON.stringify(rules, null, 4));
rules.forEach(rule => {
const { media, tagName, type, selectors, position, declarations } = rule;
let style = {};
// 格式化选择器
const cleanedSelector = [].concat(selectors).map(cleanSelector);
// 普通样式规则
if (type === RULE) {
style = convert({ tagName, selectors: cleanedSelector, declarations });
cleanedSelector.forEach(selector => {
let sanitizedSelector = sanitizeSelector({
selector,
transformDescendantCombinator,
position
});
if (sanitizedSelector) {
const pseudoIndex = sanitizedSelector.indexOf(':');
// 处理伪类,比如将 `a:hover` 键名将转换成 `ahover`
if (pseudoIndex > -1) {
let pseudoStyle = {};
const pseudoName = selector.slice(pseudoIndex + 1);
sanitizedSelector = sanitizedSelector.slice(0, pseudoIndex);
Object.keys(style).forEach(prop => {
pseudoStyle[prop + pseudoName] = style[prop];
});
style = pseudoStyle;
}
// 汇总到总是 styles 对象中
styles[sanitizedSelector] = Object.assign(
styles[sanitizedSelector] || {},
style
);
}
});
}
// 字体样式规则
if (type === FONT_FACE_RULE) {
let font = {};
declarations.forEach(declaration => {
font[declaration.property] = declaration.value;
});
fontFaceRules.push(font);
}
// 媒体查询规范
if (type === MEDIA_RULE) {
mediaRules.push({
key: media,
data: parseRules({ rules: rule.rules, transformDescendantCombinator })
});
}
});
return {
styles,
fontFaceRules,
mediaRules
};
}
/**
* 将 css 转换成 js 文件
*
* @export
* @param {any} source - css 字符串
* @param {boolean} [transformDescendantCombinator=false] 是否支持嵌套,具体说明可参考 http://www.aliued.com/?p=4052
* @returns
*/
export function parseStyle(source, transformDescendantCombinator = false) {
const parsedStyleAst = parse(source);
const { stylesheet } = parsedStyleAst;
if (stylesheet.parsingErrors.length) {
throw new Error('StyleSheet Parsing Error occured.');
}
return parseRules({ rules: stylesheet.rules });
}
/**
* 将 css 转换成 字符串 格式
*
* @export
* @param {any} source - css 字符串
* @param {boolean} [transformDescendantCombinator=false] 是否支持嵌套,具体说明可参考 http://www.aliued.com/?p=4052
* @returns
*/
export function toStyleSheet(source, transformDescendantCombinator = false) {
const parsedStyle = parseStyle(source, transformDescendantCombinator);
const { styles } = parsedStyle;
return JSON.stringify(styles || {});
}
|
import '../../styles/EditProfile.css';
import React, { useState } from 'react';
import { updateUserPhoto } from '../../actions/users';
import { updateUser } from '../../actions/users';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import useFormState from '../hooks/useFormState';
const EditProfile = ({ user, updateUser, updateUserPhoto }) => {
const [file, setFile] = useState('');
const [filename, setFilename] = useState('Choose File');
const [message, setMessage] = useState('');
const [name, setName] = useFormState(user.name);
const onChange = (e) => {
setFile(e.target.files[0]);
setFilename(e.target.files[0].name);
};
const onSubmit = async (e) => {
e.preventDefault();
if (name !== user.name) {
updateUser(user._id, { name });
}
if (file) {
const formData = new FormData();
formData.append('file', file);
updateUserPhoto(formData, setMessage, user._id);
}
};
return (
<div className="edit-profile">
<form onSubmit={onSubmit}>
<label>Profile Picture</label>
<div className="custom-file">
<input
type="file"
className="custom-file-input"
id="customFile"
onChange={onChange}
/>
<label className="custom-file-label" htmlFor="customFile">
{filename}
</label>
</div>
{file instanceof File ? (
<img
className="edit-profile-img"
src={URL.createObjectURL(file)}
alt="user avatar"
/>
) : (
<img
className="edit-profile-img"
src={`/uploads/${user.photo}`}
alt="user avatar"
/>
)}
<div className="form-group mt-2">
<label>Name</label>
<input
type="text"
className="form-control"
value={name}
onChange={setName}
/>
</div>
<input
type="submit"
value="Save"
className="btn btn-block mt-4 upload-btn"
/>
</form>
{message && (
<p className="edit-profile-msg text-center mt-2">{message}</p>
)}
</div>
);
};
EditProfile.propTypes = {
user: PropTypes.object.isRequired,
updateUser: PropTypes.func.isRequired,
updateUserPhoto: PropTypes.func.isRequired,
};
const mapStateToProps = (state) => ({
user: state.auth.user,
});
export default connect(mapStateToProps, { updateUser, updateUserPhoto })(
EditProfile
);
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2014-11-25.
*/
'use strict';
const ErrorType = {
/**
* A forbidden action (for business reasons)
* e.g.:
* - user A hasn't right to do action B
*/
ACCESS: 'ACCESS',
/**
* An invalid action (for business reasons)
* e.g.:
* - delete a node with an unknown node ID
*/
BUSINESS: 'BUSINESS',
/**
* Non-business internal errors that we cannot solve
* e.g.:
* - the SQLite database file is locked
* - cannot listen on port 3000: already used
*/
TECHNICAL: 'TECHNICAL'
};
class LkError extends Error {
/**
* @param {string} type Type of the error
* @param {string} key Key of the error
* @param {string} [message] Human readable description of the error
*/
constructor(type, key, message) {
super((message === null || message === undefined) ? '' : message);
this.type = type;
this.key = key;
if (!LkError.isTechnicalType(type)) {
this.stack = undefined;
}
}
/**
* @type {{ACCESS: string, BUSINESS: string, TECHNICAL: string}}
*/
static get Type() {
return ErrorType;
}
/**
* @param {string} type
* @returns {boolean} true if `type` equals `LkError.Type.ACCESS`
*/
static isAccessType(type) {
return type === LkError.Type.ACCESS;
}
/**
* @param {string} type
* @returns {boolean} true if `type` equals `LkError.Type.BUSINESS`
*/
static isBusinessType(type) {
return type === LkError.Type.BUSINESS;
}
/**
* @param {string} type
* @returns {boolean} true if `type` equals `LkError.Type.TECHNICAL`
*/
static isTechnicalType(type) {
return type === LkError.Type.TECHNICAL;
}
/**
* @returns {boolean} true if `type` equals `LkError.Type.ACCESS`
*/
isAccess() {
return LkError.isAccessType(this.type);
}
/**
* @returns {boolean} true if `type` equals `LkError.Type.BUSINESS`
*/
isBusiness() {
return LkError.isBusinessType(this.type);
}
/**
* @returns {boolean} true if `type` equals `LkError.Type.TECHNICAL`
*/
isTechnical() {
return LkError.isTechnicalType(this.type);
}
}
module.exports = LkError;
|
import { combineReducers } from "redux";
import { reducer as ui } from "./ui/reducer";
import { reducer as properties } from "./properties/reducer";
import { reducer as map } from "./map/reducer";
export default combineReducers({
ui,
properties,
map
}); |
$('#injectJquery').click(function (e) {
e.preventDefault();
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
chrome.tabs.executeScript(null, {file: 'jquery.js'}, function(result){
chrome.tabs.executeScript(null,
{
code: `
javascript:(function() {
function l(u, i) {
var d = document;
if (!d.getElementById(i)) {
var s = d.createElement('script');
s.src = u;
s.id = i;
d.body.appendChild(s);
}
}
l('//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js', 'jquery');
})();
alert('jQuery injected.');
`
}
);
});
});
});
|
module.exports = {
name: 'textBox',
create: 'each',
dependencies: [],
extending: 'widget'
}; |
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
//ES6
var Employee = /*#__PURE__*/function () {
function Employee(name, age, salary) {
_classCallCheck(this, Employee);
this.name = name;
this.age = age;
this.salary = salary;
}
_createClass(Employee, [{
key: "showInfos",
value: function showInfos() {
console.log("İsim:" + this.name + "Yaş:" + this.age + "Maaş" + this.salary);
}
}]);
return Employee;
}();
var emp = new Employee("Ertan", 20, 3000);
emp.showInfos();
console.log(emp); |
const express = require('express'); //express开发web接口
const fs = require('fs');
const bodyPaeser = require('body-parser'); // 引入body-parser post请求要借助body-parser模块
const cookieParser = require('cookie-parser'); //引入模块
const userRouter = require('./user');
const path = require('path');
const multer = require('multer'); //接收图片
// 新建app
const app = express();
// 配合Express使用
const server = require('http').Server(app);
const io = require('socket.io')(server);
const model = require('./model');
const User = model.getModel('user');
const Doctor = model.getModel('doctor');
const Patient = model.getModel('patient');
const upload = multer({dest:'./uploads'}) //定义图片上传时的临时目录
//使用中间件
app.use(cookieParser());
app.use(bodyPaeser.json());
app.use('/user',userRouter);
app.use(function(req,res,next){
if(req.url.startsWith('/user/')
|| req.url.startsWith("/g1/")
|| req.url.startsWith("/d1/")
|| req.url.startsWith('/pv1/')){
return next();
}
if(req.url.startsWith('/static/')||req.url.startsWith('/uploads/')){
const str = '.'+String(req.path)
return res.sendFile(path.resolve(str));
}
if(req.path != "/"){
const str = './dist'+String(req.path)
return res.sendFile(path.resolve(str));
}
return res.sendFile(path.resolve('./dist/index.html'));
})
app.use('/',express.static(path.resolve('static')));
app.post('/pv1/upload',upload.single('upfile'),function(req,res,next){
const imageName = Date.parse(new Date()) + req.file.originalname
//图片存储到服务器的./uploads/目录下
const newFilePath = './uploads/'+ imageName
fs.rename(req.file.path,newFilePath,function(err){
if(err){
console.log(err)
return res.status(500).json('服务器内部错误');
}
return res.status(200).json({code:0,'img':newFilePath});
})
// req.file 是 `avatar` 文件的信息
// req.body 将具有文本域数据,如果存在的话
});
//获取部门分类
app.get('/pv1/department',function(req,res){
const json = require('./static/departCategory.json');
return res.status(200).json(json);
})
app.get('/pv1/saveDoctorData',function(req,res){
const json = require('./static/doctorList.json');
// model.update({},{$set:{node:node}},{multi:true});
for(var i = 0; i<json.length;i++){
const doctorModel = new Doctor(json[i]);
doctorModel.update({},{$set:doctorModel},{multi:true},function(err,doc){
});
// doctorModel.save(function(e,d){
// if(e){
// return res.status(500).json('服务器内部错误');
// }
// console.log(d)
// return res.status(200);
// })
}
})
//获取医生列表
app.get('/pv1/doctorList',function(req,res){
const {secondFacultyId} = req.query;
const json = require('./static/doctorList.json');
for(let i = 0; i<json.length;i++){
if(secondFacultyId == json[i].secondFacultyId){
return res.status(200).json({code:0,'doctorList':json[i].doctorList})
}else{
return res.status(200).json({code:0,'doctorList':[]});
}
}
})
// 获取首页
app.get('/pv1/home',function(req,res){
const {userId} = req.query;
const accessToken = req.header('accessToken')
User.findOne({'_id':userId,accessToken},function(err,doc){
if(err){
return res.status(500).json('服务器内部错误');
}
if(!doc){
return res.status(401).json('会话过期,请重新登录');
}
return res.status(200)
.json({
'banners':[
{'link':'http://www.cnlod.net','img':'/static/banner1.jpg'},
{'link':'http://www.cnlod.net','img':'/static/banner2.jpg'},
{'link':'http://www.cnlod.net','img':'/static/banner3.jpg'}
]
});
})
})
//获取患者信息
app.get('/pv1/patient_profile',function(req,res){
const {userId} = req.query;
Patient.find({userId},function(err,doc){
if(err){
res.status(500).json('服务器内部错误');
}
return res.status(200).json(doc);
})
});
//更新患者信息
app.post('/pv1/updatePatient',function(req,res){
const {userId,_id,relation,name,sex,birthday,phone} = req.body;
Patient.findOneAndUpdate({userId,_id},{relation,name,sex,birthday,phone},function(err,doc){
if(err){
return res.status(500).json('服务器内部错误');
}
if(!doc){
return res.status(400).json('未找到该患者')
}
return res.status(200).json({code:0})
})
})
//添加患者信息
app.post('/pv1/addPatient',function(req,res){
const {userId,relation,name,sex,birthday,phone} = req.body;
const patient = new Patient({userId,relation,name,sex,birthday,phone});
patient.save(function(err,doc){
if(err){
return res.status(500).json('服务器内部错误');
}
return res.status(200).json({code:0});
})
});
//
app.get('/g1/delete',function(req,res){
Patient.remove({},function(err,doc){
if(!err){
User.remove({},function(err,doc){
if(!err){
return res.json({resultCode:0,msg:"删除成功"})
}
})
}
});
})
// 启动app,监听9090
//加入了socket.io之后使用server监听,否则会报跨域的错误
server.listen(9090,function(){
console.log('Node app is running on port:9090');
});
/*
Socket.IO 由两部分组成: websocket框架
一个服务端用于集成 (或挂载) 到 Node.JS HTTP 服务器: socket.io
一个加载到浏览器中的客户端: socket.io-client
io.on 监听事件
io.emit 触发事件
*/
/*
https://segmentfault.com/a/1190000009663833
cookie-parser 在用 express 生成器构建项目时自动安装的,
它的作用就是设置,获取和删除 cookie
var cookieParser = require('cookie-parser'); //引入模块
app.use(cookieParser()); //挂载中间件,可以理解为实例化
res.cookie(name, value [, options]); //创建cookie
var cookies = req.cookies // 获取cookie集合
var value = req.cookies.key // 获取名称为key的cookie的值
res.clearCookie(name [, options]) //删除cookies
上文所写 cookie 的各种操作,都是没有经过签名的。签名可以提高安全性。下面是使用签名生成 cookie 的方法,大同小异,修改上文即可
app.use(cookieParser('ruidoc')); # 需要传一个自定义字符串作为secret
# 创建cookie的options中,必填 signed: true
res.cookie(name, value, {
'signed': true
});
var cookies = req.signedCookies # 获取cookie集合
var value = req.signedCookies.key # 获取名称为key的cookie的值
提示:使用签名时这三处必须一起修改,只改一处是无效的!
*/
/*
body-parser中间件
post请求要借助body-parser模块。使用后,将可以用req.body得到参数
安装:
npm install body-parser
导入:
var bodyPaeser =require('body-parser')
使用中间件:
app.use(bodyParser.urlencoded({ extended: false }));
*/
/*
在package.json中添加 "proxy":"http://localhost:9093",解决跨域问题
*/
/*
node调试工具:nodemon
nodemon 的安装:
npm install -g nodemon
安装完 nodemon 后,就可以用 nodemon 来代替 node 来启动应用:
nodemon [project] [port]
可以运行 debug 模式:
nodemon --debug ./server.js 80
*/ |
const respondSuccess = (res, statusCode, data) => {
res.status(statusCode).json(data);
};
const respondErr = (res, errStatusCode, err) => {
res.status(errStatusCode).json({ errors: err });
};
const handlerError = (err, req, res, next) => {
const message = err.message
res.status(err.statusCode).json({ errors: message });
};
module.exports = { respondSuccess, respondErr, handlerError } |
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import { Container, Title, Content, Button, Left, Right, Body, Icon, Text } from 'native-base';
import Header from './Layout/Header';
import Footer from './Layout/Footer';
import { appStyle } from './theme';
export default class App extends Component {
constructor(props) {
super(props);
this.updateNav = this.updateNav.bind(this);
}
updateNav() {
console.log('nav');
const {routes, route, navigator} = this.props;
navigator.push(routes[1]);
}
render() {
const {route} = this.props;
return (
<Container>
<Header {...this.props} back />
<Content style={appStyle.welcome}>
<Button onPress={this.updateNav} success><Text>Success</Text></Button>
</Content>
<Footer />
</Container>
);
}
}
|
import React, { useEffect, useState } from 'react';
import HeaderNav from '@/components/Layout/header';
import ContentBox from '@/components/Layout/content_box';
import { format } from 'date-fns';
import GraphCard from '@/components/Collocation/AddMonitor/Overview/graph_card';
import {
useGetCollocationStatisticsQuery,
useGetDeviceStatusSummaryQuery,
getRunningQueriesThunk,
} from '@/lib/store/services/collocation';
import { findAllMatchingDevices } from '@/core/utils/matchingDevices';
import moment from 'moment';
import { wrapper } from '@/lib/store';
import Button from '@/components/Button';
import { useDispatch, useSelector } from 'react-redux';
import { isEmpty } from 'underscore';
import {
addOverviewBatch,
removeOverviewBatch,
} from '@/lib/store/services/collocation/collocationDataSlice';
import EmptyState from '@/components/Collocation/Overview/empty_state';
import OverviewSkeleton from '@/components/Collocation/AddMonitor/Skeletion/Overview';
import Toast from '@/components/Toast';
import Layout from '@/components/Layout';
import withAuth from '@/core/utils/protectedRoute';
import Head from 'next/head';
export const getServerSideProps = wrapper.getServerSideProps((store) => async (context) => {
const name = context.params?.name;
if (typeof name === 'string') {
store.dispatch(getDeviceStatusSummary.initiate(name));
}
await Promise.all(store.dispatch(getRunningQueriesThunk()));
return {
props: {},
};
});
const CollocationOverview = () => {
const dispatch = useDispatch();
const [deviceStatistics, setDeviceStatistics] = useState(null);
const [allmatchingDevices, setAllmatchingDevices] = useState(null);
const [collocationPeriods, setCollocationPeriods] = useState(null);
const [activeCollocationPeriod, setActiveCollocationPeriod] = useState(null);
const [isOpen, setIsOpen] = useState(false);
const [openDeviceMenu, setOpenDeviceMenu] = useState(false);
const [skip, setSkip] = useState(true);
const [activeIndex, setActiveIndex] = useState(0);
const [device1, setDevice1] = useState(null);
const [device2, setDevice2] = useState(null);
const [statisticsParams, setStatisticsParams] = useState({});
const [alternativeActiveDevice, setAlternativeActiveDevice] = useState(null);
// get list of selectedCollocateDevices from redux store
const selectedBatch = useSelector((state) => state.collocationData.overviewBatch);
// device summary list
const {
data: deviceStatusSummary,
isSuccess: deviceSummarySuccess,
isLoading: deviceSummaryLoading,
isError: deviceSummaryError,
} = useGetDeviceStatusSummaryQuery();
let deviceStatusSummaryList = deviceStatusSummary ? deviceStatusSummary.data : [];
const {
data: collocationStatistics,
isLoading: collocationStatisticsLoading,
isSuccess: collocationStatisticsSuccess,
isError: collocationStatisticsError,
} = useGetCollocationStatisticsQuery(statisticsParams, { skip: skip });
let collocationStatisticsList = collocationStatistics ? collocationStatistics.data : [];
// matching devices
useEffect(() => {
if (!deviceStatusSummaryList) return;
if (!isEmpty(deviceStatusSummaryList)) {
const { matchingDevicePairs, uniqueDatePairs } =
findAllMatchingDevices(deviceStatusSummaryList);
setAllmatchingDevices(matchingDevicePairs);
setCollocationPeriods(uniqueDatePairs);
setActiveCollocationPeriod(uniqueDatePairs[0]);
setActiveIndex(0);
if (!isEmpty(matchingDevicePairs)) {
if (matchingDevicePairs[0].length > 1) {
dispatch(addOverviewBatch([matchingDevicePairs[0][0], matchingDevicePairs[0][1]]));
} else {
dispatch(addOverviewBatch([matchingDevicePairs[0][0]]));
}
}
}
}, [deviceStatusSummaryList]);
// update device 1 and device 2 when selected batch changes
useEffect(() => {
if (!isEmpty(selectedBatch)) {
if (selectedBatch.length > 1) {
setDevice1(selectedBatch[0].device_name);
setDevice2(selectedBatch[1].device_name);
} else {
setDevice1(selectedBatch[0].device_name);
setDevice2(null);
}
}
}, [selectedBatch]);
useEffect(() => {
const fetchCollocationDeviceStatistics = () => {
if (!isEmpty(selectedBatch)) {
if (selectedBatch.length > 1) {
setStatisticsParams({
devices: [selectedBatch[0].device_name, selectedBatch[1].device_name],
batchId: selectedBatch[0].batch_id,
});
setSkip(false);
} else {
setStatisticsParams({
devices: [selectedBatch[0].device_name],
batchId: selectedBatch[0].batch_id,
});
setSkip(false);
}
}
};
fetchCollocationDeviceStatistics();
}, [selectedBatch]);
useEffect(() => {
if (!isEmpty(collocationStatisticsList)) {
const transformedStatistics = Object.entries(collocationStatisticsList).map(
([deviceName, deviceData]) => ({
deviceName,
s1_pm10_mean: deviceData.s1_pm10_mean,
s1_pm2_5_mean: deviceData.s1_pm2_5_mean,
s2_pm10_mean: deviceData.s2_pm10_mean,
s2_pm2_5_mean: deviceData.s2_pm2_5_mean,
}),
);
setDeviceStatistics(transformedStatistics);
}
}, [collocationStatisticsList]);
return (
<Layout>
<Head>
<title>Collocation | Overview</title>
<meta property='og:title' content='Collocation | Overview' key='Collocation | Overview' />
</Head>
<HeaderNav category={'Collocation'} component={'Overview'} />
{(collocationStatisticsError || deviceSummaryError) && (
<Toast type={'error'} timeout={10000} message={'Server error!'} />
)}
{deviceSummaryLoading || collocationStatisticsLoading ? (
<OverviewSkeleton />
) : collocationStatisticsSuccess || (!collocationStatisticsSuccess && selectedBatch) ? (
<ContentBox>
<div className='grid grid-cols-1 divide-y divide-grey-150 px-6'>
<div className='py-6'>
<div className='flex flex-col md:flex-row justify-between'>
<div>
<h5 className='font-semibold text-lg'>Today</h5>
<p className='text-base font-normal opacity-40'>
{format(new Date(), 'MMM dd, yyyy')}
</p>
</div>
<div className='md:flex md:items-center'>
<span className='text-sm text-black-600 opacity-70 max-w-[96px] md:max-w-full'>
Select a collocation period{' '}
</span>
<div className='relative'>
<Button
className='w-auto h-10 bg-blue-200 rounded-lg text-base font-semibold text-purple-700 md:ml-2'
onClick={() => setIsOpen(!isOpen)}
>
<span>
{!isEmpty(activeCollocationPeriod) &&
`${moment(activeCollocationPeriod.start_date).format(
'MMM DD, yyyy',
)} - ${moment(activeCollocationPeriod.end_date).format('MMM DD, yyyy')}`}
</span>
</Button>
{isOpen && (
<ul
tabIndex={0}
className='absolute z-30 mt-1 ml-6 w-auto border border-gray-200 max-h-60 overflow-y-auto text-sm p-2 shadow bg-base-100 rounded-md'
>
{collocationPeriods.map((period, index) => (
<li
role='button'
key={index}
className='text-sm text-grey leading-5 p-2 hover:bg-gray-200 rounded'
onClick={() => {
if (allmatchingDevices[index].length > 1) {
const firstBatchPair = [
allmatchingDevices[index][0],
allmatchingDevices[index][1],
];
dispatch(removeOverviewBatch());
dispatch(addOverviewBatch(firstBatchPair));
} else {
dispatch(removeOverviewBatch());
dispatch(addOverviewBatch(allmatchingDevices[index]));
}
// console.log(allmatchingDevices[index]);
setActiveCollocationPeriod(period);
setActiveIndex(index);
setIsOpen(false);
}}
>
<a>{`${moment(period.start_date).format('MMM DD')} - ${moment(
period.end_date,
).format('MMM DD')}`}</a>
</li>
))}
</ul>
)}
</div>
</div>
</div>
</div>
<div
className={`grid grid-cols-1 ${
selectedBatch.length === 2 && 'lg:grid-cols-2'
} lg:divide-x divide-grey-150`}
>
{!isEmpty(selectedBatch) &&
selectedBatch.length > 1 &&
!isEmpty(deviceStatistics) &&
deviceStatistics.length >= 1 ? (
<>
<GraphCard
data={[deviceStatistics[0]]}
batch={allmatchingDevices[activeIndex]}
device={selectedBatch[0]}
selectedBatch={selectedBatch}
/>
<GraphCard
data={[deviceStatistics[1]]}
secondGraph={true}
batch={allmatchingDevices[activeIndex]}
device={selectedBatch[1]}
selectedBatch={selectedBatch}
/>
</>
) : (
!isEmpty(selectedBatch) &&
!isEmpty(deviceStatistics) && (
<>
<GraphCard
data={[deviceStatistics[0]]}
secondGraph={true}
batch={allmatchingDevices[activeIndex]}
device={selectedBatch[0]}
selectedBatch={selectedBatch}
/>
</>
)
)}
{collocationStatisticsSuccess && isEmpty(deviceStatistics) && (
<div className='flex flex-col items-center justify-center col-span-2 p-8'>
<p className='text-base font-normal opacity-40 mt-4'>
No data available for the current devices. Compare other devices or collocation
period
</p>
</div>
)}
</div>
<div className='divide-y pt-20'>
<div className='flex flex-row items-center justify-between p-6 md:px-12'>
<span className='font-normal text-base opacity-60'>Monitor name</span>
<span className='font-normal text-base opacity-60 text-left'>End date</span>
</div>
{device1 && (
<div className='flex flex-row items-center justify-between p-6 md:px-12'>
<span className='font-semibold text-base flex justify-between items-center uppercase'>
{device1}
</span>
<span className='text-xl font-normal'>{format(new Date(), 'MMM dd, yyyy')}</span>
</div>
)}
{device2 && (
<div className='flex flex-row items-center justify-between p-6 md:px-12'>
<span className='font-semibold text-base flex justify-between items-center uppercase'>
{device2}
</span>
<span className='text-xl font-normal'>{format(new Date(), 'MMM dd, yyyy')}</span>
</div>
)}
</div>
</div>
</ContentBox>
) : (
<EmptyState />
)}
</Layout>
);
};
export default CollocationOverview;
|
/****************************************************
* Copyright © Legwork Studio. All Rights Reserved. *
* Updated by: Matt Wiggins and Jos, 13-Jun-2011 *
* *
* Hidden, magical things are at the top. *
****************************************************
/ */
// scroll past the media area on sub pages
// (as quick as possible)
if(window.location.href.indexOf('#') === -1) { // don't scroll if it's a hash
(function() {
var scrollTop;
if ('pageXOffset' in window) { // all browsers, except IE before version 9
scrollTop = window.pageYOffset;
}
else { // Internet Explorer before version 9
scrollTop = document.documentElement.scrollTop;
}
try {
if((scrollTop > 0) === false) {
window.scrollTo(0, 550);
setTimeout(arguments.callee, 1); // recurse until scrolled
}
} catch(e) {
setTimeout(arguments.callee, 1); // recurse if document.body fails
}
})();
}
|
import HttpStatus from 'http-status-codes';
import KoreanMedicine from '../models/korean_medicine.model';
import formidable from 'formidable';
import fs from 'fs';
import date from 'date-and-time';
/**
* Add New Korean Medicine
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
function AddKoreanMedicine(req, res) {
KoreanMedicine.forge({
Title : req.body.title, Content : req.body.content
}, {hasTimestamps: true}).save()
.then(() => res.json({
error : false,
message : "Save Korean Succed"
})
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
}
/**
* Get Korean Medicine by id
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
export function GetKoreanById(req, res) {
KoreanMedicine.forge()
.fetch()
.then(korean => {
if (!korean) {
res.status(HttpStatus.NOT_FOUND).json({
error: true, korean: {}
});
}
else {
res.json({
error: false,
korean: korean.toJSON()
});
}
})
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
}
/**
* Modify Korean Medicine
*
* @param {object} req
* @param {object} res
* @returns {*}
*/
export function ModifyKorean(req, res) {
KoreanMedicine.forge({id: req.body.id})
.fetch({require: true})
.then(function(korean) {
if (korean != null)
korean.save({
Title : req.body.title || korean.get('Title'),
Content : req.body.content || korean.get('Content')
})
.then(() => res.json({
error : false,
message : "Save Korean Succed"
})
)
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: true,
message: err.message
})
)
else
AddKoreanMedicine(req, res);
})
.catch(err => res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
error: err
})
);
}
|
(function() {
'use strict';
angular.module('app.controllers')
.controller('NotesCtrl',
function($scope,
session,
$stateParams,
notes,
$rootScope) {
/**
* Init function
* @return
*/
$scope.init = function() {
$rootScope.$emit('inChildState'); // indicate to the nav ctrl that we are in child state to display back button
$scope.sessionId = $stateParams.sessionId;
$scope.notes = notes;
$scope.session = session;
}
$scope.init();
}
);
})();
|
class Enemy {
constructor(playerLevel) {
this.level = playerLevel;
this.type = enemyList[Math.floor(Math.random() * enemyList.length)];
this.maxPossibleHealth = enemyStartingMaxHealth + 3.5 * (this.level - 1);
this.maxHealth = Math.ceil(Math.random() * this.maxPossibleHealth);
this.health = this.maxHealth;
this.attack = enemyStartingMaxAttack + 1.006 * this.level * (this.level - 1);
appendToDisplay(`<bigger-letter>A</bigger-letter> <bad-guy>${this.type}</bad-guy> has appeared!`, true);
}
get name() { return this.type; }
get maxHP() {return this.maxHealth; }
get hp() { return this.health; }
power() { return Math.ceil(Math.random() * this.attack); }
takeDamage(damage) {
// Correct health underflow when taking damage.
if((this.health -= damage) < 0) this.health = 0;
appendToDisplay(`You strike the <bad-guy>${this.type}</bad-guy> for <dmg-dealt>${damage}</dmg-dealt> damage.`);
}
} |
#!/usr/bin/env node
/* begin copyright text
*
* Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved.
*
* end copyright text
*/
/* jshint esversion: 6 */
'use strict';
var startAt = process.hrtime();
/**
* Process event handlers
*/
process.on('SIGINT', function() {
console.log('Caught SIGINT');
closeHandlers();
process.exit(2);
});
process.on('SIGTERM', function() {
console.log('Caught SIGTERM');
closeHandlers();
process.exit(15);
});
process.on('exit', function(code) {
debug('Process exiting with code:', code);
console.log('Process exiting with code:', code);
});
// Please don't remove the below line - requested by devops
console.error("This message should appear in the logs if stderr stream is captured");
/**
* Module dependencies.
*/
var app = require('./app');
var debugModule = require('debug');
var debug = debugModule('vxs');
var fs = require('fs');
var fse = require('fs-extra');
var Q = require("q");
var utils = require('./utils.js');
var RequestHelper = require('./requestHelper.js');
var chalk = require('chalk');
var acl = require("./acl.js");
var ProxyManager = require('./routes/admin/proxies/proxyManager.js');
var users = require("./routes/admin/users/users.js");
var namespace = require("./lib/namespace.js");
var EventNotifier = require('./analytics/eventNotifier.js');
var billable = require('./analytics/billable.js');
var RepViewedEvent = require('./analytics/repViewedEvent.js');
var routerInfo= require("./lib/apidoc/router-info.js");
var UsageMonitor = require('./routes/handlers/usageMonitor.js');
var userRegistration = require('./routes/handlers/userRegistration.js');
var port = app.settings.port;
app.set('_requestHelper', new RequestHelper(app.settings));
var performanceMetrics = require('./routes/handlers/performanceMetrics.js');
console.log("Starting '%s' at %s", __filename, new Date().toISOString());
console.log("Current directory: " + process.cwd());
console.log("");
let startupDebug = process.env.STARTUP_DEBUG;
let userStartupDebug = process.env.DEBUG;
if (startupDebug || !userStartupDebug) {
startupDebug = startupDebug ? startupDebug : 'vx*';
debugModule.enable(startupDebug);
console.log("Setting DEBUG value:", startupDebug);
}
function assertDefaultDomainNameSettings() {
var value = app.get("defaultDomainName");
if (value && value.error) {
value.error.forEach(function(x) { console.error(x); });
process.exit(1);
}
}
assertDefaultDomainNameSettings();
/**
* Create the vault directories if it does not exists.
*/
Q.all([createStoreIfRequired('projects', app.settings.projects.storePath),
createStoreIfRequired('reps', app.settings.reps.storePath),
createStoreIfRequired('upgrade', app.settings.upgrade.storePath)])
.tap(utils.debugCallback(debug,"Create stores resolved"))
.then(function(storeInfos){
//Cache the store locations
storeInfos.forEach (function(storeInfo) {
app.get(storeInfo.configKey)['_store'] = storeInfo.path;
console.log("Store for " + storeInfo.configKey + ": " + app.get(storeInfo.configKey)['_store']);
});
/**
* Initialize the database handler.
*/
var dbHandler = app.get('_dbHandler');
return dbHandler.init();
})
.tap(utils.debugCallback(debug,"Database handler init resolved."))
.then(app.init)
.then(app.initRouter)
.then(_ => require('./lib/configVerifier')(app))
.tap(function(){
console.log("Initializing billable event");
const gracePeriod = app.get("billingGracePeriod");
billable.init(app.get('_dbHandler'), gracePeriod);
RepViewedEvent.init(app.get('_dbHandler'), gracePeriod);
if (!app.get("disableComplianceAPI")){
UsageMonitor.init(app.get('_dbHandler'), gracePeriod, app.settings.billingData);
userRegistration.init(app.get('_dbHandler'));
}
})
.then(function() {
if (!app.settings.routingConfiguration.gds) {
// Init the proxy manager
console.log("Loading proxy configurations ");
return ProxyManager.init(app.settings);
} else { return false; }
})
.tap(utils.debugCallback(debug,"load proxy configuration resolved."))
.then(function(){
return (app.settings.routingConfiguration.gds) ? false : acl.loadACRules();
})
.tap(utils.debugCallback(debug,"load Access Control Rules resolved."))
.then(function() { require("./routes/admin/tenants.js").init(app.settings); })
.then(namespace.init(app))
.tap(utils.debugCallback(debug,"namespace init resolved"))
.tap(function() {
/**
* Initialize the metrics handler.
*/
console.log("Initializing metrics handler ");
performanceMetrics.init(app);
})
.then(function(){
/**
* Initialize users handler
*/
console.log("Initializing users handler ");
return (app.get("enableAclManagement") && app.settings.authentication.type === 'local') ? (function(){
users.init(app.settings);
var localUsers = __dirname.endsWith('src') ? '../test/digest/users.json' : './digest/users.json';
return users.loadUsers(require(localUsers));}()) : Q(1);
})
.tap(utils.debugCallback(debug,"load users handler resolved."))
.tap(function() {
/**
* Initialize the dns-sd-client handler.
*/
console.log("Initializing DNS-SD handler");
var dnssdHandler = require("./dns-sd-client.js").newInstance(app.settings);
app.set('_dnssdHandler', dnssdHandler);
})
.tap(utils.debugCallback(debug,"DNS-SD handler init resolved."))
.then(function(){
EventNotifier.init(app.settings);
return require('./routes/access/rolesManager.js').init(app.settings);
})
.tap(requireListeners)
.then(function() {return require('./upgrade/upgradeManager.js')(app.settings);})
.tap(utils.debugCallback(debug,"upgrade resolved"))
.then(processAndLogRoutes)
.then(function() {
if (startupDebug) {
debugModule.enable(userStartupDebug);
console.log("Setting DEBUG value:", userStartupDebug);
}
var debugs = debugModule.instances;
if (debugs) {
var debugAlways = debug.enabled ? debug : console.log;
debugAlways("Enabled debug namespaces: " + debugs.filter(x => x.enabled).map(x => x.namespace).sort().join(" "));
debugAlways("Disabled debug namespaces: " + debugs.filter(x => !x.enabled).map(x => x.namespace).sort().join(" "));
}
console.log("Starting server now ..."); // Please don't change this message. TWX-ExperienceService extension integration tests depend on it.
/**
* Create HTTPS server.
*/
var server;
var serverType;
if (app.settings.nossl) {
serverType = "HTTP";
server = require('http').createServer(app);
} else {
let httpsPackage;
if (app.settings.nohttp2) {
serverType = "HTTPS";
httpsPackage = require('https');
} else {
serverType = "HTTP2";
httpsPackage = require('spdy');
}
try {
server = httpsPackage.createServer(utils.loadHTTPSOptions(app.settings), app);
} catch(err){
throw utils.wrapIfPassphraseError(err);
}
}
/**
* Listen on provided port, on all network interfaces.
*/
app.settings.defaultRequestTimeout = server.timeout;
server.listen(port);
server.on('error', onError);
server.on('listening', function() {
if (namespace.isEnabled()) {
if (app.settings.defaultDomainName) {
app.settings.defaultDomainName = "";
console.warn('Ignoring configuration defaultDomainName in multi-tenant mode');
}
} else {
app.settings.defaultDomainName = utils.validateDefaultDomainName(app.settings.defaultDomainName, app.settings.nodn);
}
if (app.settings.nodn && !namespace.isEnabled()) {
console.log(chalk.red.bgYellow.bold("WARNING >>> Server is using overriden " +
app.settings.defaultDomainName + " as the defaultDomainName"));
} else if (app.settings.defaultDomainName) {
console.log("Server is using " + app.settings.defaultDomainName + " as the defaultDomainName");
}
if (app.settings.nossl) {
console.log(chalk.red.bgYellow.bold("WARNING >>> Server is running in INSECURE mode"));
} else {
console.log("Server is running in SECURE mode");
}
if (String(process.env.NODE_TLS_REJECT_UNAUTHORIZED) === '0') {
console.log(chalk.red.bgYellow.bold("WARNING >>> Server is set to ignore certificate errors"));
}
if (app.settings.routingConfiguration.all) {
console.log("Server is using the 'all' routingMode");
} else {
console.log(chalk.red.bgYellow.bold("WARNING >>> Server is using the '" +
app.settings.routingMode + "' routingMode"));
}
['-nossl', '-nodn', '-dev'].forEach(function(cliOption) {
if (process.argv.indexOf(cliOption) > -1) {
console.log(chalk.red.bgYellow.bold("WARNING >>> '%s' command-line argument " +
"will be deprecated soon. Use '%s' instead."), cliOption, cliOption.replace('-', '--'));
}
});
console.log((namespace.isEnabled() ? chalk.red.bgYellow("Namespaces Enabled") : chalk.green.bgYellow.bold("Namespaces Disabled")));
console.log("");
console.log("Server startup completed in " + millisecondsSince(startAt) + " ms");
var addr = server.address();
var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
console.log(serverType + ' Listening on ' + bind);
});
// add the websocket proxies
ProxyManager.addWebsocketProxies(server);
// Expose the httpServer metrics
performanceMetrics.setHttpServer(server);
})
.tap(utils.debugCallback(debug,"Server init resolved."))
.then(function() {
var mdns = null;
try { mdns = require('./mdns.js'); } catch(err) { console.warn('Multicast advertising disabled: %s', err); }
if (mdns) {
console.log('Starting multicast advertising now ...');
/**
* Begin advertising availability using mDNS
*/
app.set('_mdnsResponder', mdns.newInstance(app.settings));
app.settings._mdnsResponder.start();
}
})
.tap(utils.debugCallback(debug,"mDNS advertising resolved."))
.then(function(){
if (app.settings.startSimulator === true) {
try {
var simulator = require('./tools/simulator/simulator');
simulator.start();
}
catch(err) {
console.warn('Error starting simulator: %s', err);
}
}
})
.catch(error => {onError(error); throw error;})
.done();
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
closeHandlers();
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Create the store if it does not exists.
*/
function createStoreIfRequired(configKey, storePath, callback) {
var deferred = Q.defer();
debug("Ensure store directory: " + storePath);
fse.ensureDir(storePath, function(err) {
if (err) {
deferred.reject(err);
} else {
if (debug.enabled) { debug("Count of files or directories in %s: %d", storePath, fs.readdirSync(storePath).length); }
deferred.resolve({configKey: configKey, path: storePath});
}
});
return deferred.promise.nodeify(callback);
}
/**
* Close handlers
*/
function closeHandlers() {
performanceMetrics.stop();
if (app.settings._dbHandler) {
app.settings._dbHandler.close();
}
if (app.settings._mdnsResponder) {
app.settings._mdnsResponder.stop();
}
}
/**
* Logs all supported routes
*/
function processAndLogRoutes() {
var info = routerInfo(app);
if (debug.enabled) {
// log routes
var report = info.toLogString();
debug("## Routes report begins:\n" + report);
debug("## Routes report ends");
}
}
function millisecondsSince(startAt) {
var endAt = process.hrtime();
var ms = (endAt[0] - startAt[0]) * 1e3 + (endAt[1] - startAt[1]) * 1e-6;
return ms.toFixed(0);
}
function requireListeners() {
[
'./routes/handlers/target-generation/eventHandler.js',
'./routes/access/deleteAppListener.js',
'./routes/access/uploadArchiveListener.js'
].forEach(listener => {
const listenerObj = require(listener);
if (listenerObj.init) { listenerObj.init(app.settings); }
});
}
|
console.log('component has loaded');
window.onload = function() {
console.log('all files that this page needs have been loaded');
var clickPicture = {
imgElement: null,
initialize: function(domSelector) {
console.log('initializing component');
this.imgElement = document.createElement('img'); //<img />
this.imgElement.id = "image";
domSelector.appendChild(this.imgElement);
},
render: function(imageSrc) {
this.imgElement.src = imageSrc; // <img src='imageSrc'>
},
nextImage: function(anotherImage) {
this.imgElement.addEventListener('click', function() {
image = document.getElementById("image");
image.src='http://www.janchristianbernabe.com/wp-content/uploads/2013/02/2-18-13.jpg';
})
}
};
var content = document.getElementById('content');
console.log(content);
content.innerHTML = '';
var contentImage = 'http://www.janchristianbernabe.com/wp-content/uploads/2013/01/1-11-13.jpg';
var anotherImage = '';
clickPicture.initialize(content);
clickPicture.render(contentImage);
clickPicture.nextImage(anotherImage);
//
// // basic selectors
// // declare a selector named container
// // access that container via document.getElementById('name-of'id)
// var container = document.getElementById('container');
// console.log(container);
// var monsters = ['Wreck-it Ralph', 'The giraffe from Lion King SNES', 'Ganon'];
//
// for (var baddie in monsters) {
// // create a new dom element using document.createElement('name-of-tag');
// var li = document.createElement('li');
// console.log(li);
// // access and assign a property to my dom element
// li.innerHTML = monsters[baddie];
// // append it to a container using selector.appendChild(domElement)
// container.appendChild(li);
// }
//
// // now, we need to create an image!
// var kittenImage = document.createElement('img');
// // alt text (alt) - ADA compliancy text for the blind
// kittenImage.alt = 'A cute random kitten';
// kittenImage.id = 'kitten';
// // src = image source
// kittenImage.src = 'http://www.wikihow.com/images/5/51/Buttercup-color-Step-7.jpg';
// // append my element as a child to a selector
// container.appendChild(kittenImage);
//
// // modify the cuteness level of my kitten
// // create a new selector by querying the DOM
// // notice the use of CSS style selectors!
// // makes things easy to remember
// var kitten = document.querySelector('#kitten');
// kitten.src = 'http://www.wikihow.com/images/5/51/Buttercup-color-Step-7.jpg';
//
// var listItemsArray = document.getElementsByTagName('li');
// console.log(listItemsArray);
//
// for (var li in listItemsArray) {
// listItemsArray[li].innerHTML = 'We are the champions (my friend)';
// }
//
// var status = document.getElementById('status-message');
// var btn = document.getElementById('addPoint');
// // var btn = document.querySelector('#addPoint');
//
// // initialize our UI component
// user.initialize(status);
// // selector.addEventListener(eventType, function());
// btn.addEventListener('click', function() {
// user.updateScoreByOnePoint();
// });
//
// // bind events to a DOM element
// // var body = document.getElementsByTagName('body')[0];
// // // we need to add a listener for events to an element
// // // mouse event
// // body.addEventListener('click', function(event) {
// // console.log(event);
// // console.log('ow, y u click me bro?');
// // });
// // // touch events
// // body.addEventListener('touchstart', function(event) {
// // // console.log(event);
// // // touchstart
// // // touchmove
// // // touchend
// // console.log('yo yo dude y u pokin me? wtf man');
// // });
// // // keyboard events
// // body.addEventListener('keyup', function(event) {
// // // look for specific keys to be pressed
// // if (event.keyCode == 13) {
// // console.log('y u press enter so much yo?');
// // }
// // console.log(event.keyCode);
// // });
//
// } // end window.onload
//
//
// // create a user interface component!
// // the goal here is to create an Object
// // that can update itself
// // and visually show that if needed
//
// // ex #1: user component
// var user = {
// name: null,
// score: 0,
// domElement: null,
// // elementToAppendTo: document.selector for an indivual element
// initialize: function(elementToAppendTo) {
// if (this.name == null) {
// this.name = prompt('What is your name?');
// }
// this.domElement = document.createElement('div');
// elementToAppendTo.appendChild(this.domElement);
// console.log('initialize: complete');
// },
// // innerHTM: valid html to place in our domElement
// render: function(innerHTML) {
// if (typeof(innerHTML) == 'string') {
// this.domElement.innerHTML = innerHTML;
// }
// },
// buildPlayerStatusString: function() {
// return this.name + ': ' + this.score;
// },
// getName: function() {
// return this.name;
// },
// saveName: function(newName) {
// if (typeof(newName) == 'string' && newName.length > 0) {
// this.name = newName;
// } else {
// alert('You entered an incorrect or empty name');
// }
// },
// getScore: function() {
// return this.score;
// },
// updateScoreByOnePoint: function() {
// this.score = this.score + 1;
// var status = this.buildPlayerStatusString();
// this.render(status);
// return this.score;
// }
// };
};
|
export default {
items: [
{
name: 'Product',
url: '/products',
icon: 'icon-drop',
},
{
name: 'Image',
url: '/theme/typography',
icon: 'icon-pencil',
}
],
};
|
class GraficoPiramide {
constructor(element_id, data) {
this.element_id = element_id;
this.data = data;
this.width = 500;
this.height = 250;
this.margin = {top: 20, right: 10, bottom: 20, left: 10, middle: 20};
this.axis_font_size = '0.7em';
this.leftBarColor = "#2c6bb4";
this.rightBarColor = "#f37120";
}
criar(){
let element_id = this.element_id;
let self = this;
let width = this.width - this.margin.left - this.margin.right;
let height = this.height - this.margin.top - this.margin.bottom;
let svg = d3.select('#'+this.element_id);
let sectorWidth = (width / 2) - this.margin.middle;
let leftBegin = sectorWidth - this.margin.left;
let rightBegin = width - this.margin.right - sectorWidth;
let pyramid = svg
.append("g")
.attr("transform", "translate("+self.margin.left+","+self.margin.top+")");
let totalPopulation = d3.sum(data, function(d) {
return d.male + d.female;
});
let percentage = function(d) {
return d / totalPopulation;
};
// find the maximum data value for whole dataset
// and rounds up to nearest 5%
// since this will be shared by both of the x-axes
var maxValue = Math.ceil(Math.max(
d3.max(self.data, function(d) {
return percentage(d.male);
}),
d3.max(self.data, function(d) {
return percentage(d.female);
})
)/0.05)*0.05;
// SET UP SCALES
// the xScale goes from 0 to the width of a region
// it will be reversed for the left x-axis
var xScale = d3.scaleLinear()
.domain([0, maxValue])
.range([0, (sectorWidth-self.margin.middle)])
.nice();
var xScaleLeft = d3.scaleLinear()
.domain([0, maxValue])
.range([sectorWidth, 0]);
var xScaleRight = d3.scaleLinear()
.domain([0, maxValue])
.range([0, sectorWidth]);
var yScale = d3.scaleBand()
.domain(data.map(function(d) {
return d.age;
}))
.range([height, 0], 0.1);
// SET UP AXES
var yAxisLeft = d3.axisRight()
.scale(yScale)
.tickSize(4, 0)
.tickPadding(self.margin.middle - 4);
var yAxisRight = d3.axisLeft()
.scale(yScale)
.tickSize(4, 0)
.tickFormat('');
var xAxisRight = d3.axisBottom()
.scale(xScale)
.ticks(5)
.tickFormat(d3.format('.0%'));
var xAxisLeft = d3.axisBottom()
// REVERSE THE X-AXIS SCALE ON THE LEFT SIDE BY REVERSING THE RANGE
.scale(xScale.copy().range([leftBegin, 0]))
.ticks(5)
.tickFormat(d3.format('.0%'));
// DRAW AXES
pyramid.append('g')
.attr("transform", "translate("+leftBegin+",0)")
.call(yAxisLeft)
.selectAll('text')
.style('text-anchor', 'middle');
pyramid.append('g')
.attr("transform", "translate("+rightBegin+",0)")
.call(yAxisRight);
pyramid.append('g')
.attr("transform", "translate(0,"+height+")")
.call(xAxisLeft);
pyramid.append('g')
.attr("transform", "translate("+rightBegin+","+height+")")
.call(xAxisRight);
// MAKE GROUPS FOR EACH SIDE OF CHART
// scale(-1,1) is used to reverse the left side so the bars grow left instead of right
var leftBarGroup = pyramid.append('g')
.attr("transform", "translate("+leftBegin+",0) scale(-1,1)");
var rightBarGroup = pyramid.append('g')
.attr("transform", "translate("+rightBegin+",0)");
let barHeight = (yScale.range()[0] / data.length) - self.margin.middle / 2;
leftBarGroup.selectAll('.bar.left')
.data(data)
.enter().append('rect')
.attr('x', 0)
.attr('fill', self.leftBarColor)
.attr('y', function(d) {
return yScale(d.age) + self.margin.middle / 4;
})
.attr('width', function(d) {
return xScale(percentage(d.male));
})
.attr('height', barHeight);
rightBarGroup.selectAll('.bar.right')
.data(data)
.enter()
.append('rect')
.attr('fill', self.rightBarColor)
.attr('x', 1)
.attr('y', function(d) {
return yScale(d.age) + self.margin.middle / 4;
})
.attr('width', function(d) {
return xScale(percentage(d.female));
})
.attr('height', barHeight);
//-- TEXTO DAS BARRAS À DIREITA -----------------------------------------------------------
rightBarGroup.selectAll('.bar.right')
.data(data)
.enter()
.append('text')
.text(function(d) {
let value = percentage(d.female)*100;
value = value.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 0})+'%';
return value;
})
.style("font-size", self.axis_font_size)
.attr('fill', self.rightBarColor)
.attr('x', function(d){
return xScale(percentage(d.female));
})
.attr('y', function(d) {
return yScale(d.age) + self.margin.middle / 4 + barHeight;
})
.attr('dy', '-0.3em')
.attr('dx', '0.3em');
//-- TEXTO DAS BARRAS À ESQUERDA -----------------------------------------------
var gLeftText = pyramid.append('g')
.attr("transform", "translate("+leftBegin+",0)");
gLeftText.selectAll('.bar.right')
.data(data)
.enter()
.append('text')
.text(function(d) {
let value = percentage(d.male)*100;
value = value.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 0})+'%';
return value;
})
.style("text-anchor", "end")
.style("font-size", self.axis_font_size)
.attr('fill', self.leftBarColor)
.attr('x', function(d){
let value = xScale(percentage(d.male))*-1;
return value;
})
.attr('y', function(d) {
return yScale(d.age) + self.margin.middle / 4 + barHeight;
})
.attr('dy', '-0.3em')
.attr('dx', '-0.3em');
}
} |
const routes = [
[-20, 15],
[-14, -5],
[-18, -13],
[-5, -3],
];
const solution = (routes) => {
let answer = 0;
routes.sort((a, b) => {
return a[1] - b[1];
});
let camera = -30001;
for (let i = 0; i < routes.length; i++) {
if (camera < routes[i][0]) {
answer++;
camera = routes[i][1];
}
}
return answer;
};
console.log(solution(routes));
|
const WebSocket = require("ws");
const wss = new WebSocket.Server({port: 80});
wss.on('connection', function connection(ws, req) {
console.log(wss.clients.size);
ws.on('message', function incoming(message) {
console.log('received: %s', message);
wss.clients.forEach(function (client) {
if (client == ws) {
return;
}
client.send(message);
})
});
wss.clients.forEach(function (client) {
client.send("A new user has joined");
})
});
|
// DB 모델을 작성한다.
// Video 자체를 DB에 저장하진 않을 것이다. 즉, byte를 저장하는 것이 아니라 video의 link를 저장한다.
import mongoose from "mongoose";
const VideoSchema = new mongoose.Schema({
fileUrl: {
type: String,
required: "File URL is required", // url이 없으면 오류메시지 출력
},
title: {
type: String,
required: "Title is required",
},
description: String,
views: {
type: Number,
default: 0, // 비디오를 처음 생성하면 views를 0으로..
},
createdAt: {
type: Date,
default: Date.now, // 현재 날짜를 반환하는 function
},
// video와 comment를 연결하는 방법 #1
comments: [
{
type: mongoose.Schema.Types.ObjectId, // 그 다음 어느 model에서 온 id인지 알려줘야 한다.
ref: "Comment",
},
],
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
});
// 이제 이 스키마를 이용하여 model을 만들어준다.
// 모델의 이름은 "Video"
const model = mongoose.model("Video", VideoSchema);
export default model;
// 모델이 만들어짐을 알리기 위해 init.js에 import해준다.
|
'use strict'
const _ = require('lodash')
const Helpers = use('Helpers')
const Config = use('Config')
const Drive = use('Drive')
const Post = use('App/Models/Post')
const Option = use('App/Models/Option')
const { HttpException } = require('@adonisjs/generic-exceptions')
const BaseController = require('./ResourceController')
module.exports = class PostController extends BaseController {
async recommends(ctx) {
const { params, query } = ctx
const recommend = await Option.get('recommend')
const ids = recommend[params.name]
let whereId = ids
if (_.isArray(ids)) {
whereId = { in: ids }
}
const finder = Post.query(query).listFields().where({
_id: whereId
}).with(['course.categories', 'user'])
if (_.isArray(ids)) {
const posts = await finder.fetch()
for(let post of posts.rows) {
await post.fetchAppends(ctx, ['is_buy'])
}
return posts
} else {
const post = await finder.first()
await post.fetchAppends(ctx, ['is_buy'])
return post
}
}
} |
/*菜单*/
define([
"dojo/_base/declare",
"echo/utils/EventBus",
"dojo/query",
"dojo/NodeList-dom",
"dojo/domReady!"
],
function(declare, EventBus, query) {
return declare("menu", null, {
constructor: function(config) {
this.config = config;
this.init();
},
startup: function() {
this.bindEvent();
},
init: function() {
this.startup();
},
bindEvent: function() {
/*添加菜单点击事件*/
//菜单样式
this.runChlidMenuMoudle();
//放大
query('#fangda').on('click', (function() {
this.runMoudle('ZOOM_IN_OR_ZOOM_OUT_STARTUP','fangda')
}).bind(this));
//缩小
query('#suoxiao').on('click', (function() {
this.runMoudle('ZOOM_IN_OR_ZOOM_OUT_STARTUP','suoxiao')
}).bind(this));
// 测距
query('#distance').on('click', (function() {
this.runMoudle('DISTANCE_STARTUP')
}).bind(this));
//测面
query('#area').on('click', (function() {
this.runMoudle('AREA_STARTUP')
}).bind(this));
//测绘
query('#tagging').on('click', (function() {
this.runMoudle('TAGGING_STARTUP')
}).bind(this));
$("#attrQueryBtn").on("click", (function(event){
this.runMoudle("ATTRMANAGER_WIDGET_START_UP");
}).bind(this));
$('#commonTool').on('click',function(){
$('#toolMap').show();
});
if($('#USERNAME').val() !=''){
$('#username').show();
$('#login').hide();
$('#username').html($('#USERNAME').val()+"<a class='user-logout' title='注销' href='./logOut'></a>");
}
},
//打开模块通用方法
runMoudle: function(modulesStartup) {
EventBus.emit('All_WIDGETS_CLOSE');
EventBus.emit(modulesStartup);
},
//打开右菜单工具条并设置选中状态样式方法
runRightMenuMoudle: function(modulesStartup,menuId) {
if(menuId != "#rightMenuClean"){//如果功能为清除,则不添加点击样式
$(menuId).addClass('draw-active');//添加点击后样式
}
$(menuId).siblings().each(function(){//删除其同级节点的点击状态样式
$(this).removeClass('draw-active');
});
EventBus.emit('All_WIDGETS_CLOSE');
if(modulesStartup){
EventBus.emit(modulesStartup);
}
},
// 二级菜单
runChlidMenuMoudle:function(){
$('#ulMenuTop li').on('click',function(){
$(this).addClass("nav-active").siblings().removeClass('nav-active')
});
query('#toolMap ul li').on('click',function(){
$(this).addClass('tool-active').siblings().removeClass('tool-active');
})
},
//打开右菜单工具条并设置选中状态样式,打开子菜单
runTopMenuMoudle: function(modulesStartup,menuId) {
//如果子菜单存在则显示子菜单背景,否则此处不做处理,直接打开模块
query("#ulTopMenu>li").removeClass("nav-active");
query(menuId).addClass("nav-active");
EventBus.emit('All_WIDGETS_CLOSE');
if(modulesStartup){
EventBus.emit(modulesStartup);
}
}
});
});
|
import { Dimensions } from 'react-native';
import { UIConstant } from '../services/UIKit/UIKit';
import { SHOW_CONTROLLER, NAVIGATION_MENU_CONTROLLER, SET_BACKGROUND_PRESET, SET_SCREEN_WIDTH, SET_MOBILE } from '../actions/ActionTypes';
const initialState = {
controllerToShow: null,
backgroundPresetName: '',
screenWidth: 0,
mobile: Dimensions.get('window').width < UIConstant.elasticWidthBroad(),
menuItems: [],
navigation: null,
};
const controllerReducer = (state = initialState, action) => {
switch (action.type) {
case NAVIGATION_MENU_CONTROLLER:
return {
...state,
menuItems: action.menuItems,
navigation: action.navigation,
};
case SHOW_CONTROLLER:
return {
...state,
controllerToShow: action.controllerToShow,
};
case SET_BACKGROUND_PRESET:
return {
...state,
backgroundPresetName: action.backgroundPresetName,
};
case SET_SCREEN_WIDTH:
return {
...state,
screenWidth: action.screenWidth,
};
case SET_MOBILE:
return {
...state,
mobile: action.mobile,
};
default:
return state;
}
};
export default controllerReducer;
|
$(document).ready(function () {
// Initialize Firebase
var config = {
apiKey: "AIzaSyDg-e09AnkOSzUQ2fBUfHDnOZ4qoiiN_Dg",
authDomain: "train-scheduler-dbf7e.firebaseapp.com",
databaseURL: "https://train-scheduler-dbf7e.firebaseio.com",
projectId: "train-scheduler-dbf7e",
storageBucket: "train-scheduler-dbf7e.appspot.com",
messagingSenderId: "424490341397"
};
firebase.initializeApp(config);
var database = firebase.database();
//add train form button handler
$("#addTrain").on("click", function (event) {
event.preventDefault();
var trainName = $("#trainName").val().trim();
var destination = $("#destination").val().trim();
var firstTrain = $("#firstTrain").val().trim();
var freq = $("#interval").val().trim();
database.ref().push({
trainName : trainName,
destination : destination,
firstTrain : firstTrain,
frequency : freq
});//end database push
});//end button handler
database.ref().on("child_added", function (childSnapshot) {
var newTrain = childSnapshot.val().trainName;
var newDestination = childSnapshot.val().destination;
var newFirstTrain = childSnapshot.val().firstTrain;
var newFreq = childSnapshot.val().frequency;
var startTimeConv = moment(newFirstTrain, "hh:mm").subtract(1, "years")
var currentTime = moment();
var diffTime = moment().diff(moment(startTimeConv), "minutes");
var tRemainder = diffTime % newFreq;
var tMinutesTillTrain = newFreq - tRemainder;
var nextTrain = moment().add(tMinutesTillTrain, "minutes");
var trainArrival = moment(nextTrain).format("HH:mm");
$("#sched-display").append(
"<tr><td>" + newTrain +
"</td><td>" + newDestination +
"</td><td>" + newFreq +
"</td><td>" + trainArrival +
"</td><td>" + tMinutesTillTrain +
"</td></tr>"
);
$("#trainName, #destination, #firstTrain, #interval").val("");
})//end database child call
});// end for doc ready |
/* global JSON */
'use strict';
exports.setClipboardCopyData = setClipboardCopyData;
exports.parsePostFromPaste = parsePostFromPaste;
var _parsersMobiledoc = require('../parsers/mobiledoc');
var _parsersHtml = require('../parsers/html');
var _parsersText = require('../parsers/text');
var _mobiledocHtmlRenderer = require('mobiledoc-html-renderer');
var _mobiledocTextRenderer = require('mobiledoc-text-renderer');
var MOBILEDOC_REGEX = new RegExp(/data\-mobiledoc='(.*?)'>/);
var MIME_TEXT_PLAIN = 'text/plain';
exports.MIME_TEXT_PLAIN = MIME_TEXT_PLAIN;
var MIME_TEXT_HTML = 'text/html';
exports.MIME_TEXT_HTML = MIME_TEXT_HTML;
function parsePostFromHTML(html, builder, plugins) {
var post = undefined;
if (MOBILEDOC_REGEX.test(html)) {
var mobiledocString = html.match(MOBILEDOC_REGEX)[1];
var mobiledoc = JSON.parse(mobiledocString);
post = _parsersMobiledoc['default'].parse(builder, mobiledoc);
} else {
post = new _parsersHtml['default'](builder, { plugins: plugins }).parse(html);
}
return post;
}
function parsePostFromText(text, builder, plugins) {
var parser = new _parsersText['default'](builder, { plugins: plugins });
var post = parser.parse(text);
return post;
}
// Sets the clipboard data in a cross-browser way.
function setClipboardData(clipboardData, html, plain) {
if (clipboardData && clipboardData.setData) {
clipboardData.setData(MIME_TEXT_HTML, html);
clipboardData.setData(MIME_TEXT_PLAIN, plain);
} else if (window.clipboardData && window.clipboardData.setData) {
// IE
// The Internet Explorers (including Edge) have a non-standard way of interacting with the
// Clipboard API (see http://caniuse.com/#feat=clipboard). In short, they expose a global window.clipboardData
// object instead of the per-event event.clipboardData object on the other browsers.
window.clipboardData.setData('Text', html);
}
}
// Gets the clipboard data in a cross-browser way.
function getClipboardData(clipboardData) {
var html = undefined;
var text = undefined;
if (clipboardData && clipboardData.getData) {
html = clipboardData.getData(MIME_TEXT_HTML);
if (!html || html.length === 0) {
// Fallback to 'text/plain'
text = clipboardData.getData(MIME_TEXT_PLAIN);
}
} else if (window.clipboardData && window.clipboardData.getData) {
// IE
// The Internet Explorers (including Edge) have a non-standard way of interacting with the
// Clipboard API (see http://caniuse.com/#feat=clipboard). In short, they expose a global window.clipboardData
// object instead of the per-event event.clipboardData object on the other browsers.
html = window.clipboardData.getData('Text');
}
return { html: html, text: text };
}
/**
* @param {Event} copyEvent
* @param {Editor}
* @return null
*/
function setClipboardCopyData(copyEvent, editor) {
var range = editor.range;
var post = editor.post;
var mobiledoc = post.cloneRange(range);
var unknownCardHandler = function unknownCardHandler() {}; // ignore unknown cards
var unknownAtomHandler = function unknownAtomHandler() {}; // ignore unknown atoms
var _render = new _mobiledocHtmlRenderer['default']({ unknownCardHandler: unknownCardHandler, unknownAtomHandler: unknownAtomHandler }).render(mobiledoc);
var innerHTML = _render.result;
var html = '<div data-mobiledoc=\'' + JSON.stringify(mobiledoc) + '\'>' + innerHTML + '</div>';
var _render2 = new _mobiledocTextRenderer['default']({ unknownCardHandler: unknownCardHandler, unknownAtomHandler: unknownAtomHandler }).render(mobiledoc);
var plain = _render2.result;
setClipboardData(copyEvent.clipboardData, html, plain);
}
/**
* @param {Event} pasteEvent
* @param {PostNodeBuilder} builder
* @param {Array} plugins parser plugins
* @return {Post}
*/
function parsePostFromPaste(pasteEvent, builder) {
var plugins = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2];
var post = undefined;
var _getClipboardData = getClipboardData(pasteEvent.clipboardData);
var html = _getClipboardData.html;
var text = _getClipboardData.text;
if (html && html.length > 0) {
post = parsePostFromHTML(html, builder, plugins);
} else if (text && text.length > 0) {
post = parsePostFromText(text, builder, plugins);
}
return post;
} |
class Shape {
constructor(color) {
this.color = color;
}
move() {
console.log('move');
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color); // --> it extends Shape constructor.
super.move(); // it allows to see the fShape's move implementation.
this.radius = radius;
}
draw() {
console.log('circle ....')
}
/**
* method riding --> it overrides Shape's implementation
*/
move() {
console.log('circle moving ...')
}
}
const c = new Circle('red', 33);
c.draw();
c.move();
|
import React from 'react';
import { CircularProgress } from '@material-ui/core';
const Spinner = () => {
return (
<div>
<CircularProgress style={{margin: "4vh"}} />
</div>
);
};
export default Spinner; |
var app = app || {};
$(function () {
/* $("#sendMessage").click(function(evt) {
var msg = $("#message").val();
$.ajax({
type: "POST",
url: "geofeeder",
contentType: "application/json",
data: msg
}).done(function(data1){
alert("Message sent successfully");
$(data1);
}).fail(function(data1){
alert("Message can not be sent or it is empty.");
$(data1);
});
});*/
$("#clear").click(function(evt) {
$("#message").val('');
});
}); |
const fs = require('fs');
const about = fs.readFileSync('./contents/HTML/about.html', 'utf-8');
const blog = fs.readFileSync('./contents/HTML/blog.html', 'utf-8');
const contact = fs.readFileSync('./contents/HTML/contact.html', 'utf-8');
const index = fs.readFileSync('./contents/HTML/index.html', 'utf-8');
const pricing = fs.readFileSync('./contents/HTML/pricing.html', 'utf-8');
const service = fs.readFileSync('./contents/HTML/services.html', 'utf-8');
const work = fs.readFileSync('./contents/HTML/work.html', 'utf-8');
const data = {
about: about,
blog: blog,
contact: contact,
index: index,
pricing: pricing,
service: service,
work: work
};
module.exports = { data };
|
export const OPEN = 'DIALOG/OPEN';
export const open = (id, data) => ({
type: OPEN,
id,
data,
});
export const CLOSE = 'DIALOG/CLOSE';
export const close = (id) => ({
type: CLOSE,
id,
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.