text stringlengths 7 3.69M |
|---|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsPlayArrow = {
name: 'play_arrow',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>`
};
|
'use strict';
(function () {
var uploadOverlay = document.querySelector('.upload-overlay');
var uploadEffectControls = uploadOverlay.querySelector('.upload-effect-controls');
var effectImagePreview = uploadOverlay.querySelector('.effect-image-preview');
var uploadResizeValue = uploadOverlay.querySelector('.upload-resize-controls-value');
var hashTags = uploadOverlay.querySelector('.upload-form-hashtags');
var uploadPhotoForm = document.querySelector('.upload-form');
var effectLevelBlock = uploadEffectControls.querySelector('.upload-effect-level');
var filterHandle = uploadEffectControls.querySelector('.upload-effect-level-pin');
var effectValue = uploadEffectControls.querySelector('.upload-effect-level-value');
var setDefaultOptions = function () {
effectValue.style.display = 'none';
filterHandle.style.display = 'none';
effectLevelBlock.style.display = 'none';
effectImagePreview.style = '';
effectImagePreview.className = 'effect-image-preview';
uploadResizeValue.setAttribute('value', window.constants.PERCENT_MAXVALUE + '%');
};
setDefaultOptions();
var setDefaultFilter = function () {
effectLevelBlock.style.display = 'block';
if (effectImagePreview.className === 'effect-none') {
filterHandle.style.display = 'none';
effectImagePreview.style.filter = 'none';
effectLevelBlock.style.display = 'none';
}
if (effectImagePreview.className === 'effect-chrome') {
effectImagePreview.style.filter = 'grayscale(' + window.constants.INITIAL_INPUT_VALUE / 100 + ')';
}
if (effectImagePreview.className === 'effect-sepia') {
effectImagePreview.style.filter = 'sepia(' + window.constants.INITIAL_INPUT_VALUE / 100 + ')';
}
if (effectImagePreview.className === 'effect-marvin') {
effectImagePreview.style.filter = 'invert(' + window.constants.INITIAL_INPUT_VALUE + '%' + ')';
}
if (effectImagePreview.className === 'effect-phobos') {
effectImagePreview.style.filter = 'blur(' + window.constants.INITIAL_INPUT_VALUE / 100 * 5 + 'px' + ')';
}
if (effectImagePreview.className === 'effect-heat') {
effectImagePreview.style.filter = 'brightness(' + window.constants.INITIAL_INPUT_VALUE / 100 * 3 + ')';
}
};
window.initializeFilter.applyClass(setDefaultFilter);
var adjustScale = function () {
var parsedResizeValue = parseInt(uploadResizeValue.value, 10);
if (parsedResizeValue < window.constants.PERCENT_MAXVALUE) {
effectImagePreview.style.transform = 'scale(0.' + parsedResizeValue + ')';
} else {
effectImagePreview.style.transform = 'scale(1)';
}
};
window.initializeScale.resizeDecrease(adjustScale);
window.initializeScale.resizeIncrease(adjustScale);
var getFormError = function () {
var separator = ' ';
var hashTagsSplit = hashTags.value.toLowerCase().split(separator);
hashTags.style.outlineColor = '';
hashTags.style.outlineStyle = 'solid';
var filteredHashTags = hashTagsSplit.filter(window.util.getUniqueElements);
if (hashTagsSplit.length > 5) {
return true;
}
var checkFormValidity = hashTagsSplit.some(function (hashTag) {
if (filteredHashTags.length !== hashTagsSplit.length) {
return true;
}
if (hashTag.length > window.constants.HASHTAG_MAXLENGTH
|| (hashTag.length !== 0 && hashTag.lastIndexOf('#') !== 0)) {
return true;
}
return false;
});
return checkFormValidity;
};
var getFormResponse = function () {
var errors = getFormError();
if (errors) {
hashTags.style.outlineColor = 'red';
hashTags.setCustomValidity('Форма заполнена неверно :(');
} else {
hashTags.setCustomValidity('');
}
};
// хэштеги
hashTags.addEventListener('input', function () {
getFormResponse();
});
uploadPhotoForm.addEventListener('submit', function (evt) {
getFormResponse();
window.backend.save(new FormData(uploadPhotoForm), function () {
uploadOverlay.classList.add('hidden');
uploadPhotoForm.reset();
setDefaultOptions();
}, window.util.errorHandler);
evt.preventDefault();
});
var applyFilter = function () {
if (effectImagePreview.className === 'effect-chrome') {
effectImagePreview.style.filter = 'grayscale(' + (effectValue.value / window.constants.PERCENT_MAXVALUE).toFixed(1) + ')';
}
if (effectImagePreview.className === 'effect-sepia') {
effectImagePreview.style.filter = 'sepia(' + (effectValue.value / window.constants.PERCENT_MAXVALUE).toFixed(1) + ')';
}
if (effectImagePreview.className === 'effect-marvin') {
effectImagePreview.style.filter = 'invert(' + Math.round((filterHandle.offsetLeft + window.shift.x) / window.constants.RANGE_MAXCOORD * window.constants.PERCENT_MAXVALUE) + '%' + ')';
}
if (effectImagePreview.className === 'effect-phobos') {
effectImagePreview.style.filter = 'blur(' + (effectValue.value / window.constants.PERCENT_MAXVALUE * window.constants.BLUR_MAXVALUE).toFixed(1) + 'px' + ')';
}
if (effectImagePreview.className === 'effect-heat') {
effectImagePreview.style.filter = 'brightness(' + (effectValue.value / window.constants.PERCENT_MAXVALUE * window.constants.BRIGHTNESS_MAXVALUE).toFixed(1) + ')';
}
};
window.initializeFilter.controlSlider(applyFilter);
})();
|
import * as React from 'react';
import {useState, useEffect} from 'react'
import { ScrollView,View, Text, Image } from 'react-native';
import styles from './Style';
import ProgressCircle from 'react-native-progress-circle'
import { ListItem, Button, Avatar } from 'react-native-elements'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'
import { useNavigation } from '@react-navigation/native';
import {connect} from 'react-redux';
import axios from 'axios'
function ActivityHeader() {
const navigation = useNavigation()
return (
<View style={styles.headerContainer}>
<View style={{display: 'flex', flexDirection: 'row', justifyContent:'space-between'}}>
<Text style={styles.headerName}><Icon onPress={() => navigation.goBack()} name="chevron-left" size={35}/>My Class</Text>
</View>
</View>
)
}
function MyClass(props) {
const navigation = useNavigation()
let [studentClass, setStudentClass] = useState([]);
let [fasilitatorClass, setFasilitatorClass] = useState([]);
const role = props.authReducers.user.role_id
useEffect(() => {
const token = props.authReducers.user.token;
axios
.get(
"http://192.168.1.100:8000/courses/api/studentscore/",
{
headers: {'x-access-token': `Bearer ${token}`},
},
)
.then(res => setStudentClass(res.data.data))
.catch(err => console.log(err));
}, []);
console.log(studentClass)
useEffect(() => {
const token = props.authReducers.user.token;
axios
.get(
"http://192.168.1.100:8000/courses/api/myClassFasilitator/?page=1&limit=20",
{
headers: {'x-access-token': `Bearer ${token}`},
},
)
.then(res => setFasilitatorClass(res.data.result))
.catch(err => console.log(err));
}, []);
console.log(fasilitatorClass)
return (
<ScrollView>
<ActivityHeader/>
{role === 1 ? (
<View style={{padding: 20}}>
<View style={{display: 'flex', flexDirection: 'row', marginTop : 15, justifyContent: 'space-between', marginBottom: 20, margin: 10, marginRight: 30}}>
<Text style={{fontFamily: 'Montserrat-SemiBold', fontSize: 16}}>Class Name</Text>
<Text style={{fontFamily: 'Montserrat-SemiBold', fontSize: 16}}>Score</Text>
<Text style={{fontFamily: 'Montserrat-SemiBold', fontSize: 16}}>Progress</Text>
</View>
<View>
{studentClass?.length === 0 && (
<>
<ListItem>
<ListItem.Content style={styles.itemContent}>
<Text style={styles.textItem1}>You Got No Class</Text>
</ListItem.Content>
</ListItem>
</>
)}
{
studentClass.map((l, i) => (
<ListItem containerStyle={{borderRadius: 20, marginTop: 5}} key={i} bottomDivider>
<ListItem.Content style={{padding: 10, display:'flex', flexDirection: 'row', justifyContent: 'space-between'}}>
<Text style={{fontFamily: 'Montserrat-Medium', fontSize: 16, flex: 1}}>{l.class_name}</Text>
<Text style={{fontFamily: 'Montserrat-SemiBold', fontSize: 30, alignSelf:'center', color: '#51E72B', flex: 1, marginLeft: '10%'}}>{l.score}</Text>
<ProgressCircle
percent={Number(l.progress)}
radius={27}
borderWidth={4}
color="#3399FF"
shadowColor="#fff"
bgColor="#fff"
>
<Text style={{ fontSize: 18, color: '#5784BA' }}>{l.progress}%</Text>
</ProgressCircle>
</ListItem.Content>
<Image style={{height: 30, width: 7, alignSelf: 'center'}} source={require('../../../assets/img/list.png')}/>
</ListItem>
))
}
</View>
</View>
) : (
<View style={{padding: 20}}>
<View style={{display: 'flex', flexDirection: 'row', marginTop : 15, justifyContent: 'space-between', marginBottom: 20, margin: 10, marginRight: 30}}>
<Text style={{fontFamily: 'Montserrat-SemiBold', fontSize: 16}}>Class Name</Text>
<Text style={{fontFamily: 'Montserrat-SemiBold', fontSize: 16}}>Student Count</Text>
</View>
<View>
{fasilitatorClass?.length === 0 && (
<>
<ListItem>
<ListItem.Content style={styles.itemContent}>
<Text style={styles.textItem1}>You Don't Have Class</Text>
</ListItem.Content>
</ListItem>
</>
)}
{
fasilitatorClass.map((l, i) => (
<ListItem containerStyle={{borderRadius: 20, marginTop: 5}} key={i} bottomDivider>
<ListItem.Content style={{padding: 10, display:'flex', flexDirection: 'row', justifyContent: 'space-between'}}>
<Text onPress={() => navigation.navigate('ClassDetail')} style={styles.textItem1}>{l.class_name}</Text>
<Text style={{fontFamily: 'Montserrat-SemiBold',textAlign: 'center', color: '#000000', fontSize: 16}}>{l.student_count} <Image source={require("../../../assets/img/student-icon.png")} /></Text>
</ListItem.Content>
</ListItem>
)) }
</View>
</View>
)}
</ScrollView>
);
}
const mapStateToProps = state => {
return {
authReducers: state.authReducers,
};
};
const ConnectedMyClass = connect(mapStateToProps)(MyClass);
export default ConnectedMyClass; |
import React from "react"
import Advert from "../components/Advert"
import AdvertCards from "../components/AdvertCards"
import Events from "../components/Events"
import Goods from "../components/Goods"
import Hero from "../components/Hero"
import News from "../components/News"
import WrapperThree from "../components/WrapperThree"
import WrapperTwo from "../components/WrapperTwo"
import Seo from "../components/Seo"
export default function Home() {
return (
<>
<Seo title="home" />
<main className="main-content">
<Hero />
<Advert />
<Goods />
<AdvertCards />
<WrapperTwo />
<News />
<Events />
<WrapperThree />
</main>
</>
)
}
|
import React, { Component, Suspense } from 'react';
import {
Switch,
Redirect,
Router
} from 'react-router-dom';
import { Layout, Spin } from 'antd';
import { createHashHistory } from 'history';
import LayoutHeader from '@components/LayoutHeader/index';
import Menu from './components/menu';
import routeConfig from '@routeConfig';
import './index.less';
const { Header, Content, Sider } = Layout;
const history = createHashHistory();
class Index extends Component {
constructor(props) {
super(props);
this.state = { };
}
render() {
return (
<Router history={history}>
<Layout className="homeLayout">
<Sider
style={{
overflow: 'auto',
height: '100vh',
left: 0
}}
theme="light"
>
<div className="logo" />
<Menu />
</Sider>
<Layout>
<Header className="header">
<LayoutHeader />
</Header>
<Content className="homeContent">
<Suspense fallback={<section className="page-spin"><Spin /></section>}>
<Switch>
{routeConfig}
<Redirect
from="/*"
to="/dashboard"
/>
</Switch>
</Suspense>
</Content>
</Layout>
</Layout>
</Router>
);
}
}
export default Index;
|
Ext.define('LocalStorageDao',
{
config:
{
fields:null,//列名
storageId:null,//localStorage的唯一标示,相当于表名
rowId:'id'//行主键名,默认是id
},
constructor: function(config)
{//构造方法
this.initConfig(config);
return this;
},
getAll:function()
{//获取表所有数据,以数组返回
var table = [];
var t = localStorage.getItem(this.getStorageId());
if(t)
table = Ext.decode(t);
return table;
},
getSortAll:function(type)
{//排序
var table = this.getAll();
var rowId = this.getRowId();
if(type == 'asc')
{
table.sort(function(a,b)
{
if(a[rowId] < b[rowId])
return -1;
if(a[rowId] > b[rowId])
return 1;
return 0;
});
}else if(type == 'desc')
{
table.sort(function(a,b)
{
if(a[rowId] > b[rowId])
return -1;
if(a[rowId] < b[rowId])
return 1;
return 0;
});
}
return table;
},
queryByField:function(fieldName,fieldValue)
{//查询
var table = this.getAll();
var field = null;
for(var i=0;i<table.length;i++)
{
if(table[i][fieldName]==fieldValue)
{
field = table[i];
break;
}
}
return field;
},
insert:function(field)
{//插入
var table = this.getAll();
table.push(field);
localStorage.setItem(this.getStorageId(),Ext.encode(table));
},
update:function(field)
{//更新
var table = this.getAll();
var fieldDb = this.queryByField(this.getRowId(),field[this.getRowId()]);
if(!fieldDb)
{
this.insert(field);
}else{
var tableStr = Ext.encode(table);
var newTableStr = tableStr.replace(Ext.encode(fieldDb),Ext.encode(field));
localStorage.setItem(this.getStorageId(),newTableStr);
}
},
del:function(field)
{//删除
var table = this.getAll();
var fieldDb = this.queryByField(this.getRowId(),field[this.getRowId()]);
if(fieldDb)
{
var tableStr = Ext.encode(table);
var newTableStr = tableStr.replace(Ext.encode(fieldDb)+',','');
newTableStr = tableStr.replace(Ext.encode(fieldDb),'');
localStorage.setItem(this.getStorageId(),newTableStr);
}
}
}); |
/*
Connette TTN con MONGODB
quando il client TTN riceve un nuovo messaggio (in MQTT ?)
lo inserisce nel DB di mongo
*/
//Libraries
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var ttn = require('ttn');
//Library to run shell script:
var exec = require('child_process').exec;
//MongoDb Local Url
var url = 'mongodb://localhost:27017/arcesLoraPlatform';
//TTN Application Info
var region = 'eu';
var appId = 'app00';
var accessKey = 'ttn-account-v2.-BJ3YmxaJpAuwMtyHmnCOIemBpOrop5haiwI5K4yrrY';
var client = new ttn.Client(region, appId, accessKey);
client.on('connect', function(connack) {
console.log('[DEBUG]', 'Connect:', connack);
});
client.on('error', function(err) {
console.error('[ERROR]', err.message);
});
client.on('activation', function(deviceId, data) {
console.log('[INFO] ', 'Activation:', deviceId, JSON.stringify(data, null, 2));
});
client.on('device', null, 'down/scheduled', function(deviceId, data) {
console.log('[INFO] ', 'Scheduled:', deviceId, JSON.stringify(data, null, 2));
});
client.on('message', function(deviceId, data) {
console.info('[INFO] Message Arrived');
//Call insert local document:
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, data, function() {
db.close();
});
});
//Publish on Arces GIOVE server:
exec('sh mosquittoPub.sh ' + data.payload_fields.moisture + ' ' + data.dev_id + ' ' + data.metadata.time, function(error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
else {
console.log('Published on Giove');
}
});
});
//Define a function to insert a document:
var insertDocument = function(db, data, callback) {
db.collection('loramessages').insertOne( {
"app_id" : data.app_id,
"dev_id" : data.dev_id,
"deviceType" : data.payload_fields.deviceType,
"moisture" : data.payload_fields.moisture,
"battery" : data.payload_fields.battery,
"timestamp" : data.metadata.time,
}, function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the loramessage collection.");
callback();
});
}; |
import React from 'react'
import "./card.css"
const Card = ({text,icon,no}) => {
return (
<>
<div className="card_wrapper">
<div className="icon">
{icon}
</div>
<h1>{no}</h1>
<p>{text}</p>
</div>
</>
)
}
export default Card
|
$(function () {
var obtainPlayerData = function (callback) {
var file = 'players_from_updates.txt'
// var file = './nfl-players2.txt';
playerMap = {};
$.getJSON(file, function (json) {
var allPlayersJSON = json;
$.each(allPlayersJSON, function (index, player) {
playerMap[player['player']] =
{
pos: player['pos'],
team: player['team'],
};
});
callback (playerMap);
}).fail(function (a, b, err) {
alertify.error('Failed loading players - ' + err);
});
// playerMap = {};
// $.ajax({
// url: file,
// type: 'GET',
// dataType: 'jsonp',
// jsonpCallback: 'callback',
// async: true,
// success: function (data) {
// var allPlayersJSON = data;
// $.each(allPlayersJSON['list'], function (index, player) {
// playerMap[player['player']] =
// {
// pos: player['pos'],
// team: player['team'],
// };
// });
// callback (playerMap);
// },
// error: function (data, err) {
// alertify.error('Failed loading players - ' + err);
// },
// });
};
window.PlayerHandler = obtainPlayerData;
}); |
$(document).ready(function(){
$('.round').corners('bottom-left bottom-right');
});
|
$(document).ready( function() {
$('#autocomplete').autocomplete({
serviceUrl: '/API/autocomplete',
onSelect: function (suggestion) {
console.log(suggestion.value);
window.location = '/API/results?q=' + suggestion.value;
}
});
});
|
function check(){
var userName = getCookie("user");
if (userName != "" && userName != null) {
$("#user_name").html(userName);
$("#user_login").html("");
$("#user_register").html("");
return true;
} else {
location.href = "findByPhone.html";
return false;
}
}
function show(){
$.ajax({
type:"post",
url:"/Shop/pre/findOrders.do",
dataType:"json",
success:function(jo){
if(jo.REQUEST_SUCCESS=="1"){
var data = jo.RESULT_CONTENT.orderList;
var str = "";
$(data).each(function(){
str +='<tr data-order-id="'+this.order_id+'">'+
'<td>'+this.address_person+'</td>'+
'<td>'+this.address_phone+'</td>'+
'<td>'+this.address+'</td>'+
'<td>'+this.order_price+'</td>';
if(this.order_status=="1"){
str +='<td>未收货</td>';
}else{
str +='<td>已收货</td>';
}
str +='<td><a class="order_look" data-target="#ajax_target" data-trigger="ajax" href="#">查看</a>/<a class="queren" style="cursor: pointer;">确认收货</a></td></tr>';
$("#order_tbody").append(str);
str="";
$("#order_tbody tr:last").data("order",this);
});
}else{
alert(jo.RESULT_MESSAGE);
}
}
});
}
$(document).on("click",'.order_look',function(){
order_id=$(this).parent().parent("tr").attr("data-order-id");
location.href="orderDetail.html?order_id="+order_id;
});
$(document).on("click",'.queren',function(){
var id=$(this).parent().parent().data("order").order_id;
$.ajax({
type:"post",
url:"/Shop/pre/shouhuo.do",
dataType:"json",
data:{"id":id},
success:function(jo){
if(jo.RESULT_SUCCESS=="1")
alert(jo.RESULT_MESSAGE);
$("#order_tbody").html("");
check();
show();
}
});
});
$(function(){
if(check()){
show();
}
}); |
$('body').append('<input type="text" id="sessionKeyInput" value="e4mc48qmxb7vsps3e5y0lv00jjtax02722exjn0v">');
$('body').append('<input type="submit" id="sessionKeySubmit" value="Login" onClick="checkData()">');
$('body').append('<div id="result">');
function checkData(){
getProfile()
.then(function () {
return getRoles()
})
.then(function (roles) {
roles.forEach(function (item) {
setRole(item.name)
.then(function (role) {
getSchools(role.key).then(function (schools) {
schools.forEach(function (school) {
if (role.role === 'ADMIN' || role.role === 'MANAGER' || role.role === 'TRAINER'){
getStudentList(role.key, school.id);
getHouseList(role.key, school.id);
getFormList(role.key, school.id);
}
})
});
})
});
});
}
function getProfile() {
var usid = $("#sessionKeyInput").val();
return $.ajax({
type: "GET",
headers: {"usid": usid},
url: "http://api.stage1.squadintouch.com/i/profile?filter=%22%22",
statusCode: {
200: function (response) {
$('#result').append('<div id="profile">');
$('#profile').html('Name: '+response.firstName + ' ' + response.lastName);
},
},
dataType: "json"
});
}
function getRoles() {
var usid = $("#sessionKeyInput").val();
return $.ajax({
type: "GET",
headers: {"usid": usid},
url: "http://api.stage1.squadintouch.com/i/roles?filter=%22%22",
statusCode: {
200: function (response) {
response.forEach(function(item) {
$('#result').append('<ul id="roles">');
$('#roles').append("<li>"+item.name+"</li>");
});
},
},
dataType: "json"
});
}
function setRole(role) {
var usid = $("#sessionKeyInput").val();
return $.ajax({
type: "POST",
headers: {"usid": usid},
url: "http://api.stage1.squadintouch.com/i/roles/" + role + "/become?filter=%22%22",
statusCode: {
201: function (response) {
// console.log(response);
},
},
dataType: "json"
});
}
function getSchools(sessionKey) {
return $.ajax({
type: "GET",
headers: {"usid": sessionKey},
url: "http://api.stage1.squadintouch.com/i/schools?filter=%22%22",
statusCode: {
200: function (response) {
// console.log(response);
},
},
dataType: "json"
});
}
function getStudentList(sessionKey, schoolId) {
return $.ajax({
type: "GET",
headers: {"usid": sessionKey},
url: "http://api.stage1.squadintouch.com/i/schools/" + schoolId + "/students?filter=%7B%22limit%22%3A20%2C%22skip%22%3A20%7D&{}",
statusCode: {
200: function (response) {
console.log(response);
},
},
dataType: "json"
});
}
function getHouseList(sessionKey, schoolId) {
return $.ajax({
type: "GET",
headers: {"usid": sessionKey},
url: "http://api.stage1.squadintouch.com/i/schools/" + schoolId + "/houses?filter=%7B%22limit%22%3A20%7D&{}",
statusCode: {
200: function (response) {
console.log(response);
},
},
dataType: "json"
});
}
function getFormList(sessionKey, schoolId) {
return $.ajax({
type: "GET",
headers: {"usid": sessionKey},
url: "http://api.stage1.squadintouch.com/i/schools/" + schoolId + "/forms?filter=%7B%22limit%22%3A30%7D&{}",
statusCode: {
200: function (response) {
console.log(response);
},
},
dataType: "json"
});
} |
import express from 'express';
import {postOption, fetchJsonByNode} from '../../../common/common';
import {host} from '../../globalConfig';
let api = express.Router();
const maxNumber = 20;
const service = `${host}/tms-service`;
// 获取界面信息
api.get('/config', async (req, res) => {
const module = await require('./config');
res.send({returnCode: 0, result: module.default});
});
/*-------------列表增删改查-------------*/
// 获取主列表数据
api.post('/list', async (req, res) => {
const url = `${service}/payable_month_bill/list/search`;
const {filter,...others} = req.body;
const body = {
...filter,...others
};
res.send(await fetchJsonByNode(req,url,postOption(body)));
});
//获取单条信息
api.get('/one/:id', async (req, res) => {
const url = `${service}/payable_month_bill/${req.params.id}`;
res.send(await fetchJsonByNode(req,url));
});
// 新增保存or编辑
api.post('/add', async (req, res) => {
const url = `${service}/payable_month_bill`;
res.send(await fetchJsonByNode(req,url,postOption(req.body)));
});
//批量删除
api.post('/delete', async (req, res) => {
const url = `${service}/payable_month_bill/batch`;
res.send(await fetchJsonByNode(req, url,postOption(req.body, 'delete')));
});
//批量发送
api.post('/send', async (req, res) => {
const url = `${service}/payable_month_bill/send`;
res.send(await fetchJsonByNode(req, url,postOption(req.body)));
});
//批量对账
api.post('/check', async (req, res) => {
const url = `${service}/payable_month_bill/reconciliation`;
res.send(await fetchJsonByNode(req, url,postOption(req.body)));
});
//批量撤销
api.post('/cancel', async (req, res) => {
const url = `${service}/payable_month_bill/cancel`;
res.send(await fetchJsonByNode(req, url,postOption(req.body)));
});
/*-------------结算单位-------------*/
// 获取结算单位
api.post('/settlement', async (req, res) => {
const url = `${service}/transport_order/cost/month_bill/list/search`;
res.send(await fetchJsonByNode(req,url,postOption(req.body)));
});
//加入结算单位(批量)
api.post('/addSettlement', async (req, res) => {
const url = `${service}/payable_month_bill_charge/batch`;
res.send(await fetchJsonByNode(req,url,postOption(req.body)));
});
//根据结算单位ID获取单条信息拿到币种
api.get('/supplierId/:id', async (req, res) => {
const url = `${host}/archiver-service/supplier/${req.params.id}`;
res.send(await fetchJsonByNode(req, url));
});
//移除明细
api.delete('/del', async (req, res) => {
const url = `${service}/payable_month_bill_charge`;
res.send(await fetchJsonByNode(req, url,postOption(req.body,'delete')));
});
// 删除明细
api.delete('/delList', async (req, res) => {
const url = `${service}/payable_month_bill`;
res.send(await fetchJsonByNode(req,url,postOption(req.body,'delete')));
});
//根据月帐单标识及应收结算单标识返回列表信息
api.get('/monthId/:id', async (req, res) => {
const url = `${service}/payable_month_bill/${req.params.id}/${req.query.filter}`;
res.send(await fetchJsonByNode(req, url));
});
//应收月帐单加入对账明细
api.post('/joinSettlement', async (req, res) => {
const url = `${service}/payable_month_bill_charge`;
res.send(await fetchJsonByNode(req,url,postOption(req.body)));
});
/*-------------下拉-------------*/
// 获取币种
api.get('/currency', async (req, res) => {
const body = {
currencyTypeCode:req.query.filter,
maxNumber
};
const url = `${host}/archiver-service/charge/tenant_currency_type/drop_list`;
res.send(await fetchJsonByNode(req, url, postOption(body)));
});
// 获取结算单位下拉(客户下拉)
api.get('/supplierId', async (req, res) => {
const url = `${host}/archiver-service/supplier/drop_list/enabled_type_enabled`;
const body = {
filter:req.query.filter,
maxNumber
};
res.send(await fetchJsonByNode(req, url, postOption(body)));
});
export default api;
|
// TODO: part of GUI
|
const express = require('express');
const homeRoute = express.Router();
const controller = require('./../controllers/home');
homeRoute.get('/', controller.get['/']);
homeRoute.get('/user/:name', controller.get['/user/:name']);
module.exports = homeRoute;
|
var mysql = require('mysql'),
claimingId = 1,
connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'corelogic',
database : 'imageservice'
});
connection.connect();
ImageQueue = function() {};
ImageQueue.prototype.enqueue = function (obj, callback) {
connection.query('INSERT INTO blobimage SET ?',
{ Account: obj.Account,
Project: obj.Project,
ImageFormat: obj.ImageFormat,
Image: obj.Image,
Created: new Date(),
Updated: new Date(),
Status: 'New'},
function(err, result) {
if (err) throw err;
callback(null, result.insertId);
});
};
ImageQueue.prototype.dequeue = function(callback) {
connection.query('call blob_dequeue(' + connection.escape(claimingId++) + ')',
function(err, rows) {
if (rows === null || rows.length === 0) return callback(null, null);
callback(null, rows[0]);
});
};
ImageQueue.prototype.getStatus = function(id, callback) {
connection.query('select status from blobimage where id = ' + connection.escape(id), function(err, results) {
if (results === null || results.length === 0) return callback(null, null);
callback(null, results[0].status);
});
};
exports.ImageQueue = ImageQueue; |
/**
* Record of all entity Classes available
*/
/*global define */
define(['entities/base', 'entities/image', 'entities/resize', 'entities/text'],
function (Base, Image, Resize, Text) {
'use strict';
var entity = {
Base: Base,
Image: Image,
Resize: Resize,
Text: Text
};
return entity;
}); |
/**=========================================================
* Module: form-wizard.js
* Handles form wizard plugin and validation
* [data-toggle="wizard"] to activate wizard plugin
* [data-validate-step] to enable step validation via parsley
=========================================================*/
(function($, window, document){
'use strict';
if(!$.fn.bwizard) return;
var Selector = '[data-toggle="wizard"]';
$(Selector).each(function() {
var wizard = $(this),
validate = wizard.data('validateStep'), // allow to set options via data-* attributes
options;
// Find a progress bar if exists and advance its state
options = {
'show' : function(e, ui) {
var panelParent = $(ui.panel).parent(),
total = panelParent.find('[role="tabpanel"]').length,
current = ui.index + 1,
percent = (current/total) * 100;
panelParent.siblings('.progress').children('.progress-bar').css({width:percent+'%'});
}
};
if(validate) {
// Dont allow direct move to step
options.clickableSteps = false;
// validate via parsley
options.validating = function(e, ui) {
var $this = $(this),
form = $this.parent(),
group = form.find('.bwizard-activated');
if (false === form.parsley().validate( group[0].id )) {
e.preventDefault();
return;
}
};
}
// Invoke the plugin
wizard.bwizard(options);
});
}(jQuery, window, document));
|
import React from 'react';
import PropTypes from 'prop-types';
import styles from 'App/components/stylesheets/StepsList.scss';
const { string } = PropTypes;
/**
* A step that leads to getting a certificate.
*
* @example "Take All Lessons" from a course main page
*
* @param {Object} props - The React props object
*
* @since 1.0.0
*/
const Step = (props) => {
const {
className,
title,
children
} = props;
return (
<li className={ className }>
<span className={ `${ styles.title } course-step-title` }>{ title }</span>
<span className={ `${ styles.desc } course-step-description` }>{ children }</span>
</li>
);
};
Step.propTypes = {
className: string,
title: string,
children: string
};
export default Step;
|
var courier = require('../main');
var localCourier = courier.clone( courier.addCourier( courier.System.clone() ) );
global.courier = localCourier;
global.System = localCourier.System;
localCourier.config({
config: __dirname+"/node_test_plugins/config.js",
main: "main"
});
localCourier.startup().then(function(){
console.log("worked");
},function(e){
console.log(e);
})
|
import React from "react";
import styled from "styled-components";
import { BiEditAlt } from "react-icons/bi";
import { Link } from "react-router-dom";
const Create = () => {
return (
<Link to={"/create"} style={{ textDecoration: "none" }}>
<Main>
<Icon>
<BiEditAlt color="dodgerblue" size={30} />
</Icon>
<Text>Create New Post</Text>
</Main>
</Link>
);
};
export default Create;
const Icon = styled.div`
background: white;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
border-radius: 1rem;
width: 2rem;
font-size: 20px;
`;
const Text = styled.p`
margin-left: 1rem;
font-size: 25px;
`;
const Main = styled.div`
margin: 2rem auto;
background-color: #fff;
border-radius: 1rem;
padding: 1rem;
color: dodgerblue;
width: 40rem;
height: 5rem;
display: flex;
align-items: center;
transition-timing-function: ease-in-out;
transition-duration: 200ms;
border: solid 5px dodgerblue;
box-sizing: border-box;
&:hover {
background: dodgerblue;
transform: scale(1.03);
color: white;
}
`;
|
import {Controller} from '@hotwired/stimulus';
export default class extends Controller {
/**
*
* @param event
*/
touchstart(event) {
this.startPageY = event.touches[0].screenY;
}
/**
*
* @param event
*/
touchmove(event) {
if (this.willRefresh) {
return
}
const scrollTop = document.body.scrollTop
const dy = event.changedTouches[0].screenY - this.startPageY
if (scrollTop < 1 && dy > 150) {
this.willRefresh = true;
this.element.style = 'filter: blur(1px);opacity: 0.2;touch-action: none;';
}
}
/**
*
* @param event
*/
touchend(event) {
if (this.willRefresh) {
Turbo.visit(window.location.toString(), {action: 'replace'});
}
}
}
|
import React, { useRef, useState } from "react";
import styled from "styled-components";
import gsap from "gsap";
const Container = styled.div`
position: relative;
width: 80vw;
height: 80vh;
border: 1px dashed black;
padding: 25px;
.primary-section {
position: absolute;
z-index: 1;
height: calc(100% - 50px);
width: calc(100% - 50px);
background-color: #172a3a;
border-radius: 25px;
display: flex;
justify-content: center;
align-items: center;
color: whitesmoke;
}
.secondary-section {
position: absolute;
width: calc(50% - 50px);
height: calc(100% - 50px);
right: 0;
opacity: 0;
display: flex;
justify-content: center;
align-items: center;
}
button {
position: absolute;
z-index: 2;
padding: 10px 20px;
border: 3px solid #74b3ce;
border-radius: 20px;
background-color: white;
cursor: pointer;
bottom: 35px;
right: 35px;
}
`;
export default function Form() {
const [section, setSection] = useState(1);
let primarySect = useRef(null);
let primaryTitle = useRef(null);
let secondSect = useRef(null);
let buttonRef = useRef(null);
const sectionHandler = () => {
if (section > 3) {
nextSectionHandler();
} else {
finalSectionHandler();
}
};
const nextSectionHandler = () => {
gsap.to(primarySect, {
width: "calc(100% - 50px)",
duration: 0.8,
ease: "circ.inOut",
});
gsap.to(primaryTitle, {
opacity: 0,
duration: 0.5,
});
gsap.to(primaryTitle, {
opacity: 1,
duration: 0.4,
delay: 1,
});
setTimeout(() => {
let temp = section + 1;
setSection(temp);
}, 800);
};
const finalSectionHandler = () => {
gsap.to(primarySect, {
width: "calc(30% - 25px)",
duration: 0.8,
ease: "circ.inOut",
});
gsap.to(secondSect, {
width: "calc(70% - 25px)",
opacity: 1,
duration: 0.8,
ease: "circ.inOut",
});
gsap.to(primaryTitle, {
opacity: 0,
duration: 0.5,
});
gsap.to(primaryTitle, {
opacity: 1,
duration: 0.4,
delay: 1,
});
setTimeout(() => {
let temp = section + 1;
setSection(temp);
}, 800);
};
return (
<Container>
<section className="primary-section" ref={(el) => (primarySect = el)}>
<h1 ref={(el) => (primaryTitle = el)}>{section}</h1>
</section>
<section className="secondary-section" ref={(el) => (secondSect = el)}>
<h1>{section}</h1>
</section>
{section < 5 && (
<button ref={(el) => (buttonRef = el)} onClick={sectionHandler}>
NEXT
</button>
)}
{section === 5 && <button>Submit</button>}
</Container>
);
}
|
import styled from 'styled-components';
export const Container = styled.div`
background-color: #343746;
box-shadow: 0 0 14px 0 rgba(3, 5, 2, 0.2);
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
margin-top: 35px;
text-align: center;
padding: 30px;
border-radius: 5px;
transform-style: preserve-3d;
transition: all .8s;
:active {
box-shadow: 0 0 14px 0 rgba(99, 99, 99, 0.1);
transform: rotateY(180deg);
}
.front {
backface-visibility: hidden;
}
.verse {
position: absolute;
padding: 20px;
backface-visibility: hidden;
transform: rotateY(180deg);
justify-content: center;
align-items: center;
p {
color: #fff;
font-weight: bold;
}
}
img {
box-shadow: 0 0 14px 0 rgba(1, 1, 1, 0.08);
height: 300px;
width: 450px;
object-fit: cover;
border-radius: 5px;
}
h3 {
color: #c4c4c4;
font-weight: bold;
margin-top: 12px;
}
`;
|
/* Question:
* There is a building of 100 floors. If an egg drops from the Nth floor or above
* it will break If it’s dropped from any floor below, it will not break.
* You’re given 2 eggs Find N, while minimizing the number of drops for the worst case.
*
* consider two extreme cases:
* - try at each floor (interval is 0 (no skipping)): worst case: 100 tries
* - drop at 100th floor (interval is 99 (skipping all)), then try each floor: 100 tries
* solution: find the perfect interval to start with and reduce one as it goes up.
* (so that the interval size is not bigger than the number of tries have done)
* idea: 1 + 2 + 3 + ... + n >= 100, find n?
* 0-14-27-39-50-60-69-77-84-90-95-99-100
*/
function findMaxTries () {
var sum = 0,
n = 1;
while (sum < 100) {
n++;
sum += n;
}
return n; // => 14
}
|
import React from 'react'
import { Modal } from 'antd-mobile';
import './ask.css'
import { withRouter } from 'react-router-dom'
import MyScore from 'api/score/score'
import Asking from './asking/asking'
import { connect } from 'react-redux'
const alert = Modal.alert;
// 关闭辅助函数
function closest(el, selector) {
const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
while (el) {
if (matchesSelector.call(el, selector)) {
return el;
}
el = el.parentElement;
}
return null;
}
class Ask extends React.Component {
constructor(props) {
super(props);
this.state = {
modal1: false,
listScore: [],
isAsk: false,
};
}
componentDidMount() {
this.init()
}
goto_score() {
this.props.history.push("/course/test/score")
}
init() {
this.getScoreListData()
}
getScoreListData() {
// 获取学生成绩列表
let testInfo = this.props.testInfo
MyScore.getListScore(testInfo.tsId).then(res => {
this.setState({
listScore: [...res.data.items]
})
// 显示已答题
if (res.data.items.length >= testInfo.tsAsk) {
this.showModal()
}
else { // 显示确认答题框?
this.showAlert(testInfo.tsAsk - res.data.items.length)
}
})
}
showModal(e) {
e && e.preventDefault() // 修复 Android 上点击穿透
this.setState({
modal1: true,
});
}
// 显示答题确认框
showAlert(count) {
alert('提示', `还有${count}次答题机会,确定答题?`, [
{ text: '不了', onPress: () => { this.props.history.push("/course/index/activity") }, style: 'default' },
{
text: '确定', onPress: () => {
this.setState({
isAsk: true
})
}
},
]);
}
// 返回上一页
onBack = key => () => {
this.props.history.push("/course/index/activity")
}
// 显示框辅助函数
onWrapTouchStart = (e) => {
// fix touch to scroll background page on iOS
if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
return;
}
const pNode = closest(e.target, '.am-modal-content');
if (!pNode) {
e.preventDefault();
}
}
render() {
return (
<div className='ask'>
<Modal
visible={this.state.modal1}
transparent
maskClosable={false}
title="提示"
footer={[
{ text: '返回', onPress: () => { this.onBack()() } },
{
text: '查看成绩', onPress: () => {
this.goto_score()
}
},
]}
wrapProps={{ onTouchStart: this.onWrapTouchStart }}
>
<div style={{ height: 40, overflow: 'scroll' }}>
你的次数答题已用尽。<br />
</div>
</Modal>
{
this.state.isAsk ?
<Asking/>
:
null
}
</div>
)
}
}
const mapStateToProps = state => {
return {
testInfo: state.testInfo
}
}
export default withRouter(connect(mapStateToProps,null)(Ask)) |
define(['apps/system/system.service'], function (app) {
app.factory("system_user_service", function ($rootScope,Restangular, userApiUrl, userApiVersion) {
var restSrv = Restangular.withConfig(function (configSetter) {
configSetter.setBaseUrl(userApiUrl + userApiVersion);
})
return {
getUsers: function () {
return restSrv.all("user").getList();
},
getUsersEx: function (withdept, withrole, withpermission, withsys) {
return restSrv.all("user").customGET("ex", {
"withdept": withdept,
"withrole": withrole,
"withpermission": withpermission,
"withsys": withsys
});
},
setPermission: function (userID,permission) {
return restSrv.one("user", userID).customPUT(permission,$rootScope.currentBusiness.Key + "/permission");
},
getBusiness: function (userID) {
return restSrv.one("user", userID).customGET("business");
},
setProduction: function (userID, info) {
return restSrv.one("user", userID).customPUT(info, "production");
},
update: function (user) {
return restSrv.one("user", user.ID).customPUT(user);
},
create: function (user) {
return restSrv.all("user").post(user);
},
disable: function (id) {
return restSrv.one("user", id).customPUT({}, "disable");
},
enable: function (id) {
return restSrv.one("user", id).customPUT({}, "enable");
},
resetPsw: function (id) {
return restSrv.one("user", id).customPUT({}, "resetpsw");
},
checkAccount: function (account) {
return restSrv.one("user", account).customGET("check");
}
}
});
});
|
const { spawn } = require('child_process');
async function getJsdocs() {
const jsdocCommand = spawn('./node_modules/.bin/jsdoc', [
'./node_modules/lodash/lodash.js',
'-X',
]);
return new Promise((resolve, reject) => {
let jsdocs = '';
jsdocCommand.stdout.on('data', data => {
jsdocs += data;
});
jsdocCommand.stderr.on('data', data => {
reject(data);
});
jsdocCommand.on('close', () => {
resolve(JSON.parse(jsdocs));
});
});
}
module.exports = getJsdocs;
|
import jwt from 'jsonwebtoken';
import User from '../entities/user';
import logger from '../utils/logger';
require('dotenv').config();
export default async (req, res, next) => {
let response;
try {
const authorization = req.header('Authorization');
if (!authorization) {
response = { message: 'Authorization token is invalid', status: false };
logger.error(response);
return res.status(401).json(response);
}
const token = authorization.split(' ')[1];
if (!token) {
response = { message: 'Authorization token is missing', status: false };
logger.error(response);
return res.status(401).json(response);
}
const decoded = await jwt.verify(token, process.env.SECRET_KEY);
const user = await User.findById(decoded.id).select('-password');
if (!user) {
response = { message: 'Failed to authenticate user', status: false };
logger.error(response);
return res.status(401).json(response);
}
req.user = user;
next();
} catch (error) {
response = { message: 'Failed to authenticate user', error: error.message, status: false };
logger.error(response);
return res.status(500).json(response);
}
};
|
var VideoModel = require("../models/videos");
var ThumbnailGenerator = require("video-thumbnail-generator").default;
const fs = require("fs");
const ytdl = require("ytdl-core");
const { getInfo } = require("ytdl-getinfo");
const path = require("path");
var getDimensions = require("get-video-dimensions");
const gm = require("gm");
var async = require("async");
var S3Helper = require("./s3-helper");
var config = require("../config").config;
function YoutubeVideos() {
//if(isLoading){
this.isLoading = false;
this.model = new VideoModel();
//}
}
YoutubeVideos.prototype.download = function() {
var _this = this;
console.log(this.isLoading);
if (!this.isLoading) {
this.model.modelDB.findOne({ status: 0 }, function(err, doc) {
//console.log(doc.youtubeURL);
if (doc) _this.processDownload(doc);
});
}
};
YoutubeVideos.prototype.processDownload = function(doc) {
var _this = this;
//console.log(ThumbnailGenerator);
if (doc.youtubeURL) {
this.isLoading = true;
const url = doc.youtubeURL;
let output = path.resolve(__dirname, "../public/videos");
output += "/" + doc._id + ".mp4";
console.log(
" ---------------------- output ---------------------------- ",
output
);
this.model
.update(doc._id, { status: 1 })
.then(async () => {
console.log(
" ---------------------- update ---------------------------- "
);
try {
const videoInfo = await getInfo(url);
console.log(videoInfo);
var video = ytdl(url, {
quality: "highestvideo",
filter: (format) => format.container === 'mp4'
}).on(
"progress",
async (length, downloaded, totallength) => {
if (downloaded === totallength) {
const tg = new ThumbnailGenerator({
sourcePath: output,
thumbnailPath: path.resolve(
__dirname,
"../public/images/video-thumbnails"
)
});
const thumbsArray = [];
await tg
.generateOneByPercent(10, {
size: "100%",
filename: `${doc._id}_1`
})
.then(th => {
thumbsArray.push(
"/static/images/video-thumbnails/" +
th
);
});
await tg
.generateOneByPercent(50, {
size: "100%",
filename: `${doc._id}_2`
})
.then(th => {
thumbsArray.push(
"/static/images/video-thumbnails/" +
th
);
});
await tg
.generateOneByPercent(90, {
size: "100%",
filename: `${doc._id}_3`
})
.then(th => {
thumbsArray.push(
"/static/images/video-thumbnails/" +
th
);
});
const upload_date = videoInfo.items[0].upload_date;
const year = upload_date.substr(0, 4);
const month = upload_date.substr(4, 2);
const day = upload_date.substr(6, 2);
this.model
.update(doc._id, {
title: videoInfo.items[0].fulltitle,
uploadDate: `${year}-${month}-${day}`,
path:
"/static/videos/" +
doc._id +
".mp4",
thumbnails: thumbsArray,
status: 2
})
.then(result => {
//console.log(res);
});
this.uploadToAWSS3(output, doc._id);
this.isLoading = false;
}
}
);
video.on("error", err => {
console.log(err);
this.isLoading = false;
});
video.pipe(fs.createWriteStream(output));
} catch (err) {
console.log(err);
this.isLoading = false;
}
})
.catch(err => {
console.log(err);
this.isLoading = false;
});
}
this.isLoading = false;
};
YoutubeVideos.prototype.uploadToAWSS3 = function(path, videoId) {
var accessKey = config.AWS_ACCESS_KEY.replace(/(\r\n|\n|\r)/gm, "")
var secretKey = config.AWS_SECRET_ACCESS_KEY.replace(/(\r\n|\n|\r)/gm, "")
var bucketName = config.AWS_S3_BUCKET_NAME.replace(/(\r\n|\n|\r)/gm, "")
console.log(accessKey)
console.log(secretKey)
var S3 = new S3Helper(
{
AWS_ACCESS_KEY: accessKey,
AWS_SECRET_ACCESS_KEY: secretKey
},
bucketName
);
console.log("uploadToAWSS3 method********************************, s3", S3);
S3.upload(path)
.then(url => {
console.log(
"succcess.....uploadToAWSS3 method********** *******",
url
);
this.model
.update(videoId, { path: url })
.then(res => {
fs.unlink(path, err => {
if (err) {
console.log("Error... amazon S3 server", err);
} else {
console.log(" video moved to amazon S3 server ");
}
});
})
.catch(err => {
console.log(err);
});
})
.catch(err => {
console.log("s3 error...", err);
});
};
module.exports = YoutubeVideos;
|
require('./styles/App.scss');
import 'core-js/fn/object/assign'
import React from 'react'
import { render } from 'react-dom'
import {
BrowserRouter as Router,
Route,
} from 'react-router-dom'
import { Provider } from 'react-redux'
import App from './containers/App'
import Home from './containers/home'
import Manage from './containers/manage'
import Company from './containers/company'
import configureStore from './store/configureStore'
// import createBrowserHistory from 'history/createBrowserHistory'
const store = configureStore()
// const customHistory = createBrowserHistory()
// Render the main component into the dom
render(
<Provider store={store}>
<Router>
<div>
<App/>
<Route exact path="/" component={ Home }/>
<Route path="/manage" component={ Manage }/>
<Route path="/company" component={ Company }/>
</div>
</Router>
</Provider>,
document.getElementById('root')
)
|
import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
export default class MyDocument extends Document {
static async getInitialProps (ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render () {
return (
<html lang='en'>
<Head>
<meta name='viewport' content='initial-scale=1.0, width=device-width' />
<link rel="icon" href="/img/logo/logo_mobile.png" type="image/x-icon"/>
<link rel="stylesheet" href="/static/plugins/bootstrap-4.1.1/css/bootstrap.min-v4.3.1.css" type="text/css"/>
<link rel="stylesheet" href="/static/plugins/dzsparallaxer/dzsparallaxer.css"/>
<link rel="stylesheet" href="/static/plugins/dzsparallaxer/dzsscroller/scroller.css"/>
<link rel="stylesheet" href="/static/plugins/dzsparallaxer/advancedscroller/plugin.css"/>
<link rel="stylesheet" href="/static/plugins/nprogress.css"/>
{/* Icons */}
<link rel="stylesheet" href="/static/plugins/icon-line/css/simple-line-icons.css"/>
<link rel="stylesheet" href="/static/plugins/icon-etlinefont/style.css"/>
<link rel="stylesheet" href="/static/plugins/icon-line-pro/style.css"/>
<link rel="stylesheet" href="/static/plugins/icon-hs/style.css"/>
<link rel="stylesheet" href="/static/plugins/themify-icons/themify-icons.css"/>
<link rel="stylesheet" href="/static/plugins/fontawesome/css/font-awesome.min.css" type="text/css" />
<link rel="stylesheet" href="/static/plugins/components.css" type="text/css"/>
<link rel="stylesheet" href="/static/plugins/globals.css" type="text/css"/>
<link rel="stylesheet" href="/static/plugins/animate.min.css" type="text/css" />
{/* <link rel="stylesheet" href="/static/slick.min.css" type="text/css" />*/}
<link rel="stylesheet" href="/static/bg-files.css" type="text/css" />
{/* <link rel="stylesheet" href="/static/styles.css" type="text/css" />*/}
<script src="/static/plugins/jquery/jquery.min-3.2.1.js"></script>
<script src="/static/plugins/bootstrap-4.1.1/js/popper.min.js"></script>
<script src="/static/plugins/bootstrap-4.1.1/js/bootstrap.min.js"></script>
<script src="/static/plugins/plugins/dzsparallaxer/dzsparallaxer.js"></script>
<script src="/static/plugins/dzsparallaxer/dzsscroller/scroller.js"></script>
<script src="/static/plugins/dzsparallaxer/advancedscroller/plugin.js"></script>
</Head>
<body className="">
<Main />
<NextScript />
</body>
</html>
)
}
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { deleteCard } from '../actions/cardActions.js';
const Card = (props) => (
<div className='card'>
<h4>{props.card}<span onClick={() => props.deleteCard(props.categories, props.index1, props.index2)}><i className="fas fa-trash-alt" /></span></h4>
</div>
);
const mapStateToProps = state => ({
categories: state.categories.categories
})
export default connect(mapStateToProps, { deleteCard })(Card);
|
'use strict';
function createModal(target, galleryItem) {
const doc = document.documentElement;
let isImg = false;
if (target.tagName === 'I') {
modal.innerHTML = `
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete image?</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Delete</button>
<button type="button" class="btn btn-secondary">Cancel</button>
</div>
</div>
</div>`;
/* firstElementChild --> тобто внутрішній блок модалки для видалення (modal-dialog)*/
modal.firstElementChild.addEventListener('click', (event) => {
if (event.target.tagName !== 'BUTTON') return;
const btn = event.target;
if (btn.classList.contains('btn-danger')) {
galleryItem.remove();
}
hideModal();
})
} else if (target.tagName === 'IMG') {
const src = target.src; //.match(/\i\m\g\/.+/i)
modal.innerHTML = '<img src="" alt="">';
modal.firstElementChild.src = src;
isImg = true;
}
modal.style.display = 'block';
overlay.style.display = 'block';
body.style.overflow = 'hidden';
modal.style.left = (doc.clientWidth - (isImg ? modal.firstElementChild.offsetWidth : modal.offsetWidth)) / 2 + 'px';
modal.style.top = (doc.clientHeight - (isImg ? modal.firstElementChild.offsetHeight : modal.offsetHeight)) / 2 + 'px';
}
function hideModal() {
modal.style.display = '';
overlay.style.display = '';
body.style.overflow = '';
}
|
const apiKey = "439a231ab42d75a3d00292db922838ef-us1";
const server = "us1";
const listId = "381eb46b2a";
module.exports = {apiKey, server, listId}; |
import React, { useState, useEffect } from 'react'
import { Select, Button } from 'antd';
import _ from 'lodash';
import axios from 'axios';
const constants = require("../config/constants");
const { Option } = Select;
const AdminDashboard = () => {
const [ sourceList, setSourceList ] = useState([])
const [ isApiLoading, setIsApiLoading ] = useState(false)
const newsSourceList = constants.newsSourceList
useEffect(() => {
setIsApiLoading(true)
axios.get('http://localhost:5000/api/user/get-selected-source-list')
.then(res => {
setSourceList(res.data.data[0].sourcesId)
setIsApiLoading(false)
})
.catch(err => {
console.log(err)
setIsApiLoading(false)
})
}, [])
const newsSourceName = _.flatMap(newsSourceList, (value) => (
<Option key={value.id.toString(36)}>{value.name.toString(36)}</Option>
))
function handleChange(value) {
setSourceList(value)
}
function updateSourceList() {
setIsApiLoading(true)
axios.put('http://localhost:5000/api/user/set-selected-source-list', sourceList)
.then(res => {
setIsApiLoading(false)
})
.catch(err => {
console.log(err)
setIsApiLoading(false)
})
}
return (
<div className="container">
<Select
mode="multiple"
allowClear
style={{ width: '100%' }}
placeholder="Please select"
onChange={handleChange}
disabled={isApiLoading}
value={sourceList}
>
{newsSourceName}
</Select>
<Button type="primary" onClick={updateSourceList}>Update</Button>
</div>
);
}
export default AdminDashboard;
|
'use strict';
angular.module('core.client', ['ngResource']);
|
import { connect } from 'react-redux'
import Mask from '../components/Mask'
const mapStateToProps = (state, ownProps) => ({
isShowPop:state.showPopReducer.isShowPop
})
export default connect(mapStateToProps)(Mask) |
import React from "react";
import { Table, Card, Input, InputGroupAddon, Button, InputGroup, Row } from "reactstrap";
import User from "./User";
import { NotificationContainer } from "react-notifications";
import { getUsers, getCurrentUser } from "../../services/appuser.service";
import styles from "./AppUserList.module.css";
class AppUserList extends React.Component {
state = {
pagedItemResponse: null,
pageIndex: 0,
pageSize: 10,
totalCount: 0,
totalPages: 0,
search: null,
userName: ""
};
componentDidMount() {
this.loadPage();
getCurrentUser().then(response => {
const res = response.data.item.firstName;
this.setState({ userName: res });
});
}
loadPage = () => {
this.setState({ pagedItemResponse: null });
const { pageIndex, search } = this.state;
const pageSize = 40;
const req = { pageIndex, pageSize, search };
getUsers(req).then(response => {
this.setState({ pagedItemResponse: response.data.item.pagedItems });
});
};
searchChange = e => {
const { value } = e.target;
this.setState({ search: value });
};
backToHomePage = e => {
this.props.history.push("/admin/tenantAgencyHomepage");
};
render() {
const appUsers = this.state.pagedItemResponse;
return (
<React.Fragment>
<React.Fragment>
<h1>{this.state.userName}</h1>
<h2 className="content-header">User Roles</h2>
<InputGroup>
<Input placeholder="Search Name.." className="col-md-3" onChange={this.searchChange} />
<InputGroupAddon addonType="append">
<Button onClick={this.loadPage}>
<i className="fa fa-search" />
</Button>
</InputGroupAddon>
</InputGroup>
</React.Fragment>
<Card className="px-2 py-2" style={{ overflow: "auto" }}>
<Row>
<Table className={"px-2 py-2 " + styles.table}>
<thead>
<tr style={{ backgroundColor: "#04b9b6" }} className="text-light">
<th>Name</th>
<th>Email</th>
<th className="text-center">Admin</th>
<th className="text-center">Agency Rep</th>
<th className="text-center">Business Owner</th>
</tr>
</thead>
<tbody>
{appUsers ? (
<>
{appUsers.map(appUsers => (
<User appUsers={appUsers} key={appUsers.id} />
))}
</>
) : (
<tr>{null}</tr>
)}
</tbody>
</Table>
</Row>
</Card>
<Button color="primary" onClick={this.backToHomePage} block>
Back
</Button>
</React.Fragment>
);
}
}
export default AppUserList;
|
import React, { Component } from 'react';
import './App.css';
class RowDone extends Component {
render() {
return (
<tr className="table-success">
<td style={{textAlign: 'center'}}>{this.props.index+1}</td>
<td style={{textAlign: 'center'}}>{this.props.task.title}</td>
<td onClick={() => this.props.click} style={{textAlign: 'center'}}> <i class="material-icons">done</i> </td>
</tr>
)
}
}
class RowTodo extends Component {
render() {
return (
<tr className="table-danger">
<td style={{textAlign: 'center'}}>{this.props.index+1}</td>
<td style={{textAlign: 'center'}}>{this.props.task.title}</td>
<td onClick={() => this.props.click} style={{textAlign: 'center'}}> <i class="material-icons">clear</i> </td>
</tr>
)
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = (
JSON.parse(localStorage.getItem("todolist")) ||
{
"tasks": [],
}
)
window.onbeforeunload = () => this.saveState()
}
saveState(){
localStorage.setItem("todolist", JSON.stringify(this.state))
}
addTask(){
let taskTitle = prompt("Enter title")
this.setState((oldState) => ({
tasks: [...oldState.tasks, {title: taskTitle, done: false}]
}))
}
removeTask(){
this.setState((oldState) => ({
tasks: oldState.tasks.slice(0,oldState.tasks.length-1)
}))
}
modifyTask(i){
// let i = prompt("Enter task index")-1
this.setState((oldState) => ({
tasks: oldState.tasks.slice(0,i).concat({title: oldState.tasks[i].title, done: !oldState.tasks[i].done}, oldState.tasks.slice(i+1,oldState.tasks.length))
}))
}
deleteTask(i){
this.setState((oldState) => {
return {
...oldState,
tasks: oldState.tasks.slice(0,i).concat(oldState.tasks.slice(i+1,oldState.tasks.length)),
}
})
}
modifyTitle(i){
let newTitle = prompt("Enter new title")
this.setState((oldState) => ({
tasks: oldState.tasks.slice(0,i).concat({title: newTitle, done: oldState.tasks[i].done}, oldState.tasks.slice(i+1,oldState.tasks.length))
}))
}
new(){
this.setState((oldState) => ({
tasks: [],
}))
}
render() {
return (
<main className="container">
<div className="jumbotron" style={{height: 160, padding: 30}}>
<h1 className="display-4" style={{textAlign: 'center'}}>ToDo List</h1>
<p class="lead" style={{textAlign: 'center'}}>Number off tasks: {this.state.tasks.length}</p>
</div>
<p></p>
<table className="table">
<thead className="thead-dark">
<tr>
<th scope="col" style={{textAlign: 'center'}}>Delete?</th>
<th scope="col" style={{textAlign: 'center'}}>#</th>
<th scope="col" style={{textAlign: 'center'}}>Title</th>
<th scope="col" style={{textAlign: 'center'}}>Done?</th>
</tr>
</thead>
{this.state.tasks.map((task, i) => (
<tbody>
{task.done ? (
<tr className="table-success">
<td style={{textAlign: 'center'}} ><button onClick={() => this.deleteTask(i)} type="button" className="btn btn-danger" > X </button></td>
<td style={{textAlign: 'center'}}> {i+1} </td>
<td onClick={() => this.modifyTitle(i)} style={{textAlign: 'center'}}>{task.title}</td>
<td onClick={() => this.modifyTask(i)} style={{textAlign: 'center'}}> <i class="material-icons">done</i> </td>
</tr>
) : (
<tr className="table-danger">
<td style={{textAlign: 'center'}} ><button onClick={() => this.deleteTask(i)} type="button" className="btn btn-danger" > X </button></td>
<td style={{textAlign: 'center'}}> {i+1} </td>
<td onClick={() => this.modifyTitle(i)} style={{textAlign: 'center'}}>{task.title}</td>
<td onClick={() => this.modifyTask(i)} style={{textAlign: 'center'}}> <i class="material-icons">clear</i> </td>
</tr>
)}
</tbody>
))}
</table>
<div class="btn-group" role="group" aria-label="Basic example" style={{width:'100%'}} >
<button type="button" class="btn btn-success" style={{width: '50%'}} onClick={
() => this.addTask()
}>Add</button>
<button type="button" class="btn btn-danger" style={{width: '50%'}} onClick={
() => this.new()
}>Delete All</button>
</div>
</main>
);
}
}
// <RowDone task={task} index={i} click={this.modifyTask(i)} />
export default App;
// <tr className="table-danger">
// <td style={{textAlign: 'center', height: 15}}>{i+1}</td>
// <td style={{textAlign: 'center'}}>{task.title}</td>
// <td className="done" onClick={() => this.modifyTask(i)} style={{textAlign: 'center'}}> <i class="material-icons">clear</i> </td>
// </tr>
// <tr className="table-success">
// <td style={{textAlign: 'center'}}>{i+1}</td>
// <td style={{textAlign: 'center'}}>{task.title}</td>
// <td className="done" onClick={() => this.modifyTask(i)} style={{textAlign: 'center'}}> <i class="material-icons">done</i> </td>
// </tr>
// <button type="button" class="btn btn-dark" style={{width: '34%'}} onClick={
// () => this.new()
// }>New List</button> |
var client = new Dropbox.Client({
key: 'ydspoohcpyj0lyo'
});
client.authenticate(function(error, client) {
if (error) {
// Replace with a call to your own error-handling code.
//
// Don't forget to return from the callback, so you don't execute the code
// that assumes everything went well.
console.log(error);
}
// Replace with a call to your own application code.
//
// The user authorized your app, and everything went well.
// client is a Dropbox.Client instance that you can use to make API calls.
console.log('gg');
});
|
var program = require('commander');
program
.version('0.0.1')
.usage('<word>')
.parse(process.argv);
var thesaurus = require("thesaurus");
var word = program.args[0];
var reg = /^[a-z]+$/;
/*if (thesaurus.find(word).length > 0) console.log("yes");
else console.log("no");*/
var syns = thesaurus.find(word);
console.log(syns);
syns.forEach(function(syn) {
// if (reg.test(syn)) console.log(syn);
});
|
const Augur = require("augurbot"),
u = require("../utils/utils");
const Module = new Augur.Module()
.addCommand({name: "help",
description: "Get a list of available commands or more indepth info about a single command.",
syntax: "[command name]",
aliases: ["commands"],
process: async (msg, suffix) => {
try {
msg.react("👌");
u.clean(msg);
const perPage = 20;
let prefix = Module.config.prefix;
let commands = Module.client.commands.filter(c => c.permissions(msg) && c.enabled);
let embed = u.embed()
.setURL("https://my.ldsgamers.com/commands")
.setThumbnail(msg.client.user.displayAvatarURL({size: 128}));
if (!suffix) { // FULL HELP
commands = commands.filter(c => !c.hidden);
embed
.setTitle(msg.client.user.username + " Commands" + (msg.guild ? ` in ${msg.guild.name}.` : "."))
.setDescription(`You have access to the following commands. For more info, type \`${prefix}help <command>\`.`)
.setFooter(`Page 1 of ${Math.ceil(commands.size / perPage)}`);
let categories = commands
.filter(c => c.category != "General")
.map(c => c.category)
.reduce((a, c, i, all) => ((all.indexOf(c) == i) ? a.concat(c) : a), [])
.sort();
categories.unshift("General");
let i = 1;
for (let category of categories) {
for (let [name, command] of commands.filter(c => c.category == category).sort((a, b) => a.name.localeCompare(b.name))) {
embed.addField(`[${category}] ${prefix}${command.name} ${command.syntax}`.trim(), command.description || "*No Description Available*");
if (++i % perPage == 1) {
try {
await msg.author.send({embed});
} catch(e) {
msg.channel.send("I couldn't send you a DM. Make sure that `Allow direct messages from server members` is enabled under the privacy settings, and that I'm not blocked.").then(u.clean);
return;
}
embed = u.embed().setTitle(msg.client.user.username + " Commands" + (msg.guild ? ` in ${msg.guild.name}.` : ".") + " (Cont.)")
.setURL("https://my.ldsgamers.com/commands")
.setDescription(`You have access to the following commands. For more info, type \`${prefix}help <command>\`.`)
.setFooter(`Page ${Math.ceil(i / perPage)} of ${Math.ceil(commands.size / perPage)}`);
}
}
}
try {
if (embed.fields.length > 0)
await msg.author.send({embed});
} catch(e) {
msg.channel.send("I couldn't send you a DM. Make sure that `Allow direct messages from server members` is enabled under the privacy settings, and that I'm not blocked.").then(u.clean);
return;
}
} else { // SINGLE COMMAND HELP
suffix = suffix.toLowerCase();
let command = null;
if (commands.has(suffix)) command = commands.get(suffix);
else if (Module.client.commands.aliases.has(suffix)) command = Module.client.commands.aliases.get(suffix);
if (command) {
embed
.setTitle(prefix + command.name + " help")
.setDescription(command.info)
.addField("Category", command.category)
.addField("Usage", prefix + command.name + " " + command.syntax);
if (command.aliases.length > 0) embed.addField("Aliases", command.aliases.map(a => `!${a}`).join(", "));
try {
await msg.author.send({embed});
} catch(e) {
msg.channel.send("I couldn't send you a DM. Make sure that `Allow direct messages from server members` is enabled under the privacy settings, and that I'm not blocked.").then(u.clean);
return;
}
} else {
msg.reply("I don't have a command by that name.").then(u.clean);
}
}
} catch(error) { u.errorHandler(error, msg); }
}
});
module.exports = Module;
|
console.log("hi")
function begin() {
// var birth = document.getElementById("birthDate").value;
//
//
//
//
// var birth = new Date(birth); //Make the Form value into a JavaScript date
// var years = new Date().getFullYear() - birth.getFullYear();
//
// var birthMilli = birth.getTime(); //Turn into Milliseconds
var today = new Date().getTime(); //Get today into milliseconds
var total = today - birthMilli; //Difference
var grade = years - 5 //Gets their grade
var total = Math.floor((total / 1000 / 60 / 60 / 24)); //Convert into days
var graduation = birth.getFullYear() + 17;
if (total < 0) {
total = "Please input a valid date"
}
else if (grade == 0) {
total = `You are ${total} days old and most likely in kindergarten. You will probably graduate in ${graduation}.`
}
else if (years > 0 && years < 18) {
if(grade < 0){
console.log("OYUNG");
}
total = `You are ${total} days old and most likely in grade ${grade}. You will probably graduate in ${graduation}.`
}
else {
total = `You are ${total} days old and most likely graduated in ${graduation}.`
}
document.getElementById("total").innerHTML = total;
}
|
/**
* 汇总工具类
* @param opt
* @returns {summaryUtils}
*/
function summaryUtils(opt){
//汇总类型:1.按货号汇总;2.按货号色码汇总
this.repType = opt.repType;
//组装查询参数
this.constructQryParamFunc = opt.constructQryParamFunc;
//查询url
this.postUrl = opt.postUrl;
//标题
this.repTitle = opt.repTitle;
//是否销售单
this.isSell = opt.isSell;
}
summaryUtils.prototype = {
summary : function(){
var colNames= [];
var colModel = [];
var cstQryParamFunc = this.constructQryParamFunc;
var postData = cstQryParamFunc ? cstQryParamFunc() : {};
var repType = this.repType;
postData.repType = repType;
if(repType == 1){
// 按货号汇总
colNames = ["货品号", "货品名称", "单位","总数量"];
colModel = [{
name : "goodNo",
width : 100,
align : "center"
}, {
name : "goodName",
width : 90
}, {
name : "goodUnit",
width : 80,
align : "right"
}, {
name : "num",
width : 60,
align : "right"
}];
}else if(repType == 2){
// 按货号、颜色汇总
colNames = ["货品号", "货品名称", "单位","色码","颜色","S", "M","L","XL","XXL","XXXL","XXXX","总数量"];
colModel = [{
name : "goodNo",
width : 100,
align : "center"
}, {
name : "goodName",
width : 90
}, {
name : "goodUnit",
width : 80,
align : "right"
}, {
name : "colorNo",
width : 80,
align : "right"
}, {
name : "colorName",
width : 80,
align : "right"
}, {
name : "num1",
width : 40,
align : "right"
}, {
name : "num2",
width : 40,
align : "right"
}, {
name : "num3",
width : 40,
align : "right"
}, {
name : "num4",
width : 40,
align : "right"
}, {
name : "num5",
width : 40,
align : "right"
}, {
name : "num6",
width : 40,
align : "right"
}, {
name : "num7",
width : 40,
align : "right"
}, {
name : "num",
width : 60,
align : "right"
}];
}
if(this.isSell){
//如为销售开票
colNames.push("总金额");
colModel.push({
name : "total",
width : 60,
align : "right"
});
}
$("#repList").GridUnload();
$("#repList").jqGrid(
{
url : this.postUrl,
datatype : "json",
postData:postData,
colNames : colNames,
colModel : colModel,
ajaxSelectOptions :{},
pager : "#repPager",
rowNum : 27,
rowList : [ 20, 27, 30 ],
height : 250,
// toolbar:[true,"top"],
sortname : "upNum",
sortorder : "desc",
viewrecords : true,
gridview : true,
autoencode : true,
userDataOnFooter : true,
footerrow : true,
caption : "查询结果",
jsonReader : {
root : "rows", // json中代表实际模型数据的入口
page : "currPage", // json中代表当前页码的数据
total : "totalPage", // json中代表页码总数的数据
records : "totalRecords", // json中代表数据行总数的数据
repeatitems : false,
id : "0"
}
});
$("#repList").jqGrid("setGridParam",{page:1}).trigger("reloadGrid");
var title = this.repTitle;
//加入窗口标题
$('#repWin').window({
title : title
});
//加入表格标题
$("#repGridTitle").remove();
var gridWidth = $("#gbox_repList").width();
$("#gbox_repList").before("<div id='repGridTitle' style='font-size:20px;font-family: SimHei;font-weight: bold;text-align:center;width:"+gridWidth+"px;'>"+title+"</div>");
$('#repWin').window('open');
}
}; |
//Quantity of owned currencies
//Insert values from cloud here
let btcOwned = 0.8;
let ltcOwned = 6;
let ethOwned = 5;
//Rates for owned currencies -> Cost of 1 unit
//This also needs to updated dynamically
let btcRate = 7121.16;
let ltcRate = 63.89;
let ethRate = 328.50;
//TRANSACTIONS
//Array to store transactions. Transactions can be added using .push()
let transactionsArray = [];
//A transaction object to temporarily store a transaction and its details befor being added to the array
var transaction = {
counter:1,
currency:'BTC',
amount:2,
type:'Bought'
};
//Create a new transaction and add to the transactions array
function newTransaction(currency, amount, type) {
transaction.counter++;
transaction.currency = currency;
transaction.amount = amount;
transaction.type = type;
transactionsArray.push(transaction);
}
newTransaction('ETH', 4.5, 'Sold');
console.log(transactionsArray.pop(0));
console.log(transactionsArray.pop(1));
function updateOwnedCurrencies()
{
document.getElementById('btcValue').innerHTML = "$"+(btcOwned*btcRate).toFixed(2);
document.getElementById('ltcValue').innerHTML = "$"+(ltcOwned*ltcRate).toFixed(2);
document.getElementById('ethValue').innerHTML = "$"+(ethOwned*ethRate).toFixed(2);
}
function processTransaction(currency, type, amount)
{
let transactionHTMLelement = "order";
transactionHTMLelement = transactionHTMLelement + transaction.counter.toString(); //getting each transaction element
document.getElementById(transactionHTMLelement).innerHTML = transaction.counter + ". " + transaction.type + " " + transaction.currency + ": " + transaction.amount;
transaction.counter++;
}
|
'use strict';
/**
* Route Mappings
* (sails.config.routes)
*
* Your routes map URLs to views and controllers.
*
* If Sails receives a URL that doesn't match any of the routes below,
* it will check for matching files (images, scripts, stylesheets, etc.)
* in your assets directory. e.g. `http://localhost:1337/images/foo.jpg`
* might match an image file: `/assets/images/foo.jpg`
*
* Finally, if those don't match either, the default 404 handler is triggered.
* See `config/404.js` to adjust your app's 404 logic.
*
* Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies
* flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or
* CoffeeScript for the front-end.
*
* For more information on configuring custom routes, check out:
* http://sailsjs.org/#/documentation/concepts/Routes/RouteTargetSyntax.html
*/
module.exports.routes = {
// See https://github.com/balderdashy/sails/issues/2062
'OPTIONS /*': function(req, res) {
res.send(200);
},
// Authentication routes
'GET /keyword-vs-searchterm': 'https://ppcentourage.forumbee.com/t/k966dk/the-difference-between-keywords-and-search-terms',
'GET /profitmargin': 'https://ppcentourage.forumbee.com/t/q568bf/how-to-determine-your-acos-profit-zone-and-profit-margins',
'GET /negativekeywords': 'https://ppcentourage.forumbee.com/t/m2688x/negative-keywordshow-to-drastically-reduce-needless-ad-spend',
'/logout': 'AuthController.logout',
'POST /login': 'AuthController.callback',
'POST /forgot': 'ForgotController.sendmail',
'POST /pchange': 'ForgotController.pchange',
'POST /echange': 'ForgotController.echange',
'GET /chgpwd': 'ForgotController.chgpwd',
'POST /signup': 'SettingsController.signup',
'POST /login/:action': 'AuthController.callback',
'POST /auth/local': 'AuthController.callback',
'POST /auth/local/:action': 'AuthController.callback',
'post /api/uploads':"SettingsController.upload",
'post /api/uploads1':"SettingsController.upload1",
'post /api/upload_keywords': "CampaignController.upload_keywords",
'post /api/uploadphoto':"ProductController.upload"
};
|
/**
* Recurring loop logic
*/
/*global define */
define(
['models/dom', 'models/loop', 'models/storage', 'controllers/input', 'controllers/layering'],
function (dom, loopModel, storage, input, layering) {
'use strict';
var _private = {
animate: function () {
loop.draw();
window.requestAnimationFrame(_private.animate);
}
};
var loop = {
/**
* Sets up the primary loop logic, should only be run once
*/
init: function () {
_private.animate();
},
/**
* Infinitely recurring draw loop. Be extremely careful as to what you put in here
*/
draw: function () {
loopModel.delta = Date.now - loopModel.deltaPrev;
// Graveyard should always keep running to prevent artifact buildup
if (!loopModel.pause) {
dom.ctx.clearRect(0, 0, dom.canvas.width, dom.canvas.height);
input.monitor();
for (var ent = 0; ent < storage.entities.length; ent++) {
storage.entities[ent].update();
storage.entities[ent].draw();
}
layering.sortLayers();
}
if (storage.graveyard.length > 0) {
var deceased;
// Remove the entity from the loop
while (storage.graveyard.length > 0) {
deceased = storage.graveyard.pop();
for (ent = 0; ent < storage.entities.length; ent++) {
if (storage.entities[ent] === deceased) {
storage.entities.splice(ent, 1);
break;
}
}
}
}
loopModel.deltaPrev = Date.now;
}
};
return loop;
}); |
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function editObjetivo( event ) {
$("#store-objetivo").css("display","none");
$("#update-objetivo").css("display","inline-block");
$("#objetivo-id").val( $(this).data('objetivo-id') );
$("#objetivo").val( $(this).data('objetivo') );
$("#plan-objetivo").modal();
}
function updateObjetivo( event ) {
var objetivo = $("#objetivo").val();
var objetivo_id = $("#objetivo-id").val();
var data = { 'objetivo_id': objetivo_id, 'objetivo': objetivo };
$.post("/planc/updateobjetivo", data)
.done(function(response, status) {
$( '#objetivo-' + objetivo_id ).text("OBJETIVO: " + objetivo);
$( '#button-' + objetivo_id ).data('objetivo', objetivo);
});
}
function newActividad( event ) {
$("#store-actividad").css("display","inline-block");
$("#update-actividad").css("display","none");
$("#objetivo-id").val( $(this).data('objetivo-id') );
$('textarea').val("");
$('input[type=text]').val("");
$('input[type=checkbox]').prop('checked', false);
$("#plan-actividad").modal();
}
function storeActividad( event ) {
var objetivo_id = $("#objetivo-id").val();
var actividad = $("#actividad").val();
var uni_med = $("#uni_med").val();
var meta = $("#meta").val();
if($("#mes1").prop('checked')) { var mes1 = 1; } else { var mes1 = 0; }
if($("#mes2").prop('checked')) { var mes2 = 1; } else { var mes2 = 0; }
if($("#mes3").prop('checked')) { var mes3 = 1; } else { var mes3 = 0; }
if($("#mes4").prop('checked')) { var mes4 = 1; } else { var mes4 = 0; }
if($("#mes5").prop('checked')) { var mes5 = 1; } else { var mes5 = 0; }
var responsable = $("#responsable").val();
var data = { 'objetivo_id': objetivo_id, 'actividad': actividad, 'uni_med': uni_med, 'meta': meta, 'mes1': mes1, 'mes2': mes2, 'mes3': mes3, 'mes4': mes4, 'mes5': mes5, 'responsable': responsable };
$.post("/planc/storeactividad", data)
.done(function(response, status) {
$( "#tbody-" + objetivo_id ).append( response );
$(".edit-actividad").on( "click", editActividad );
});
}
function editActividad( event ) {
$("#store-actividad").css("display","none");
$("#update-actividad").css("display","inline-block");
$('input[type=checkbox]').prop('checked', false);
$("#actividad-id").val( $(this).data('actividad-id') );
var data = { 'actividad_id': $(this).data('actividad-id') };
$.post("/planc/getactividad", data, 'json')
.done(function(response, status) {
$("#actividad").val(response.actividad);
$("#uni_med").val(response.uni_med);
$("#meta").val(response.meta);
if(response.mes1 == '1') { $("#mes1").prop('checked', true); }
if(response.mes2 == '1') { $("#mes2").prop('checked', true); }
if(response.mes3 == '1') { $("#mes3").prop('checked', true); }
if(response.mes4 == '1') { $("#mes4").prop('checked', true); }
if(response.mes5 == '1') { $("#mes5").prop('checked', true); }
$("#responsable").val(response.responsable);
});
$("#plan-actividad").modal();
}
function updateActividad( event ) {
var actividad_id = $("#actividad-id").val();
var actividad = $("#actividad").val();
var uni_med = $("#uni_med").val();
var meta = $("#meta").val();
if($("#mes1").prop('checked')) { var mes1 = 1; } else { var mes1 = 0; }
if($("#mes2").prop('checked')) { var mes2 = 1; } else { var mes2 = 0; }
if($("#mes3").prop('checked')) { var mes3 = 1; } else { var mes3 = 0; }
if($("#mes4").prop('checked')) { var mes4 = 1; } else { var mes4 = 0; }
if($("#mes5").prop('checked')) { var mes5 = 1; } else { var mes5 = 0; }
var responsable = $("#responsable").val();
var data = { 'actividad_id': actividad_id, 'actividad': actividad, 'uni_med': uni_med, 'meta': meta, 'mes1': mes1, 'mes2': mes2, 'mes3': mes3, 'mes4': mes4, 'mes5': mes5, 'responsable': responsable };
$.post("/planc/updateactividad", data)
.done(function(response, status) {
$( '#tr-' + actividad_id ).html( response );
$(".edit-actividad").on( "click", editActividad );
});
}
$(".edit-objetivo").on( "click", editObjetivo );
$("#update-objetivo").on( "click", updateObjetivo );
$(".new-actividad").on( "click", newActividad );
$("#store-actividad").on( "click", storeActividad );
$(".edit-actividad").on( "click", editActividad );
$("#update-actividad").on( "click", updateActividad );
}); |
export { default } from "./rtg"
|
import { renderString } from '../../src/index';
describe(`Enforce HTML escaping. This will probably double escape variables.`, () => {
it(`unnamed case 0`, () => {
const html = renderString(`{% set escape_string = "<div>This markup is printed as text</div>" %}
{{ escape_string|forceescape }}
`);
});
}); |
const mongoose = require('mongoose');
const { Schema } = mongoose;
const answerSchema = new Schema({
date: Date,
answer: [ Number ],
rating: Number,
_user: { type: Schema.Types.ObjectId, ref: 'User' }
});
//
mongoose.model('answers', answerSchema);
module.exports = answerSchema; |
import React from 'react';
import { Link } from 'react-router-dom';
import { FaChevronRight } from 'react-icons/fa';
// Components
import Li from '../../HtmlTags/Li';
const MenuItems = ({ path, title, setActiveMenu }) => {
return (
<>
<div
className='menu_link'
onClick={() => (!path ? setActiveMenu(title) : '')}
>
{path ? (
<Li text={<Link to={path}>{title}</Link>} />
) : (
<Li text={title} />
)}
<FaChevronRight />
</div>
</>
);
};
export default MenuItems;
|
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { CustomSelect } from "components/Forms/CustomSelect";
import logo from "assets/logo.svg";
import i18n from "i18n";
import * as path from "../../constants/routes";
import "./style.scss";
const NavBar = () => {
const [language, setLanguage] = useState("en");
i18n.changeLanguage(language);
const handleLanguageChange = value => {
setLanguage(value);
i18n.changeLanguage(language);
};
const routes = [
{ id: "1", title: "Contact us", path: path.CONTACT_US, spa: true },
{ id: "2", title: "Cookie Policy", path: path.COOKIE_POLICY },
{ id: "3", title: "Privacy Policy", path: path.PRIVACY_POLICY },
{ id: "4", title: "Terms and Conditions", path: path.TERMS_AND_CONDITIONS },
{ id: "5", title: "FAQ", path: path.FAQ }
];
const languageOptions = [
{ key: "en", value: "en", text: "EN" },
{ key: "ru", value: "ru", text: "RU" }
];
return (
<div className="d-flex justify-content-between align-items-center text-center text-white pt-3 auth-navbar">
<div>
<img src={logo} alt="" />
</div>
<div>
{routes.map(route =>
route.spa ? (
<Link key={route.id} to={route.path} className="px-3">
{route.title}
</Link>
) : (
<a
key={route.id}
target="_blank"
rel="noopener noreferrer"
href={route.path}
className="px-3"
>
{route.title}
</a>
)
)}
</div>
<div>
<CustomSelect
value={language}
onChange={handleLanguageChange}
options={languageOptions}
className="language"
form={{
touched: [],
errors: []
}}
field={{
name: ""
}}
icon="chevron down"
/>
</div>
</div>
);
};
export default NavBar;
|
import React from 'react';
import {Link} from 'react-router-dom';
import TextEditorHeader from './TextEditorHeader';
import TextEditorToolBar from './TextEditorToolBar';
class TextEditor extends React.Component {
render() {
return (
<div>
<TextEditorHeader/>
<TextEditorToolBar/>
</div>
);
}
}
export default TextEditor |
angular.module('focus.models.phonenumber', ['ngResource'])
.factory('phoneNumberModel', [
'$resource', function($resource) {
return $resource('/api/phonenumber/:id', { id: '@Id' });
}
]); |
const axios = require('axios');
const db = require('../db/models');
const MAX_REQUESTS = 100000;
const RESULTS_PER_REQUEST = 100;
let start = 0;
const getGames = async () => {
for (let i = 0; i < MAX_REQUESTS; i += 1) {
console.time('request ' + i)
const results = await axios.get(`https://games.roblox.com/v1/games/list?model.startRows=${start}&model.maxRows=${RESULTS_PER_REQUEST}`)
if (!results.data.games || !results.data.games.length) {
console.log('End of paging.');
return;
}
for (let j = 0; j < results.data.games.length; j++) {
const result = results.data.games[j];
const game = {
name: result.name,
placeId: result.placeId,
universeId: result.universeId,
creatorName: result.creatorName,
creatorId: result.creatorId,
upVotes: result.totalUpVotes,
downVotes: result.totalDownVotes,
imageToken: result.imageToken,
url: `https://www.roblox.com/games/${result.placeId}/${result.name}`
};
// const place = await getGameData(game)
// game.description = place.data.description;
// game.visits = place.data.visits;
// game.updatedAt = place.data.updated;
// game.createdAt = place.data.created;
try {
db.game.upsert(game);
} catch (err) {
console.error(err);
console.log(result);
}
}
console.timeEnd('request ' + i)
start += RESULTS_PER_REQUEST;
}
}
const getGameData = (game) => {
return axios.get(`https://games.roblox.com/v1/games/${game.universeId}`)
}
getGames();
|
class DbContextConfig{
setContextDb(data) {
return localStorage.setItem('products', JSON.stringify(data))
}
getContextData(){
return JSON.parse(localStorage.getItem('products'))
}
}
class IdGenerate {
static generateId(storage) {
if(!storage) return 1
return storage.length + 1
}
}
class Products {
context = null
storageSet = []
constructor(){
this.context = new DbContextConfig()
}
showProducts(){
let products = this.context.getContextData()
if(!products) return false
return products.map((index) => {
return index
})
}
insertProduct(productParams){
let product = this.context.getContextData()
if(this.checkExistentProduct(productParams))
return { state: 0, message: 'This product exist in stock' }
if(!product) {
this.storageSet.push({
id: IdGenerate.generateId(product),
...productParams
})
}else {
this.storageSet.push(
...product,
{
id: IdGenerate.generateId(product),
...productParams
}
)
}
return (!this.context.setContextDb(this.storageSet)) ? 'Successuly!' : 'ERROR!'
}
updateProduct(productParams){
let product = this.context.getContextData()
this.storageSet.push(...product)
let index = this.storageSet.findIndex((item) => item.id == productParams.id)
this.storageSet[index] = productParams
localStorage.clear()
this.context.setContextDb(this.storageSet)
location.reload()
}
deleteProduct(id) {
let product = this.context.getContextData()
this.storageSet.push(...product)
let productIndex = this.storageSet.findIndex((item) => item.id == id)
const remainingItems = this.storageSet.filter((item, index) => {
return index !== productIndex
})
localStorage.clear()
this.context.setContextDb(remainingItems)
location.reload()
}
checkExistentProduct(product){
let check = []
let productFitlter = this.context.getContextData()
if(productFitlter) {
check = productFitlter.filter(
(item) => item.name == product.name
)
}
return (check.length > 0) ? true : false
}
}
// const products = [
// { id: 1, name: 'Banana', quantity: 1, price: 120.00, total: 120.00 },
// { id: 2, name: 'Ananas', quantity: 1, price: 20.00, total: 20.00 },
// { id: 3, name: 'Batata', quantity: 1, price: 10.00, total: 10.00 }
// ]
// let context = new DbContextConfig()
// context.setContextDb(products)
// let product = new Products()
// let message = product.insertProduct({ name: 'Ananas', quantity: 1, price: 120.00, total: 120.00})
// console.log(message)
|
const jwt = require('jsonwebtoken')
const bcryptjs = require('bcryptjs')
const conexion = require('../database/db')
const {promisify} = require('util')
const { error } = require('console')
//INSERT
exports.registrar = async (req,res)=>{
try {
const full_name = req.body.full_name
const gender = req.body.gender
const email = req.body.email
const pwd = req.body.pwd
const profile = req.body.profile
let pwdHash = await bcryptjs.hash(pwd, 8)
//
conexion.query('insert into feliperod_usuario set ?',
{
full_name:full_name,
gender:gender,
email:email,
pwd:pwdHash,
profile:profile
}, (err, results)=>{
if (err) {
console.log(err)
res.setHeader('Content-Type', 'application/json')
res.writeHead(400)
res.end('{"Estado":"400","Mensaje":"Usuario no fue ingresado."}')
}else{
console.log('Usuario Registrado')
res.setHeader('Content-Type', 'application/json')
res.writeHead(200)
res.end('{"Estado":"200","Mensaje":"Usuario ingresado correctamente."}')
}
})
} catch (error) {
console.log(error)
}
//ok
//console.log(pwdHash)
//console.log(full_name + gender + email + pwd + profile)
}
|
import React from 'react';
const UsersList = (props) => {
return (
<div>
<h1> Found user list: </h1>
<div className='user-card-container'>
{
props.usersData.map((user, index) => (
<div key={index} className="user-card">
<h3>{user.firstName} {user.lastName}</h3>
<img src={user.img}/>
</div>
))
}
</div>
</div>
)
}
export default UsersList;
|
/*
* 唯一的参数是 ID,ID 不重复,那 URL 即是 myservice/username?id=some-unique-id
如果请求错误或者失败需要有报错或错误提示。
*/
//GET请求
//jq的
$.ajax('myservice/username', {
data: {
id: 'some-unique-id'
}
})
.then(
function success(name) {
alert('用户名:' + name);
},
function fail(data, status) {
alert('请求失败,返回状态:' + status);
}
);
//原生的
var xhr = new XMLHttpRequest();//IE 6 则需要把 new XMLHttpRequest() 替换成 new ActiveXObject("MSXML2.XMLHTTP.3.0")
xhr.open('GET','myservice/username?id=some-unique-id');
xhr.onload = function(){
if(xhr.status === 200){
alert('用户名:'+xhr.responseText);
}else{
alert('请求失败,返回状态:'+xhr.status);
}
};
xhr.send();
//POST请求
//JQ
var newName = 'John Smith';
$.ajax('myservice/username?' + $.params({id:'some-unique-id'}),{
method:'POST',
data:{
name:newName
}
}).then(function success(name){
if(name !== newName){
alert('发生错误,当前用户名是:'+name);
}
},function fail(data,status){
alert('请求失败,返回状态:'+ status);
});
//原生
var newName = 'John Smith',
xhr = new XMLHttpRequest();
xhr.open('POST','myservice/username?id=some-unique-id');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function(){
if(xhr.status === 200 && xhr.responseText !== newName){
alert('发生错误,当前用户名是:'+ xhr.responseText);
}else if(xhr.status !==200){
alert('请求失败,返回状态:'+xhr.status);
}
};
xhr.send(encodeURI('name='+newName));
//CORS跨域
//JQ
$.ajax('http://someotherdomain.com', {
method: 'POST',
contentType: 'text/plain',
data: 'sometext',
beforeSend: function(xmlHttpRequest) {
xmlHttpRequest.withCredentials = true;
}
});
//原生
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://someotherdomain.com');
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send('sometext');
//JSOP请求
//1,定义函数 function Fn(data) { ……. }
//2,发送 JSONP 请求
//3,创建一个 script 标签,src 设置为 JSONP 请求路径
//4,JSONP 返回的是 Fn({a:1, b:2}),相当于带参数执行了函数 Fn() ,以此达到跨域目的
//JQ
$.ajax('http://jsonp-aware-endpoint.com/user', {
jsonp: 'callback',
dataType: 'jsonp',
data: {
id: 123
}
}).then(function(response) {
});
//原生
function jsonp(url, callback) {
var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[callbackName] = function(data) {
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};
var script = document.createElement('script');
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
document.body.appendChild(script);
}
//调用方式
jsonp('http://jsonp-aware-endpoint.com/user?id=1',function(data){
alert(data)
})
|
var yuan = {
"春晖园":["梅香楼","兰洁楼","菊清楼","竹贞楼"],
"图强园":["成敬楼","恭虚楼","谨信楼","勤勉楼"],
"积胜园":["梅香楼","兰洁楼","菊清楼","竹贞楼"],
"弘毅园":["明志楼","明德楼"],
"至善园":["日善楼","兼善楼"],
"思贤园":["思勉楼","思齐楼"],
"其他":["其他"]
}
$('#location').click(function(){//点击地址跳转
window.location.href = 'address.html';
});
$('[name="addressGo"]').click(function(){//点击地址跳转
window.location.href='address.html';
});
//showIOSDialog1
$(function(){
//第一个列表
var $androidActionSheet = $('#androidActionsheet');
var $androidMask = $androidActionSheet.find('.weui-mask');
$("#garden").on('click', function(){
$androidActionSheet.fadeIn(50);//显示
$androidMask.on('click',function () {
$androidActionSheet.fadeOut(200);//关闭
});
$androidActionSheet.find('.weui-check__label').click(function(){//点击列表
var y = $('p',this).text();//当前选中的是哪个园
var html = '';
$androidActionSheet.fadeOut(200);//关闭
$("#garden").text(y);//选中当前园后添加
html += '<label class="weui-cell weui-check__label" for="x8"><div class="weui-cell__hd"><input type="radio" class="weui-check" name="radio3" id="x8" checked="checked"/><i class="weui-icon-checked"></i></div><div class="weui-cell__bd"><p>'+yuan[y][0]+'</p></div></label>';//添加第一个
for(var i=1; i<yuan[y].length; i++){
html += '<label class="weui-cell weui-check__label" for="x'+i+9+'"><div class="weui-cell__hd"><input type="radio" name="radio3" class="weui-check" id="x'+i+9+'"/><i class="weui-icon-checked"></i></div><div class="weui-cell__bd"><p>'+yuan[y][i]+'</p></div></label>';
}
//console.log(html);
$('#androidActionsheet2 .weui-cells_checkbox').html(html);//全部添加
$("#floor").text(yuan[y][0]);//添加第二个
if($('p',this).text()=='其他'){
$('#qiTa').css('display','block');
}else{
$('#qiTa').css('display','none');
}
});
});
//第二个列表
var $androidActionSheet2 = $('#androidActionsheet2');
var $androidMask2 = $androidActionSheet2.find('.weui-mask');
$("#floor").on('click', function(){
$androidActionSheet2.fadeIn(50);//显示
$androidMask2.on('click',function () {
$androidActionSheet2.fadeOut(200);//关闭
});
$androidActionSheet2.find('.weui-check__label').click(function(){
$androidActionSheet2.fadeOut(200);//关闭
$("#floor").text($('p',this).text());//选中当前园后添加
});
});
//点击显示
$('.showIOSDialog1').on('click', function(){
$('#iosDialog1').fadeIn(200);
});
//点按钮关闭
$('#dialogs').on('click', '.weui-dialog__btn', function(){
$(this).parents('.js_dialog').fadeOut(200);//关闭
});
});
//添加地址 检测是否 为空
$('[name="sub"]').click(function(){//检查字符串
var checkAddress = {//地址
user_name : $('#name').val(),
sex : $('#sex label input').eq(0).is(':checked')?'先生':'女士',
user_phone : $('#phone').val(),
user_address : $('#garden').text() +','+$('#floor').text() +','+ $('#room').val()
};
//检查不为空
var s='';
if(checkAddress.user_name==''){
s += ',姓名'
}
if(checkAddress.user_phone==''){
s += ',电话'
}
if($('#room').val()==''){
s += ',房号'
}
if(checkAddress.user_name && checkAddress.user_phone && $('#room').val()){
return ;//JSON.stringify(json);//json转字符串
}
$('#iosDialog2').find('span').text(s)
$('#iosDialog2').fadeIn(200);
});
//**************************************
|
export default class extends React.Component {
render () {
return <div>
<h1>This is about page</h1>
</div>
}
}
|
define([ "Floors", "PointerLockControls", "PointerLockSetup", "Particles",
"MazePath", "Shapes", "Core", "TinyPubSub","Utilities", "Sockets" ], function(Floors,
PointerLockControls, PointerLockSetup, Particles, MazePath, Shapes,
Core, TinyPubSub, utilities, io) {
var particles;
var mazepath=[];
var shapes;
var core;
var particleBaseName;
var animateNpc = true;
var cube = null;
var size = 20;
var cubes = [];
var eyex = 200;
var eyez = 300;
var msize = 8.5;
var npcX;
var npcZ;
var me;
var myGridX;
var myGridZ;
var io;
function Control() {
init();
animate();
$.subscribe('drawMap', redrawMap);
}
function init() {
core = new Core();
var screenWidth = window.innerWidth / window.innerHeight;
core.camera = new THREE.PerspectiveCamera(75, screenWidth, 1, 1000);
core.scene = new THREE.Scene();
core.scene.fog = new THREE.Fog(0xffffff, 0, 750);
addLights();
// drawing floor
var floors = new Floors();
floors.drawFloor(core.scene);
// creating mazepath
mazepath = new MazePath();
mazepath.addCubes("Grid000.json", core.scene, core.camera);
// particles creation
particles = new Particles();
particles.initNpc("Npc000.json", core.scene, core.camera);
particles.getNpcX=npcX;
particles.getNpcZ=npcZ;
doPointerLock();
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var blockSize = 8.5;
ctx.fillStyle = "#00FF00";
ctx.fillRect(1 * blockSize, 1 * blockSize, blockSize,blockSize);
raycaster = new THREE.Raycaster(new THREE.Vector3(), new THREE.Vector3(
0, -1, 0), 0, 10);
core.renderer = new THREE.WebGLRenderer({
antialias : true
});
core.renderer.setClearColor(0xffffff);
core.renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(core.renderer.domElement);
window.addEventListener('resize', onWindowResize, false);
$("#gameData").load("GameData.html");
$.getJSON("GameData.json", function(json) {
$("gameJason").html(json[0].Name);
});
}
function doPointerLock() {
controls = new THREE.PointerLockControls(core.camera);
var yawObject = controls.getObject();
core.scene.add(yawObject);
// Move camera to the 1, 1 position
yawObject.position.x = size;
yawObject.position.z = size;
var ps = new PointerLockSetup(controls);
}
function animate() {
requestAnimationFrame(animate);
var xAxis = new THREE.Vector3(1, 0, 0);
particles.rotateParticlesAroundWorldAxis(0, xAxis, Math.PI / 180,
animateNpc);
animateNpc = !animateNpc;
controls.isOnObject(false);
var socket = io.connect('http://127.0.0.1:30025');
socket.on('socket_is_connected', function(message) {
$('#debug').html(message);
});
socket.emit("socket_listener_connect","Listerner connected");
//socket.emit("GreadChanged", {"grid":$.getJSON("Grid000.json")});
socket.emit("npcLocations", {"positionX": npcX, "positionZ": npcZ});
socket.emit("redrawMap", {"grid":$.getJSON("Grid000.json"),"particles":$.getJSON("Npc000.json")});
var controlObject = controls.getObject();
var position = controlObject.position;
myGridX = Math.floor(position.x/size);
myGridZ = Math.floor(position.z/size);
if (particles.isNpc(myGridX, myGridZ))
{
particles.NPCs(myGridX, myGridZ, 0);
}
drawText(controlObject, position, particles);
mazepath.collisionDetection(position);
$.publish('drawMap', {type:"me"},'Please redraw mini map');
// Move the camera
controls.update();
core.renderer.render(core.scene, core.camera);
}
/*var myObject= new Object();
function redrawMap(){
var controlObject = controls.getObject();
var position = controlObject.position;
var c = document.getElementById("myCanvas");
var context = c.getContext("2d");
context.fillStyle = "#FF0000";
if(myObject.x != undefined){
console.log(myObject.x);
context.clearRect(myObject.x, myObject.z, msize, msize);
}
context.fillStyle = "#FFFF00";
var nowX = Math.floor(position.x/size)*msize;
var nowZ = Math.floor(position.z/size)*msize;
if(myObject.x == nowX){
console.log(myObject.x);
context.clearRect(myObject.x, myObject.z, msize, msize);
}
context.fillRect(nowX, nowZ, msize, msize);
myObject.x = nowX;
myObject.z = nowZ;
}*/
function addLights() {
var light = new THREE.DirectionalLight(0xffffff, 1.5);
light.position.set(1, 1, 1);
core.scene.add(light);
light = new THREE.DirectionalLight(0xffffff, 0.75);
light.position.set(-1, -0.5, -1);
core.scene.add(light);
}
function addSphere(scene, camera, wireFrame, x, y) {
var geometry = new THREE.SphereGeometry(10, 10, 10);
var material = new THREE.MeshNormalMaterial({
color : 0x00ffff,
wireframe : wireFrame
});
var sphere = new THREE.Mesh(geometry, material);
sphere.overdraw = true;
sphere.position.set(x, 10, y);
scene.add(sphere);
return sphere;
}
function drawText(controlObject, position, particles){
$('#cameraX').html(Math.floor(position.x)/size);
$('#cameraY').html(Math.floor(position.y)/size);
$('#cameraZ').html(Math.floor(position.z)/size);
$('#particleX').html(particles.getNpcX);
$('#particleZ').html(particles.getNpcZ);
}
function onWindowResize() {
core.camera.aspect = window.innerWidth / window.innerHeight;
core.camera.updateProjectionMatrix();
core.renderer.setSize(window.innerWidth, window.innerHeight);
}
return Control;
});
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.PACKAGE_NAME = factory());
}(this, (function () { 'use strict';
class B {
static getVal() {
return 100;
}
}
class A {
constructor() {
this._val = 123;
}
get val() {
return this._val + B.getVal();
}
}
class Main {
constructor() {
this._a = new A();
}
getValue() {
return this._a.val + 17;
}
}
const xxx = new Main();
return xxx;
})));
|
const db = require('../modules/firebase');
const jwt = require('../utils/jwt');
let express = require('express');
let router = express.Router();
router.route('/colectores').get(async function(req, res) {
const colectoresSnapshot = await db.collection('colectores').get();
const colectores = [];
colectoresSnapshot.forEach(colector => {
colectores.push({
id: colector.id,
nombre: colector.data().nombre
});
});
res.json(colectores);
});
router.route('/colectores').post(async function(req, res) {
if(jwt.validateToken){
const colector = {
nombre: req.body.nombre
};
const docRef = await db.collection('colectores').add(colector);
res.json({ message: 'Colector creado', id: docRef.id });
}
else{
res.json({"message": "no autorizado"});
}
});
router.route('/colector/:id').put(async function(req, res) {
if(jwt.validateToken){
const colector = {
nombre: req.body.nombre
};
await db.collection('colectores').doc(req.params.id).set(colector);
res.json({ message: 'Colector actualizado'});
}
else{
res.json({"message": "no autorizado"});
}
});
router.route('/colector/:id').delete(async function(req, res) {
if(jwt.validateToken){
await db.collection('colectores').doc(req.params.id).delete();
res.json({ message: 'Colector eliminado' });
}
else{
res.json({"message": "no autorizado"});
}
});
module.exports = router;
|
import http from "./httpService";
async function getRoomsTypes() {
try {
const { data: rooms } = await http.get(`${http.baseUrl}/roomcategory`);
return rooms;
} catch (error) {
console.log(error);
}
}
async function addRoomType(data) {
try {
const response = await http.post(
`${http.baseUrl}/roomcategory`,
data
);
return response
} catch (error) {
console.log(error);
return false
}
}
async function updateRoomType(data) {
try {
const response = await http.patch(
`${http.baseUrl}/roomcategory`,
data
);
if(response.status === 200)
return true
return false
} catch (error) {
console.log(error);
return false
}
}
async function deleteRoomType(data) {
try {
const response = await http.delete(
`${http.baseUrl}/roomcategory/${data._id}`
);
if(response.status === 200)
return true
return false
} catch (error) {
console.log(error);
return false
}
}
export default { getRoomsTypes, addRoomType, updateRoomType, deleteRoomType };
|
import React, { useEffect } from 'react';
import TodoComponent from '../todos/todo.component';
import './home.css';
const todos = [{
id: '16n5jkgfc0d4k760',
name: 'Take a shower'
}, {
id: '9a2889n7f55s410v',
name: 'Walk the dog'
}, {
id: 'pmakvvvb1s2aapkf',
name: 'Go to work'
}];
export default function () {
useEffect(function () {
// Do something when the component mounts
}, []);
return (
<div className="container">
<div className="header">
<h2 className="header-title">Welcome to the MXR Stack Workshop</h2>
<button
type="button"
className="add-button"
onClick={function () {
// Add a Todo
}}
>
Add Todo
</button>
</div>
<ul className="todos">
{todos.map(function (todo) {
return (
<li key={todo.id}>
<TodoComponent
todo={todo}
onChange={function (e) {
// Edit a Todo
}}
onDeleteClick={function () {
// Delete a Todo
}}
/>
</li>
);
})}
</ul>
</div>
);
}
|
import React, {Component} from 'react'
import {
Icon,
Card,
Statistic,
DatePicker,
Timeline
} from 'antd'
import moment from 'moment'
import Line from './line'
import Bar from './bar'
import './home.less'
const dateFormat = 'YYYY/MM/DD'
const {RangePicker} = DatePicker
export default class Home extends Component {
state = {
isVisited: true
}
handleChange = (isVisited) => {
return () => this.setState({isVisited})
}
render() {
const {isVisited} = this.state
return (
<div className='home'>
<Card
className="home-card"
title="Total Amounts"
extra={<Icon style={{color: 'rgba(0,0,0,.45)'}} type="question-circle"/>}
style={{width: 250}}
headStyle={{color: 'rgba(0,0,0,.45)'}}
>
<Statistic
value={1128163}
suffix="个"
style={{fontWeight: 'bolder'}}
/>
<Statistic
value={15}
valueStyle={{fontSize: 15}}
prefix={'Week'}
suffix={<div>%<Icon style={{color: 'red', marginLeft: 10}} type="arrow-down"/></div>}
/>
<Statistic
value={10}
valueStyle={{fontSize: 15}}
prefix={'Day'}
suffix={<div>%<Icon style={{color: '#3f8600', marginLeft: 10}} type="arrow-up"/></div>}
/>
</Card>
<Line/>
<Card
className="home-content"
title={<div className="home-menu">
<span className={isVisited ? "home-menu-active home-menu-visited" : 'home-menu-visited'}
onClick={this.handleChange(true)}>Views</span>
<span className={isVisited ? "" : 'home-menu-active'} onClick={this.handleChange(false)}>Sales</span>
</div>}
extra={<RangePicker
defaultValue={[moment('2019/01/01', dateFormat), moment('2019/06/01', dateFormat)]}
format={dateFormat}
/>}
>
<Card
className="home-table-left"
title={isVisited ? 'View Trend' : 'Sale Trend'}
bodyStyle={{padding: 0, height: 275}}
extra={<Icon type="reload"/>}
>
<Bar/>
</Card>
<Card title='Task' extra={<Icon type="reload"/>} className="home-table-right">
<Timeline>
<Timeline.Item color="green">New Version</Timeline.Item>
<Timeline.Item color="green">Complete new Version</Timeline.Item>
<Timeline.Item color="red">
<p>Mock API</p>
<p>Features</p>
</Timeline.Item>
<Timeline.Item>
<p>Login Feature</p>
<p>Authorization</p>
<p>Arrange</p>
</Timeline.Item>
</Timeline>
</Card>
</Card>
</div>
)
}
}
|
import test from 'ava'
import messageFormatter from './index'
test('formats messages for errors', t => {
const results = [
{type: 'error', message: 'first error message', key: 'the.first.key'},
{type: 'error', message: 'second error message', key: 'the.second.key'},
]
const {error} = messageFormatter(results)
t.ok(error.match(/the\.first\.key.*?first error message/))
t.ok(error.match(/the\.second\.key.*?second error message/))
})
test('formats messages for warnings', t => {
const results = [
{type: 'warning', message: 'first warning message', key: 'the.first.key'},
{type: 'warning', message: 'second warning message', key: 'the.second.key'},
]
const {warning} = messageFormatter(results)
t.ok(warning.match(/the\.first\.key.*?first warning message/))
t.ok(warning.match(/the\.second\.key.*?second warning message/))
})
|
/* eslint-disable no-tabs */
import React, { Component } from 'react';
import { Modal, Form, message } from 'antd';
import http from 'common/http';
import session from 'models/Session';
import DynamicSearchForm from 'components/DynamicSearchForm';
import { tacheCatalogSaveFormConfig } from '../StaticConfigs';
class SaveTacheCatalogModal extends Component {
constructor(props){
super(props);
this.state = {
toRender: true,
type: '',
formConfig: tacheCatalogSaveFormConfig,
systemCode: session.currentTendant.tenantCode,
tacheCatalogId: '',
tacheCatalogName: '',
parentTacheCatalogId: ''
}
let _type = props.type;
if (!props.currentTacheCatalog) _type = '';
switch (_type){
case 'addCataLog':
this.state.title = '增加目录';
this.state.parentTacheCatalogId = props.currentTacheCatalog.parentCatalogId;
this.state.tacheCatalogName = '';
this.state.formConfig.fields[0].props.defaultValue = '';
this.state.type = 'add';
break;
case 'editCataLog':
this.state.title = '修改目录';
this.state.parentTacheCatalogId = props.currentTacheCatalog.parentCatalogId;
this.state.tacheCatalogId = props.currentTacheCatalog.id;
this.state.catalogName = props.currentTacheCatalog.text;
this.state.formConfig.fields[0].props.defaultValue = props.currentTacheCatalog.text;
this.state.type = 'edit';
break;
case 'addSubCataLog':
this.state.title = '增加子目录';
this.state.parentTacheCatalogId = props.currentTacheCatalog.id;
this.state.tacheCatalogName = '';
this.state.formConfig.fields[0].props.defaultValue = '';
this.state.type = 'add';
break;
case 'deleteCataLog':
this.state.toRender = false;
if (!this.props.currentTacheCatalog) {
if (this.props.onCancel){
this.props.onCancel();
}
break;
}
this.state.tacheCatalogId = props.currentTacheCatalog.id;
this.toComfirmAndremoveTacheCatalog();
break;
default:
message.warning('请选中操作的目录');
if (props.onCancel){
props.onCancel();
}
this.state.toRender = false;
}
}
handleOnOk = (e) => {
const form = this.formRef.props.form;
form.validateFields((err, values) => {
if (err) return;
this.state.tacheCatalogName = values.tacheCatalogName;
if (this.state.type == 'add') {
this.addTacheCatalog();
} else if (this.state.type == 'edit') {
this.editTacheCatalog();
}
});
}
addTacheCatalog = () => {
http.post('/call/call.do', {
bean: 'TacheServ',
method: 'addTacheCatalog',
param: {
tacheCatalogName: this.state.tacheCatalogName,
parentTacheCatalogId: this.state.parentTacheCatalogId,
systemCode: this.state.systemCode
}
}, {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}).then(res => {
const returnData = JSON.parse(res);
if (returnData.catalogId) {
Modal.success({ title: '提示', content: '新增环节目录成功' });
if (this.props.onOk){
this.props.onOk();
}
} else {
Modal.error({ title: '提示', content: '新增环节目录失败' });
}
}, res => {
Modal.error({ title: '提示', content: '新增环节目录失败' });
});
}
editTacheCatalog = () => {
http.post('/call/call.do', {
bean: 'TacheServ',
method: 'modTacheCatalog',
param: {
tacheCatalogName: this.state.tacheCatalogName,
id: this.state.tacheCatalogId
}
}, {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}).then(res => {
const returnData = JSON.parse(res);
if (returnData.isSuccess) {
Modal.success({ title: '提示', content: '修改环节目录成功' });
if (this.props.onOk){
this.props.onOk();
}
} else {
Modal.error({ title: '提示', content: '修改环节目录失败' });
}
}, res => {
Modal.error({ title: '提示', content: '修改环节目录失败' });
});
}
toComfirmAndremoveTacheCatalog = () => {
http.post('/call/call.do', {
bean: 'TacheServ',
method: 'qryTaches',
param: { tacheCatalogId: this.state.tacheCatalogId, state: '10A', page: 1, pageSize: 1, systemCode: this.state.systemCode }
}, {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}).then(res => {
const returnData = JSON.parse(res);
if (returnData.rows.length > 0){
Modal.warning({ title: '提示', content: '该目录下存在环节,无法删除' });
return;
}
Modal.confirm({
title: '提示',
content: '确定该目录吗',
okText: '确定',
cancelText: '取消',
onOk: () => {
this.removeTacheCatalog();
},
onCancel: () => {
if (this.props.onCancel){
this.props.onCancel();
}
},
});
}, res => {
Modal.error({ title: '提示', content: '删除环节目录失败' });
});
}
removeTacheCatalog = () => {
http.post('/call/call.do', {
bean: 'TacheServ',
method: 'delTacheCatalog',
param: { id: this.state.tacheCatalogId }
}, {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}).then(res => {
const returnData = JSON.parse(res);
if (returnData.isSuccess){
Modal.success({ title: '提示', content: '删除环节目录成功' });
if (this.props.onOk) {
this.props.onOk();
}
} else {
Modal.error('提示', '删除环节目录失败');
}
}, res => {
Modal.error({ title: '提示', content: '删除环节目录失败' });
});
}
render = () => {
const { onOk, ...otherProps } = this.props;
return this.state.toRender ? (
<Modal title={this.state.title} defaultValue={this.state.tacheCatalogName} okText="保存" cancelText="取消" {...otherProps} onOk={this.handleOnOk}>
<DynamicSearchForm
wrappedComponentRef={(formRef) => { this.formRef = formRef; }}
formConfig={this.state.formConfig}
hideFooter={true}
/>
</Modal>
) : null;
}
}
export default Form.create()(SaveTacheCatalogModal); |
import axios from 'axios';
import * as actionTypes from './types';
export const addContentToWatched = (content) => async (dispatch) => {
try {
// ADD REDUCER FOR LOAD/WAIT ANIMATION
// console.log(content);
const res = await axios.post('/api/profile/add-to-watched', content);
console.log(res);
dispatch({
type: actionTypes.CONTENT_ADDED_TO_WATCH,
payload: res.data.content,
});
} catch (error) {}
};
export const getProfileData = () => async (dispatch) => {
if (localStorage.getItem('movieTrackerAccessToken')) {
try {
const res = await axios.get('/api/profile/me');
console.log(res.data);
dispatch({
type: actionTypes.PROFILE_LOADED,
payload: res.data,
});
} catch (error) {
console.log(error);
}
}
};
export const removeContentFromWatched = (content) => async (dispatch) => {
try {
// Add dispatch to handle button/icon loading/disable before sending request
console.log('action remove content', content);
const res = await axios.delete(
`/api/profile/remove-watched/${content.type}/${content.id}`
);
console.log('remove action', res.data);
dispatch({
type: actionTypes.CONTENT_REMOVED_FROM_WATCH,
payload: content,
});
} catch (error) {
if (error.response.status === 400) {
// show some message to user that content not in watched
}
console.log(error);
}
};
export const addContentToList =
(listId, listType, type, content) => async (dispatch) => {
try {
let payload = {
listId: listId,
listType: listType,
content: {
id: content.id,
title: content.title,
poster: content.poster_path,
backdrop: content.backdrop_path,
type: type,
},
};
const res = await axios.post('/api/profile/list/add', payload);
console.log(res);
if (listType === 'custom') {
dispatch({
type: actionTypes.CONTENT_ADDED_TO_LIST,
payload: { type: type, id: content.id },
});
} else {
dispatch({
type: actionTypes.CONTENT_ADDED_TO_WATCHLIST,
payload: { type: type, id: content.id },
});
}
} catch (error) {
if (error.response.status === 400) {
console.log(error.response.data.message);
} else {
console.log(error);
}
}
};
export const removeContentFromList =
(listId, type, item) => async (dispatch) => {
try {
const payload = {
listId: listId,
type: type,
contentId: item.id,
};
const res = await axios.post('/api/profile/list/remove', payload);
dispatch({
type: actionTypes.CONTENT_REMOVED_FROM_LIST,
payload: {
type: type,
id: item.id,
},
});
} catch (error) {
if (error.response.status === 400) {
console.log(error.response.data.message);
} else {
console.log(error);
}
}
};
export const addRating = (content, type, rating) => async (dispatch) => {
try {
console.log('addRating');
console.log(type);
// console.log(content);
// console.log(type);
// console.log(rating);
const payload = {
id: content.id,
title: content.title,
rating: rating,
poster: content.poster_path,
backdrop: content.backdrop_path,
type: type,
};
const res = await axios.post('api/profile/rating/add', payload);
console.log(res.data);
dispatch({
type: actionTypes.CONTENT_RATING_ADDED,
payload: payload,
});
} catch (error) {
//Handle error message display
console.log(error.message);
}
};
export const updateRating = (id, type, rating) => async (dispatch) => {
try {
const payload = {
id: id,
type: type,
rating: rating,
};
const res = await axios.patch('/api/profile/rating/update', payload);
dispatch({
type: actionTypes.CONTENT_RATING_UPDATED,
payload: payload,
});
} catch (error) {
console.log(error.message);
}
};
export const removeRating = (id, type) => async (dispatch) => {
try {
const res = await axios.delete(`api/profile/rating/remove/${type}/${id}`);
dispatch({
type: actionTypes.CONTENT_RATING_REMOVED,
payload: { id: id, type: type },
});
} catch (error) {
console.log(error.message);
}
};
export const createList = (name) => async (dispatch) => {
const payload = {
name: name,
};
console.log(name);
try {
const res = await axios.post('/api/profile/list', payload);
dispatch({
type: actionTypes.CREATE_LIST,
payload: res.data.list,
});
console.log(res.data);
} catch (err) {
console.log(err);
}
};
export const deleteList = (id) => async (dispatch) => {
try {
const res = await axios.delete(`/api/profile/delete/list/${id}`);
dispatch({
type: actionTypes.DELETE_LIST,
payload: id,
});
} catch (error) {
console.log(error);
}
};
|
import React, { PureComponent } from "react";
import { expect } from "chai";
import { act, render, cleanIt } from "reshow-unit";
import { globalStore } from "../../../stores/globalStore";
import {
Return,
localStorageStore,
sessionStorageStore,
dispatch,
} from "../../../index";
class TestEl extends PureComponent {
show = 0;
render() {
this.show++;
return <div />;
}
}
let uFake;
class FakeComponent extends PureComponent {
constructor(props) {
super(props);
uFake = this;
}
render() {
const { storage } = this.props;
return (
<Return store={storage}>
<TestEl ref={(el) => (this.el = el)} />
</Return>
);
}
}
describe("Test Storage Return", () => {
beforeEach(() => {
globalStore.path = null;
});
afterEach(() => {
cleanIt();
});
it("test get local storage", async () => {
const wrap = render(<FakeComponent storage={localStorageStore} />);
const uString = "test123";
await act(() => dispatch("local", { data: uString }), 5);
expect(uFake.el.props.data).to.equal(uString);
});
it("test get session storage", async () => {
const wrap = render(<FakeComponent storage={sessionStorageStore} />);
const uString = "test456";
await act(() => dispatch("session", { data: uString }), 5);
expect(uFake.el.props.data).to.equal(uString);
});
});
|
import Joi from 'joi';
import LoggerInstance from '../loaders/logger';
import validation from './validations/user';
import errorHandler from '../helpers/errorHandler';
import User from '../models/User';
import WhiteCollar from '../models/WhiteCollarUser';
import ListingUser from '../models/ListingUser';
import BlueCollar from '../models/BlueCollarUser';
import Employer from '../models/Employer';
import userRepository from '../repository/auth';
import employerRepository from '../repository/employer';
import whiteCollarRepository from '../repository/whiteCollar';
import blueCollarRepository from '../repository/blueCollar';
import emailService from './emailService2';
import emailTemplate from '../helpers/emailTemplates';
import functions from '../helpers/functions';
import cloud from './cloudinary';
export default class AuthService {
// constructor ({userRepository, logger}) {
// this.userRepository = userRepository
// this.logger = logger
// }
static async addUser(userInput, res) {
try {
const result = Joi.validate(userInput, validation.userSchema, {
convert: false,
});
if (result.error === null) {
const { email } = userInput;
const existUser = await userRepository.getUserByEmail(email);
if (existUser) {
errorHandler.serverResponse(res, 'User already exist', 400);
}
const userObject = { ...userInput };
const confirmCode = functions.generateConfirmCode();
userObject.confirmationCode = confirmCode;
const user = new User(userObject);
await user.save();
await emailService.sendText(
email,
'Confirm your account',
emailTemplate.confirmEmail(confirmCode),
);
return user;
}
return errorHandler.validationError(res, result);
} catch (e) {
LoggerInstance.error(e);
throw e;
}
}
static async selectUserType({ id, userType }, res) {
try {
const result = Joi.validate({ userType }, validation.validateUserType, {
convert: false,
});
if (result.error === null) {
const userId = id;
await userRepository.updateUser({ _id: id }, { userType });
const whiteCollar = new WhiteCollar({ userId });
const blueCollar = new BlueCollar({ userId });
const employer = new Employer({ userId });
const listingUser = new ListingUser({ userId });
switch (userType) {
case 'whiteCollar':
await whiteCollar.save();
break;
case 'blueCollar':
await blueCollar.save();
break;
case 'employer':
await employer.save();
break;
case 'businessOwner':
await listingUser.save();
break;
case 'vendor':
console.log('jude is an vendor');
break;
case 'admin':
console.log('jude is an admin');
break;
default:
break;
}
return true;
}
return errorHandler.validationError(res, result);
} catch (e) {
LoggerInstance.error(e);
throw e;
}
}
static async verifyRegUser(confirmCode, email, res) {
try {
const doc = await userRepository.getUserByEmail(email);
if (doc) {
const confirmationCode = !Number.isNaN(confirmCode) && String(confirmCode).trim().length === 6
? parseInt(confirmCode, 10)
: 'Invalid activation code';
if (doc.confirmationCode !== confirmationCode) {
return errorHandler.serverResponse(
res,
'Invalid confirmation code',
400,
);
}
const rslt = await userRepository.updateUser(
{ email, accountConfirm: false },
{ accountConfirm: true, isActive: true },
);
if (rslt) {
await emailService.sendText(
email,
'Welcome to Pop Express',
emailTemplate.registrationEmail(),
);
}
return true;
}
} catch (e) {
LoggerInstance.error(e);
throw e;
}
}
static async verifyUserSignIn(userInput, res) {
try {
const { email, password } = userInput;
const result = Joi.validate(userInput, validation.signInUser, {
convert: false,
});
if (result.error === null) {
const user = await userRepository.getUserByEmail(email);
if (user) {
if (user.isActive && user.accountConfirm) {
const isMatch = await user.comparePassword(password);
if (isMatch) {
const { token, firstname, lastname } = await user.generateToken();
return { firstname, lastname, token };
}
return errorHandler.serverResponse(
res,
'Password does not match',
400,
);
}
return errorHandler.serverResponse(
res,
'Account has not yet being verified',
404,
);
}
return errorHandler.serverResponse(
res,
'User is not yet registered with this email',
404,
);
}
return errorHandler.validationError(res, result);
} catch (e) {
LoggerInstance.error(e);
throw e;
}
}
static currentProfile(userDetails, res) {
if (userDetails) {
const user = { isAuth: true, ...userDetails._doc };
Reflect.deleteProperty(user, 'password');
return user;
}
return errorHandler.serverResponse(res, 'User does not exist', 400);
}
static async logOut(userDetails, res) {
try {
const result = await userRepository.updateUser(
{ _id: userDetails._id },
{ token: '' },
);
if (result) {
return true;
}
return false;
} catch (e) {
LoggerInstance.error(e);
throw e;
}
}
static async uploadPicture(profilePicPath, userValue, res) {
try {
const { url } = await cloud.picture(profilePicPath);
const { email } = userValue;
if (url) {
const doc = userRepository.updateUser({ email }, { profilePic: url });
if (doc) {
return doc;
}
return false;
}
return res.status(400).json('Something went wrong with the image upload');
} catch (error) {
LoggerInstance.error(error);
throw error;
}
}
static async uploadCv(cvUrl, userValue, res) {
try {
if (!cvUrl) {
return res.status(400).json('Please upload a file');
}
const { url } = await cloud.cv(cvUrl);
const { _id } = userValue;
console.log(url, 'cv url');
if (url) {
const doc = whiteCollarRepository.updateUser(_id, { cvUrl: url });
if (doc) {
return { doc, url };
}
return false;
}
return res.status(400).json('Something went wrong with the cv upload');
} catch (error) {
LoggerInstance.error(error);
throw error;
}
}
static async updateUserProfile(userDetails, res, userValue) {
try {
const result = Joi.validate(userDetails, validation.userUpdateSchema, {
convert: false,
});
if (result.error === null) {
const data = { ...userDetails };
const { _id, userType } = userValue;
switch (userType) {
case 'whiteCollar':
await whiteCollarRepository.updateUser(_id, userDetails);
break;
case 'blueCollar':
blueCollarRepository.updateUser(_id, userDetails);
break;
case 'employer':
employerRepository.updateUser(_id, userDetails);
break;
case 'client':
console.log('jude is an client');
break;
case 'vendor':
console.log('jude is an vendor');
break;
case 'admin':
console.log('jude is an admin');
break;
default:
break;
}
const searchFields = { _id };
const doc = await userRepository.updateUser(searchFields, data);
if (doc) {
return doc;
}
}
return errorHandler.validationError(res, result);
} catch (error) {
LoggerInstance.error(error);
throw error;
}
}
}
|
import React from 'react';
import { Link } from 'react-router-dom'
function Home () {
return (
<div>
<Link to={"/beers"}>All beers</Link>
<Link to={"/random-beer"}>Random Beer</Link>
<Link to={"/new-beer"}>New Beer</Link>
</div>
)
}
export default Home |
import React from 'react';
import { Route } from 'react-router-dom';
import PageHome from './PageHome';
// prettier-ignore
export default [
<Route key="PageHome" exact path="/" component={PageHome} />
];
|
import React from "react"
import { Card} from 'react-bootstrap';
const service = [
{
img:"img/24-7.jpg",
title:<h3>Full Support & Fast Response</h3>,
text:<>0812 xxxx xxxx (A.N. Gunadi) <br/>0821 xxxx xxxx (A.N. Heri)</>
},
{
img:"img/quality.png",
title:<><h3>Kualitas Terjaga</h3><br/></>,
text:"Kami berkomitmen untuk memberikan produk terbaik"
},
{
img:"img/free.jpg",
title:<><h3>Free Konsultasi, Survei, dan Design </h3></>,
text:"Kepuasan pelanggan adalah yang utama"
}
];
// membuat list service
export const listService = service.map((value,index)=>{
return (
<div key={index} style={{textAlign:"center"}} className="col-12 col-lg-4 my-2">
<Card style={{ width: '18rem', margin:'auto' }}>
<Card.Img variant="top" width="286px" height="180px" src={value.img} />
<Card.Body>
<Card.Title>{value.title}</Card.Title>
<Card.Text>
{value.text}
</Card.Text>
</Card.Body>
</Card>
</div>
)
}) |
import store from '../../store'
export default (to, from, next) => {
console.log('test middleware auth')
let dispatchToLogin = () => {
next({name: 'login'})
}
console.log('store.state.auth.token: ',store.state.auth.token)
if (!store.state.auth.token) {
console.log(1)
dispatchToLogin()
} else {
store.dispatch('auth/fetchUser')
.then(() => {
console.log('test0000')
if (to.path !== '/') {
next({name: 'index'});
} else {
next();
}
})
.catch((err) => {
console.log('err')
console.log(2)
dispatchToLogin()
});
}
}
|
$(document).ready(function(){
//---------- On Load Function ----------------
//------ Navigation-------------
$('#about_form').show();
$('#about a').css("color", "#e8491d").css("font-weight", "bolder");
$('#career_form').hide();
$('#contact_form').hide();
//---------- About ----------------
$('#about').on('click', function () {
$('#career_form').slideUp(function(){
$('#contact_form').slideUp(function(){
$('#about_form').slideDown(1000);
$('#about a').css("color","#e8491d").css("font-weight", "bolder");;
$('#career a').css("color","rgb(44, 156, 221)").css("font-weight", "100");
$('#contact a').css("color","rgb(44, 156, 221)").css("font-weight", "100");
});
});
});
//---------- Career ----------------
$('#career').on('click', function () {
$('#about_form').slideUp(function(){
$('#contact_form').slideUp(function(){
$('#career_form').slideDown(1000);
$('#about a').css("color","rgb(44, 156, 221)").css("font-weight", "100");
$('#career a').css("color","#e8491d").css("font-weight", "bolder");
$('#contact a').css("color","rgb(44, 156, 221)").css("font-weight", "100");
});
});
});
//---------- Contact ----------------
$('#contact').on('click', function () {
$('#about_form').slideUp(function(){
$('#career_form').slideUp(function(){
$('#contact_form').slideDown(1000);
$('#about a').css("color","rgb(44, 156, 221)").css("font-weight", "100");
$('#career a').css("color","rgb(44, 156, 221)").css("font-weight", "100");
$('#contact a').css("color","#e8491d").css("font-weight", "bolder");
});
});
});
//-------- Login -------------
$('#logcli_form').show();
$('#logadmin_form').hide();
//--- On Clinician Click ----
$('#a1').on('click', function(){
$('#logcli_form').show();
$('#logadmin_form').hide();
});
//--- On Clinician Click ----
$('#a2').on('click', function(){
$('#logcli_form').hide();
$('#logadmin_form').show();
});
//============ Registration =======================
$('#reg_cli_form').show();
$('#reg1').css("color", "#e8491d").css("font-weight", "bolder");
$('#reg_adm_form').hide();
$('#reg1').on('click', function(){
$('#reg_adm_form').slideUp(function(){
$('#reg_cli_form').slideDown(1000);
$('#reg1').css("color", "#e8491d").css("font-weight", "bolder");
$('#reg2').css("color","rgb(44, 156, 221)").css("font-weight", "100");
});
});
$('#reg2').on('click', function(){
$('#reg_cli_form').slideUp(function(){
$('#reg_adm_form').slideDown(1000);
$('#reg2').css("color", "#e8491d").css("font-weight", "bolder");
$('#reg1').css("color","rgb(44, 156, 221)").css("font-weight", "100");
});
});
//--------------------------------------------
}); |
const dbpool = require("../config/dbconfig");
const adminDao = {
getAdmin(arr,arr1){
return new Promise((resolve,reject)=>{
var sql = 'SELECT *,(SELECT a_name FROM t_admin AS b WHERE a.t_a_a_id=b.a_id) AS "create" FROM t_admin AS a WHERE 1=1';
if(arr.length>0){
if(arr1){
if(arr1.length!=0){
for(var i=0;i<arr1.length;i++){
if(arr1[i]==1){
sql += ' and a_name=?';
}
if(arr1[i]==2){
sql += ' and a_tel=?';
}
if(arr1[i]==3){
sql += ' and state=?';
}
}
}
}else{
sql += ' and a_id=?';
}
}
dbpool.connect(sql,arr,(err,data)=>{
resolve(data);
})
})
},
addAdmin(arr){
return new Promise((resolve,reject)=>{
var sql = '';
if(arr.length==4){
sql += 'INSERT INTO t_admin(t_a_a_id,a_name,a_pwd,a_tel) VALUES (?,?,?,?)'
}else if(arr.length==5){
sql += 'UPDATE t_admin SET t_a_a_id=?,a_name=?,a_pwd=?,a_tel=? WHERE a_id=?'
}
dbpool.connect(sql,arr,(err,data)=>{
resolve(data);
});
});
},
setState(arr){
return new Promise((resolve,reject)=>{
dbpool.connect('UPDATE t_admin SET state=? WHERE a_id=?',arr,(err,data)=>{
resolve(data);
})
})
}
};
module.exports=adminDao; |
import React from "react";
class AfegeixParticipants extends React.Component{
state = {name: '', image: ''};
onSubmit = (event) => {
event.preventDefault();
this.props.addPlayer(this.state.name, this.state.image);
this.setState({name: '', image: ''})
};
render () {
return (
<div className="ui segment">
<form onSubmit={this.onSubmit} className="ui form">
<div className="field">
<label>Image Serach</label>
<input type="text" name="nom" value={this.state.name} onChange={(e) => this.setState({name: e.target.value})}/>
<input type="color" name="imatge" value={this.state.image} onChange={(e) => this.setState({image: e.target.value})}/>
<button type="submit">Afegir</button>
</div>
</form>
</div>
)
}
}
export default AfegeixParticipants;
|
$(document).ready(function(){
$("#nav").click(function(){
//$("#nav dl").toggle(300);
var now_class = $("#nav").attr("class");
var showClass = (now_class == "cur") ? "" : "cur";
$("#nav").attr("class", showClass);
});
}); |
var ErrorsView = Backbone.View.extend({
render: function() {
var template = Handlebars.compile($('#errors').html());
return template(this.model);
},
});
|
/*
* @lc app=leetcode.cn id=682 lang=javascript
*
* [682] 棒球比赛
*/
// @lc code=start
/**
* @param {string[]} ops
* @return {number}
*/
var calPoints = function(ops) {
let res = [];
let num = 0;
for (let i = 0; i < ops.length; i++) {
switch(ops[i]) {
case '+' :
num = Number(res[res.length - 1]) + Number(res[res.length - 2]);
res.push(num)
break;
case 'D' :
num = Number(res[res.length - 1]) * 2;
res.push(num)
break;
case 'C' :
res.pop();
break;
default :
res.push(Number(ops[i]))
break;
}
}
let total = 0;
for (let i = 0; i < res.length; i++) {
total += res[i]
}
return total;
};
// @lc code=end
|
const mongoose = require("mongoose");
const productSchema = mongoose.Schema({
name: String,
price: String,
description: String,
category: String,
img: String,
});
const Product = mongoose.model("product", productSchema);
exports.getAllProducts = async function () {
try {
let products = Product.find();
return products;
} catch (err) {
console.log(err);
}
};
exports.getProductsById = async function (id) {
try {
let product = await Product.findById(id);
return product;
} catch (err) {
console.log(err);
}
};
exports.getProductsByCategory = async (category)=> {
try {
let products = await Product.find({category});
return products;
} catch (err) {
console.log(err);
}
}
exports.addProduct = async function({}){
try{
let product = await Product.create({})
console.log("product created in database")
}catch(err){console.log(err)}
} |
/**
* Modil
*
* A no-frills, lightweight and fast AMD implementation
* for modular JavaScript projects.
*
* @author Federico "Lox" Lucignano
* <https://plus.google.com/+FedericoLucignano/about>
* @author Jakub Olek
*
* @see https://github.com/federico-lox/modil
* @see http://requirejs.org/docs/api.html for example
* and docs until the official docs for modil ain't ready
*/
/*global setTimeout*/
(function (context) {
'use strict';
var mocks = {},
modules = {},
definitions = {},
processing = {},
//help minification
arrType = Array,
funcType = Function,
strType = 'string',
yes = true,
nil = null,
define,
require;
/**
* Processes a module definition for a require call
*
* @private
*
* @param {String} id The identifier of the module to process
* @param {Number} reqId The unique identifier generated by the require call
*
* @return {Object} The result of the module definition
*
* @throws {Error} If the processed module has circular dependencies
* @throws {Error} If id refers to an undefined module
*/
function process(id, reqId, optional) {
var module = modules[id],
mock = mocks[id],
//manage the process chain per require
//call since it can be an async call
pid = processing[reqId],
dependencies,
chain = '',
x,
y,
p,
moduleDependencies,
dependency;
if (module) {
return mock ? override(module, mock) : module;
}
if (!pid) {
pid = {length: 0};
} else if (pid[id]) {
for (p in pid) {
if (pid.hasOwnProperty(p) && p !== 'length') {
chain += p + '->';
}
}
throw 'circular dependency: ' + chain + id;
}
pid[id] = yes;
pid.length += 1;
processing[reqId] = pid;
module = definitions[id];
if (module && module.def) {
dependencies = [];
if (module.dep instanceof arrType) {
moduleDependencies = module.dep;
for (x = 0, y = moduleDependencies.length; x < y; x += 1) {
dependency = moduleDependencies[x];
dependencies[x] = process(dependency.toString(), reqId, dependency instanceof OptionalModule);
}
}
modules[id] = module = module.def.apply(context, dependencies);
} else if (!optional) {
throw 'Module ' + id + ' is not defined.';
}
delete definitions[id];
delete pid[id];
pid.length -= 1;
if (!pid.length) {
delete processing[reqId];
}
return mock ? override(module, mock) : module;
}
/**
* Defines a new module
*
* @public
*
* @example define('mymod', function () { return {hello: 'World'}; });
* @example define('mymod', ['dep1', 'dep2'], function (dep1, dep2) { ... });
*
* @param {String} id The identificator for the new module
* @param {Array} dependencies [Optional] A list of module id's which
* the new module depends on
* @param {Object} definition The definition for the module
*
* @throws {Error} If id is not passed or undefined
* @throws {Error} If id doesn't have a definition
* @throws {Error} If dependenices is not undefined but not an array
*/
function define(id, dependencies, definition, defMock) {
if (typeof id !== strType) {
throw "Module id missing or not a string. " + (new Error().stack||'').replace(/\n/g, ' / ');
}
//no dependencies array, it's actually the definition
if (!definition && dependencies) {
definition = dependencies;
dependencies = nil;
}
if (!definition) {
throw "Module " + id + " is missing a definition.";
} else if (definition instanceof funcType) {
if (dependencies === nil || dependencies instanceof arrType) {
if (defMock) {
mocks[id] = definition();
} else {
definitions[id] = {def: definition, dep: dependencies};
}
} else {
throw 'Invalid dependencies for module ' + id;
}
} else {
(defMock ? mocks : modules)[id] = definition;
}
};
/**
* Simple function to create mocks
*
* @param id {String} Name of a module to mock
* @param definition {Object} definition of mock
*/
define.mock = function (id, definition){
define(id, nil, definition, yes);
};
/**
* Declares support for the AMD spec
*
* @public
*/
define.amd = {
/**
* @see https://github.com/amdjs/amdjs-api/wiki/jQuery-and-AMD
*/
jQuery: yes
};
/**
* Requires pre-defined modules and injects them as dependencies into
* a callback, the process is non-blocking
*
* @public
*
* @example require(['mymod'], function (mymod) { ... });
* @example require(['mymod'], function (mymod, another) {}, function (err) {});
*
* @param {Array} ids An array of dependencies as moudule indentifiers
* @param {Function} callback The callback run in case of success, it will
* receive all the dependencies specified in ids as arguments
* @param {Function} errHandler [Optional] The callback to run in case of
* failure, should accept the error reference as the only parameter
*
* @throws {Error} If ids is not an array and/or callback is not a function
*/
function require(ids, callback, errHandler) {
if (ids instanceof arrType && callback instanceof funcType) {
//execute asynchronously
setTimeout(function () {
try {
var reqId = Math.random(),
m = [],
x,
y;
for (x = 0, y = ids.length; x < y; x += 1) {
var module = ids[x];
m[x] = process(module.toString(), reqId, module instanceof OptionalModule);
}
callback.apply(context, m);
} catch (err) {
if (errHandler instanceof funcType) {
errHandler.call(context, err);
} else {
throw err;
}
}
}, 0);
} else {
throw 'Invalid require call - ids: ' + JSON.stringify(ids);
}
};
/**
* Class that stores optional module name
*
* @param id {String} Name of optional module
* @constructor
*/
var OptionalModule = function(id){
this.id = id;
};
OptionalModule.prototype.toString = function(){
return this.id;
};
/**
* Function that 'marks' module as optonal
*
* @param id {String} Name of optional module
* @return {OptionalModule} OptionalModule object
*/
require.optional = function(id){
return new OptionalModule(id);
};
/**
* @param module Module to be mocked/partially mocked
* @param mock Mock
* @return Module
*/
function override(module, mock){
for (var p in mock) {
if (mock.hasOwnProperty(p) && module.hasOwnProperty(p)) module[p] = mock[p];
}
return module;
}
//expose as a "namespace"
context.Modil = {
define: define,
require: require
};
//expose as global functions if names not already assigned
if (!context.define) {
context.define = define;
}
if (!context.require) {
context.require = require;
}
}(this));
|
window.onload=function () {
window.onscroll=function(){//返回顶部函数
var btn=document.getElementById("btn");
var timer=null;
var scrolltop=document.body.scrollTop||document.documentElement.scrollTop;
var cheight=document.documentElement.clientHeight;
if (scrolltop>=cheight) {
btn.style.display="block";
}else{btn.style.display="none";}
}
function sc(){
var scrolltop=document.body.scrollTop||document.documentElement.scrollTop;
document.documentElement.scrollTop=document.body.scrollTop-=100;
if (scrolltop==0) {clearInterval(timer);}
}
btn.onclick=function(){
timer=setInterval(sc,10)
}
// var p=document.getElementById("box5").getElementsByTagName("p")[0];
// var img=document.getElementById("box5").getElementsByTagName("img")[0];
// img.onmouseover=function(){
// p.style.transform="translate(900px,0)"
// }
var arc=document.getElementsByClassName("arc")[0];
var context=arc.getContext("2d");//化圆
context.fillStyle="#ff8000";
context.beginPath();
context.arc(75,50,25,0,Math.PI*2,true);
context.closePath();
context.fill();
var can=document.getElementsByClassName("can")[0];
var con=can.getContext("2d");//化正方形
con.fillStyle="#ff8000";
con.fillRect(50,25,25,25);
var alink= document.getElementById("menu").getElementsByTagName("a");
for(var i=0;i<alink.length;i++){
alink[i].onmouseover=function(){
this.style.background="#ff8000";
this.style.color="#fff";
}
alink[i].onmouseout=function(){
this.style.background="";
this.style.color="#ff8000";
}
}
var img1=document.getElementById("box2").getElementsByTagName("img")[0];
img1.onmouseover=function(){
document.getElementById("box2").getElementsByTagName("p")[0].className="hov";
};
// img1.onmouseout=function(){
// document.getElementById("box2").getElementsByTagName("p")[0].className="hov";
// }
// var tr=document.getElementsByClassName("table")[0].getElementsByTagName("tbody")[0].getElementsByTagName("tr");
// for(var i=0;i<tr.length;i++){
// tr[i].firstChild.style.color="red";
// }
var west=document.getElementById("west");
var east=document.getElementById("east");
var dongbu=document.getElementById("dongbu");
var xibu=document.getElementById("xibu");
west.onclick=function(){
dongbu.style.display="none";
xibu.style.display="block";
}
east.onclick=function(){
xibu.style.display="none";
dongbu.style.display="block";
}
var container = document.getElementById('container');
var list = document.getElementById('list');
var buttons = document.getElementById('buttons').getElementsByTagName('span');
var prev = document.getElementById('prev');
var next = document.getElementById('next');
var index = 1;
var len = 5;
var animated = false;
var interval = 3000;
var timer;
function animate (offset) {//轮播图函数
if (offset == 0) {
return;
}
animated = true;
var time = 300;
var inteval = 10;
var speed = offset/(time/inteval);
var left = parseInt(list.style.left) + offset;
var go = function (){
if ( (speed > 0 && parseInt(list.style.left) < left) || (speed < 0 && parseInt(list.style.left) > left)) {
list.style.left = parseInt(list.style.left) + speed + 'px';
setTimeout(go, inteval);
}
else {
list.style.left = left + 'px';
if(left>-200){
list.style.left = -600 * len + 'px';
}
if(left<(-600 * len)) {
list.style.left = '-600px';
}
animated = false;
}
}
go();
}
function showButton() {//显示按钮函数
for (var i = 0; i < buttons.length ; i++) {
if( buttons[i].className == 'on'){
buttons[i].className = '';
break;
}
}
buttons[index - 1].className = 'on';
}
function play() {
timer = setTimeout(function () {
next.onclick();
play();
}, interval);
}
function stop() {
clearTimeout(timer);
}
next.onclick = function () {//下一张图片
if (animated) {
return;
}
if (index == 5) {
index = 1;
}
else {
index += 1;
}
animate(-600);
showButton();
}
prev.onclick = function () {//上一张
if (animated) {
return;
}
if (index == 1) {
index = 5;
}
else {
index -= 1;
}
animate(600);
showButton();
}
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = function () {
if (animated) {
return;
}
if(this.className == 'on') {
return;
}
var myIndex = parseInt(this.getAttribute('index'));
var offset = -600 * (myIndex - index);
animate(offset);
index = myIndex;
showButton();
}
}
container.onmouseover = stop;
container.onmouseout = play;
play();
} |
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Form from '../components/Form'
import React from 'react'
import Perfil from '../components/Perfil';
import NotFound from '../components/NotFound';
const AppRouter = () => {
return (
<Router>
<Switch>
<Route exact path="/perfil" component={Perfil}/>
<Route exact path="/"component={Form}/>
<Route path="*"component={NotFound}/>
</Switch>
</Router>
)
}
export default AppRouter
|
import io from 'socket.io-client';
import Player from '../entities/Player';
export default class Syncer {
constructor(renderer) {
this.position = {x: 0, y: 0, z: 0};
this.renderer = renderer;
this._id = '';
this.socket = io('http://localhost:3000');
this.socket.on('connected', _id => {
setInterval(() => {
if (this.updated) {
this.socket.emit('user_position_updated', {
position: this.renderer.user.body.position,
_id: this._id,
})
}
this.position = Object.assign({}, this.renderer.user.body.position);
}, 1000 / 30);
this._id = _id;
});
this.socket.on('user_positions', (users) => {
// console.log(users);
Object.keys(users).forEach((key) => {
if (!this.renderer.objects.find(p => p && p._id === key)) {
const newPlayer = new Player();
newPlayer._id = key;
this.renderer.renderObject(newPlayer);
} else {
this.renderer.objects = this.renderer.objects.map((o) => {
if (o._id === key) {
console.log(users[key].position);
o.body.position.set(...users[key].position);
}
return o;
})
}
})
})
this.socket.on('user_disconnected', (_id) => {
this.renderer.removeObjectById(_id);
})
}
sync = () => {
}
get updated () {
return !!(
this.renderer.user.body.position.x.toFixed(4) !== this.position.x.toFixed(4)
|| this.renderer.user.body.position.y.toFixed(4) !== this.position.y.toFixed(4)
|| this.renderer.user.body.position.z.toFixed(4) !== this.position.z.toFixed(4)
)
}
}
|
"use strict";
const _ = require('underscore');
const TextMessage = require(__dirname + '/text-message');
const UrlMessage = require(__dirname + '/url-message');
const ContactMessage = require(__dirname + '/contact-message');
const FileMessage = require(__dirname + '/file-message');
const LocationMessage = require(__dirname + '/location-message');
const PictureMessage = require(__dirname + '/picture-message');
const VideoMessage = require(__dirname + '/video-message');
const StickerMessage = require(__dirname + '/sticker-message');
const RichMediaMessage = require(__dirname + '/rich-media-message');
const SUPPORTED_MESSAGE_TYPES = [TextMessage, UrlMessage, ContactMessage,
FileMessage, LocationMessage, PictureMessage, VideoMessage, StickerMessage,
RichMediaMessage];
function MessageFactory(logger) {
const self = this;
this._logger = logger;
this._mapping = {};
_.each(SUPPORTED_MESSAGE_TYPES, messageType => self._mapping[messageType.getType()] = messageType);
}
MessageFactory.prototype.createMessageFromJson = function(json) {
let messageType = json.message.type.toLowerCase();
if (!_.has(this._mapping, messageType)) {
this._logger.debug(`Could not build message from type ${messageType}. No mapping found`);
return;
}
return this._mapping[messageType].fromJson(json.message, json.timestamp, json.message_token);
};
module.exports = MessageFactory;
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import WeatherApp from './WeatherApp';
import TableComponent from './components/TableComponent';
import GraphComponent from './components/GraphComponent';
ReactDOM.render(
(<Router history={browserHistory}>
<Route path="/" component={WeatherApp}>
<IndexRoute component={TableComponent} />
<Route path="/grafico" component={GraphComponent} />
</Route>
</Router>), document.querySelector('#weather-app')
);
|
var Mammal = function(name) {
this.name = name;
};
Mammal.prototype.getName = function() {
return this.name;
};
Mammal.prototype.makeSound = function() {
return this.sound || 'Me no speakum.';
};
var Cat = function(name) {
this.name = name;
this.sound = 'Meow';
};
Cat.prototype = new Mammal();
Cat.prototype.purr = function() {
return 'Puuuuuuuuuur';
};
Cat.prototype.getName = function() {
return this.makeSound() + ' ' + this.name + ' ' + this.makeSound();
};
|
const createUserInfosCard = (userResponse, color) => {
//console.log(userResponse);
const container = document.createElement('div');
container.classList.add('user');
container.style.backgroundColor = color;
const usernameHolder = document.createElement('div');
usernameHolder.classList.add('userName');
const pictureHolder = document.createElement('div');
pictureHolder.classList.add('pictureHolder');
const nameHolder = document.createElement('div');
const name = document.createElement('h3');
name.classList.add('user-name');
name.innerText = userResponse.name;
nameHolder.appendChild(name);
const infosHolder = document.createElement('div');
infosHolder.classList.add('userInfos');
usernameHolder.appendChild(pictureHolder);
usernameHolder.appendChild(nameHolder);
container.appendChild(usernameHolder);
container.appendChild(infosHolder);
const info1Label = document.createElement('h3');
info1Label.innerText = 'Username: ';
const info1 = document.createElement('span');
info1.innerText = userResponse.username;
info1Label.append(info1);
const info2Label = document.createElement('h3');
info2Label.innerText = 'Email: ';
const info2 = document.createElement('span');
info2.innerText = userResponse.parentPhone ? userResponse.parentEmail : userResponse.email;
info2Label.append(info2);
const info3Label = document.createElement('h3');
info3Label.innerText = 'School Id: ';
const info3 = document.createElement('span');
info3.innerText = userResponse.schoolId;
info3Label.append(info3);
const info4Label = document.createElement('h3');
info4Label.innerText = 'Phone: ';
const info4 = document.createElement('span');
info4.innerText = userResponse.parentPhone ? userResponse.parentPhone : userResponse.phone;
info4Label.append(info4);
infosHolder.appendChild(info1Label);
infosHolder.appendChild(info2Label);
infosHolder.appendChild(info3Label);
infosHolder.appendChild(info4Label);
let isExpand = false;
name.addEventListener('click', () => {
if (isExpand == false) {
container.style.height = "16rem";
} else {
container.style.height = "5.5rem";
}
isExpand = !isExpand;
});
return container;
}
export {
createUserInfosCard
} |
$( document ).ready(function() {
function VideoBg(elem) {
var name = 'video';
var self = this;
this.events = {};
var events = [];
var handlersToBind = [
'onClickPause',
'onVideoEnded'
];
this.elem = typeof elem === 'string' ? $(elem) : elem;
this.elem[0].VideoBg = this;
this.videoElem = this.elem.find('video');
this.videoInfo = this.elem.find('.video__info');
this.videoPause = this.videoInfo.find('.video__pause');
// set events
events.forEach(function (event) {
self._events[event] = event + '.' + name;
});
// binding methods to object
handlersToBind.forEach(function (method) {
self[method] = self[method].bind(self);
});
};
VideoBg.prototype.init = function () {
this.setInitState();
this.bindEvents();
};
VideoBg.prototype.setInitState = function () {
if (window.matchMedia('(prefers-reduced-motion)').matches) {
this.videoElem.removeAttribute("autoplay");
this.videoElem.get(0).pause();
this.videoPause.addClass("play");
}
};
VideoBg.prototype.bindEvents = function () {
var self = this;
this.videoElem.on('ended', this.onVideoEnded)
this.videoPause.on('click', this.onClickPause)
};
VideoBg.prototype.setDropAria = function () {
};
VideoBg.prototype.onVideoEnded = function (event) {
this.videoElem.pause();
this.videoFade();
};
VideoBg.prototype.onClickPause = function (event) {
event.preventDefault();
this.videoElem.toggleClass("stopfade");
if (this.videoElem.prop("paused")) {
this.videoElem.get(0).play();
this.videoPause.removeClass("play");
} else {
this.videoElem.get(0).pause();
this.videoPause.addClass("play");
}
};
VideoBg.prototype.open = function () {
};
VideoBg.prototype.videoFade = function () {
this.videoElem.addClass("stopfade");
};
VideoBg.prototype.destroy = function () {
this.videoElem.off(this.events.ended, this.onVideoEnded)
this.videoPause.off('click', this.onClickPause);
}
VideoBg.createInstance = function (elem, options) {
if (!elem.length) {
return;
}
if (VideoBg.isInstanceExist($(elem))) {
return;
}
return new VideoBg($(elem), options).init();
};
VideoBg.isInstanceExist = function (elem) {
return elem[0].VideoBg;
};
window.VideoBg = VideoBg.createInstance;
var $video = $('.video');
if (!$video.length){
return;
}
$.each($('.video'), function (index, elem) {
VideoBg.createInstance($(elem));
});
}); |
/**
*
* BitReaderMSB.js
*
* copyright 2003,2013 Kevin Lindsey
*
*/
/**
* BitReaderMSB
*
* @param {Array<Byte>} data
* @returns {BitReaderMSB}
*/
function BitReaderMSB(data) {
this.data = data;
this.index = 0;
this.mask = 0x80;
this.currentByte = null;
}
/**
* readBit
*/
BitReaderMSB.prototype.readBit = function() {
var result = null;
if ( this.mask === 0x80 ) {
if ( this.index < this.data.length ) {
this.currentByte = this.data[this.index++];
}
}
if ( this.currentByte !== null ) {
result = this.currentByte & this.mask;
this.mask >>= 1;
if ( this.mask === 0 ) {
this.mask = 0x80;
this.currentByte = null;
}
}
if ( result !== null ) {
result = (result === 0) ? 0 : 1;
}
return result;
};
/**
* readBits
*/
BitReaderMSB.prototype.readBits = function(bitCount) {
var mask = 1 << (bitCount - 1);
var result = 0;
while ( mask !== 0 ) {
if ( this.readBit() === 1) {
result |= mask;
}
mask >>= 1;
}
return result;
};
if (typeof module !== "undefined") {
module.exports = BitReaderMSB;
}
|
var events = require('events');
var eventEmmiter = new events.EventEmitter();
var myEventHandler = function(){
console.log('i hear a scream');
}
eventEmmiter.on('late', myEventHandler);
eventEmmiter.emit('late'); |
const saveToken = (token) => {
sessionStorage["token"] = token
}
const getToken = () => {
return sessionStorage["token"]
}
export {
getToken,
saveToken
} |
import React, { Component } from 'react';
import ReactJson from 'react-json-view';
import { Card } from 'react-bootstrap';
export default class JsonEditorComponent extends Component {
componentDidMount() {
const { handleRenderButton, isShow } = this.props;
if (isShow) {
handleRenderButton(false);
}
}
render() {
const { onSubmit, initState, handleInputChange } = this.props;
return (
<form onSubmit={e => onSubmit(e)}>
<Card className="jsonCard">
<Card.Header as="h4">JSON configuration <br />
<span>Hydrogen environment is not initialized. Please initialize it by using json bellow.</span></Card.Header>
<Card.Body>
<Card.Title>Edit JSON data</Card.Title>
<ReactJson
src={initState}
theme="apathy:inverted"
collapsed={1}
displayDataTypes={false}
onEdit={values => handleInputChange(values)}
iconStyle='circle'
/>
</Card.Body>
</Card>
</form>
)
}
}
|
{
"init" : [
"valid_user"
],
"class" : "Page::ring::setup::domain",
"command" : {
"domain_add" : "cmd_domain_add",
"update" : "cmd_update"
},
"template" : "u/settings/domains.html"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.