text
stringlengths 7
3.69M
|
|---|
import React from 'react';
import { Jumbotron, Button } from 'react-bootstrap';
import { Link } from 'react-router-dom';
export default function ErrorPage({ message, code }) {
return (
<Jumbotron className="bg-transparent">
<h1 className="errorTitle text-center text-white mt-5">{code || "404"}</h1>
<p className="errorMessage text-center text-white">{message || "Page Not Found"}</p>
<div className="center">
<Link to="/" style={{ textDecoration: "none" }}>
<Button variant="info" className="rounded bg-transparent homebtn btn-block" size="lg">Home</Button>
</Link>
</div>
</Jumbotron>
)
}
|
var blogModule = angular.module("BlogModule", []);
blogModule.controller('blogCtrl', function($http) {
var self = this;
self.items = [];
var fetchData = function(){$http.get('/blog').success(function(blogs) {
self.items = blogs;
});
};
fetchData();
});
var shareModule = angular.module("ShareModule", []);
shareModule.controller('shareCtrl', function($http) {
var self = this;
self.items = [];
var fetchData = function(){$http.get('/links').success(function(links) {
self.items = links;
});
};
fetchData();
});
var postModule = angular.module("PostModule", []);
postModule.controller('postCtrl', function($http) {
var self = this;
self.data ={};
var fetchData = function(){$http.get('/post/mean_intro').success(function(post) {
self.data = post;
});
};
fetchData();
});
|
let rows = table.td.slice();
let csvContent = "";
rows.forEach(function (rowArray) {
rowArray.map(function (m, i) {
rowArray[i] = m;
});
let row = rowArray.join(",");
csvContent += row + "\r\n";
});
let fileName = "";
let strMimeType = 'application/octet-stream;charset=utf-8';
let dataURI = encodeURI(csvContent);
let ua = window.navigator.userAgent;
if (ua.indexOf('MSIE ') > 0 || ua.indexOf('Trident/') > 0 || ua.indexOf('Edge') > 0) {
let blob = new Blob(["\ufeff", csvContent], { type: strMimeType });
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
let link = document.createElement("a");
link.setAttribute("href", "data:application/csv;charset=utf-8,%EF%BB%BF" + dataURI);
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
}
|
const fillWithChars = (inputSys, outputSys, pivotSys) => {
const charCodeDiff = 55
const fromDict = {}
const toDict = {}
if (outputSys > pivotSys)
for (let i = pivotSys; i < outputSys; i++)
toDict[i] = i + charCodeDiff
if (inputSys > pivotSys)
for (let i = pivotSys; i < inputSys; i++)
fromDict[i + charCodeDiff] = i
return { fromDict, toDict }
}
const castToPivotSys = (value, charDict, initSys) => {
value = value.toString().split('')
let sum = 0
for (let i = 0; i < value.length; i++) {
const code = value[i].charCodeAt(0)
value[i] = charDict[code] ? charDict[code] : value[i]
sum += value[i] * initSys ** (value.length - i - 1)
}
return sum
}
const castToTargetSys = (value, charDict, targetSys) => {
const result = []
while (value >= 1) {
const remainder = value % targetSys
result.unshift(charDict[remainder]
? String.fromCharCode(charDict[remainder])
: remainder)
value = Math.floor(value / targetSys)
}
return result.join('')
}
const convert = (initVal, fromSys, toSys) => {
const marginalSys = 10
const dicts = fillWithChars(fromSys, toSys, marginalSys)
if (fromSys !== marginalSys)
initVal = castToPivotSys(initVal, dicts['fromDict'], fromSys)
return castToTargetSys(initVal, dicts['toDict'], toSys)
}
console.log(convert('FE', 16, 10))
|
const express = require('express')
const router = express.Router()
const controller = require('../controller/user')
router.post('/createUser', controller.createUser)
router.post('/login', controller.userLogin)
module.exports = router
|
import React from "react";
import { Dialog } from "@material-ui/core";
import "assets/scss/confirm-dialog.sass";
const ImagePreview = ({ open, src, close }) => {
return (
<Dialog
open={open}
onClose={close}
aria-labelledby="image-preview-title"
aria-describedby="image-preview-description"
maxWidth={"lg"}
>
<div className={"full-image-preview"}>
<img className={"image"} src={src || ""} alt={"image"} />
</div>
</Dialog>
);
};
export default ImagePreview;
|
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'starter',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', type: 'text/css', href: 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto' }
]
},
/*
** Global CSS
*/
build: {
vendor: ['vuetify', 'vue-i18n', 'axios'],
loader: [
{
test: /\/.styl$/,
loader: ['style', 'css', 'stylus']
}
]
},
router: {
middleware: 'i18n'
},
plugins: ['~plugins/vuetify.js', '~/plugins/i18n.js'],
css: ['~assets/css/main.css', '~assets/css/app.styl'],
/*
** Customize the progress-bar color
*/
loading: { color: '#3B8070' }
};
|
import P from 'bluebird'
import fetchJson from './fetch-json'
import { getResolvedActionType, getRejectedActionType } from './utils'
export default function fetchAction({
data,
type,
...fetchArgs,
}) {
return dispatch => {
dispatch({
type,
payload: data,
})
return fetchJson({ ...fetchArgs, data })
.then(
response => {
dispatch({
type: getResolvedActionType(type),
payload: response,
})
return response
},
error => {
dispatch({
type: getRejectedActionType(type),
payload: error,
})
return P.reject(error)
},
)
}
}
|
angular.module('tdf.utilities').factory('Utilities',
[
function() {
return {
/**
* Removes all objects from list where object[propertyname] equals
* property.
*
* Note that the operation is performed in-place, though the
* result is also returned.
*/
spliceByProperty: function(list, propertyname, property) {
for (var i in list) {
if (list[i][propertyname] === property) {
list.splice(i, 1);
}
}
return list;
},
/**
* Removes all objects from list where the object is equal to obj.
*
* Note that the operation is performed in-place, though the
* result is also returned.
*/
spliceByObject: function(list, obj) {
for (var i in list) {
if (list[i] === obj) {
list.splice(i, 1);
}
}
return list;
}
};
}
]);
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
/**
* A component that shows the player's score as well as the answers.
*/
class ResultComponent extends Component {
render() {
const { quizData } = this.props;
return (
<div className="result">
<h3>Ditt slutresultat blev {this.props.score} av {quizData.length} poäng </h3>
<p>
Rätt svar på frågorna var
</p>
<ul class="quizResultList">
{quizData.map((item, index) => (
<li className={item.answer.correct ? 'correct' : 'wrong'} key={index}>
{item.answer.title} ({item.answer.song} by {item.answer.composer})
</li>
))}
</ul>
<Link to={{
pathname: '/',
//state: { accessToken }
}}
>
<button className='glow-on-hover'>
Spela igen?
</button>
</Link>
</div>
);
}
}
export default ResultComponent;
|
const router = require("express").Router();
const blogController = require('../controllers/blogController');
router.route('/create')
.post([], blogController.createBlog);
router.route('/list')
.get([], blogController.listBlog);
module.exports = router;
|
import React, { useEffect, useState } from 'react';
import { Form, Button, Dropdown } from 'react-bootstrap'
import { useHistory } from "react-router-dom";
import DayPickerInput from 'react-day-picker/DayPickerInput';
import { axios_instance } from '..';
import Select from 'react-select'
import "../../node_modules/react-time-picker/dist/TimePicker.css";
import "../../node_modules/react-clock/dist/Clock.css";
import TimePicker from 'react-time-picker'
import Subjects from './Subjects';
import { formatDateMillisTimeString } from '../utility'
const EditSessionForm = (props) => {
if (props.location.state && props.location.state.session) {
localStorage.setItem('editedSession', JSON.stringify(props.location.state.session));
}
const localStorageSession = JSON.parse(localStorage.getItem("editedSession"))
const history = useHistory();
const [endTime, setEndTime] = useState('');
const [time, setTime] = useState('');
const [session, setSession] = useState(localStorageSession);
const [errors, setErrors] = useState(undefined);
const greaterTime = (time1, time2) => {
const time1Hours = Number(time1.substring(0, 2))
const time2Hours = Number(time2.substring(0, 2))
const time1Minutes = Number(time1.substring(3, 5))
const time2Minutes = Number(time2.substring(3, 5))
if (time1Hours > time2Hours) {
return time1;
}
else if (time1Hours == time2Hours) {
return time1Minutes >= time2Minutes ? time1 : time2;
}
else {
return time2;
}
}
const handleErrors = () => {
const errorList = []
if (!time || !endTime || greaterTime(time, endTime) == time) {
errorList.push('Invalid time');
}
setErrors(errorList)
return errors;
}
const handleSubmit = (e) => {
e.preventDefault()
handleErrors();
if (!errors) {
const endDateTime = formatDateMillisTimeString(session.date.$date, endTime);
const startDateTime = formatDateMillisTimeString(session.date.$date, time)
console.log("FormattedEndDateTime: ", endDateTime)
console.log("FormattedStartDateTime: ", startDateTime)
const edited_session = {
...session,
end_time: endDateTime,
date: startDateTime,
}
const config = {
xhrFields: {
withCredentials: true
},
crossDomain: true,
headers: {
'Content-Type': 'application/json',
}
}
axios_instance.post(`/user/sessions/${session._id.$oid}/edit`, { ...edited_session, tutor_confirmed: false, student_confirmed: false }, config)
.then(() => {
history.push(`/`)
})
.catch((err) => {
console.log(err)
})
}
}
const handleDayClick = (day, { selected }) => {
const selectedDay = selected ? undefined : day;
const updated_session = { ...session, date: selectedDay }
setSession(updated_session);
}
const onTimeChange = (time) => {
setTime(time);
}
const onEndTimeChange = (time) => {
setEndTime(time);
}
const onDropdownSelect = (eventKey) => {
setSession({ ...session, subject: eventKey });
}
return (
<div className="form-comp-container">
<div className="form-comp">
<h1>Edit Session</h1>
<span className="errors">{errors}</span>
<Form onSubmit={handleSubmit}>
<Subjects onSelect={onDropdownSelect} subject={session.subject} />
<Form.Group controlId="tutor">
<Form.Label>Tutor</Form.Label>
<Form.Control type="text" value={session.tutor.username} />
</Form.Group>
<Form.Group controlId="student">
<Form.Label>Student</Form.Label>
<Form.Control type="text" value={session.student.username} />
</Form.Group>
<Form.Group>
<Form.Label>Date</Form.Label>
<DayPickerInput
className="calendar"
disabledDays={{ before: new Date() }}
format="M/D/YYYY"
name="date"
id="date"
onDayClick={handleDayClick}
selectedDays={new Date(session.date.$date)}
/>
</Form.Group>
<Form.Group>
<Form.Label className="block-label">Start Time</Form.Label>
<TimePicker
name="time"
id="time"
disableClock={true}
onChange={onTimeChange}
value={time}
/>
</Form.Group>
<Form.Group>
<Form.Label className="block-label">End Time</Form.Label>
<TimePicker
name="end_time"
id="end_time"
disableClock={true}
onChange={onEndTimeChange}
value={endTime}
/>
</Form.Group>
<Button variant="primary" type="submit">Submit</Button>
</Form>
</div>
</div>);
}
export default EditSessionForm;
|
import { combineReducers } from 'redux';
import * as types from '../types/baby';
const order = (state = [], action) => {
switch (action.type) {
case types.CREATE_BABY: {
return [ ...state, action.payload.id];
}
default: {
return state;
}
}
};
const byId = (state = {}, action) => {
switch (action.type) {
case types.CREATE_BABY: {
return {
...state, [action.payload.id]: {
id: action.payload.id,
name : action.payload.name,
lastName : action.payload.lastName,
}
};
}
default: {
return state;
}
}
};
const selectedBaby = (state = "", action) => {
if(action.type === types.SELECT_BABY){
return action.payload;
}
return state;
};
const baby = combineReducers({
byId,
order,
selectedBaby,
});
export default baby;
export const getBaby = (state, id) => state.byId[id];
export const getBabies = state => state.order.map(
id => getBaby(state, id),
).filter(baby => baby != null);
export const getSelectedBaby = state => state.selectedBaby;
|
define([
"backbone",
"modules/finger/fingers"
], function (Backbone, Fingers) {
"use strict";
var fingers = new Fingers([
{id: 1, place: {x: 396, y: -30}},
{id: 2, place: {x: 434, y: 38}},
{id: 3, place: {x: 499, y: 38}},
{id: 4, place: {x: 564, y: 42}},
{id: 5, place: {x: 633, y: 37}},
{id: 6, place: {x: 699, y: 37}},
{id: 7, place: {x: 765, y: 36}},
{id: 8, place: {x: 846, y: 22}}
]);
return fingers;
});
|
/*
* events.js - Single library to handle generic events
* The MIT License (MIT)
*
* Copyright (c) 2014 Jesús Manuel Germade Castiñeiras <jesus@germade.es>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
(function (root, factory) {
if ( typeof module !== 'undefined' ) {
module.exports = factory();
} else if( root ) {
if( root.define ) {
root.define('Events', function () { return factory(); } );
} else if( root.angular ) {
root.angular.module('jstools.events', []).factory('Events', function () { return factory(true); });
} else if( !root.Events ) {
root.Events = factory();
}
}
})(this, function (ng) {
'use strict';
var method = ng ? {
on: '$$on', once: '$$once', off: '$$off', trigger: '$$triger'
} : {
on: 'on', once: 'once', off: 'off', trigger: 'trigger'
};
function _addListener (handlers, handler, context) {
if( ! handler instanceof Function ) {
return false;
}
handlers.push({ handler: handler, context: context });
}
function _triggerEvent (handlers, attrs, caller) {
if( handlers ) {
for( var i = 0, len = handlers.length; i < len; i++ ) {
handlers[i].handler.apply(caller, attrs);
}
return len;
}
}
function _emptyListener (handlers) {
if( handlers ) {
handlers.splice(0, handlers.length);
}
}
function _removeListener (handlers, handler) {
if( handlers ) {
for( var i = 0, len = handlers.length; i < len; ) {
if( handlers[i].handler === handler ) {
handlers.splice(i, 1);
len--;
} else {
i++;
}
}
}
}
function Events (target) {
target = target || this;
var listeners = {};
var listenersOnce = {};
target[method.on] = function (eventName, handler, context) {
listeners[eventName] = listeners[eventName] || [];
_addListener(listeners[eventName], handler, context);
};
target[method.once] = function (eventName, handler, context) {
listenersOnce[eventName] = listenersOnce[eventName] || [];
_addListener(listenersOnce[eventName], handler, context);
};
target[method.trigger] = function (eventName, attrs, caller) {
_triggerEvent(listeners[eventName], attrs, caller);
var len = _triggerEvent(listenersOnce[eventName], attrs, caller);
if( len ) {
listenersOnce[eventName].splice(0, len);
}
};
target[method.off] = function (eventName, handler) {
if( handler === undefined ) {
_emptyListener(listeners[eventName]);
_emptyListener(listenersOnce[eventName]);
} else {
_removeListener(listeners[eventName], handler);
_removeListener(listenersOnce[eventName], handler);
}
};
}
return Events;
});
|
//用途:1.用于人员招聘模块 面试流程 2.客户管理
//2014-10-25 12:43 李晓彤
//----------------------------------------------------------面试流程-------------------------------------------------------------------
//创建预约
function showActDlg_DGItems(datagrid, title, msg, url, width, height) {
checkOnline()
var ids = [];
var rows = $("#" + datagrid).datagrid('getSelections');
getDeleteIDs(ids, rows, url, datagrid);
var log = 0;
for (var i = 0; i < rows.length; i++) {
if (rows[i]["Done"].trim() != '') {
log = rows[i]["Done"].trim();
break;
}
}
if (log == "已创建预约") {
$.messager.alert("提示", "已存在面试信息,无需再次预约");
return;
}
else if (log == "已转员工") {
$.messager.alert("提示", "已转员工,预约失败");
return;
}
else {
$.extend($.messager.defaults, {
ok: "确定", cancel: "取消"
})
$.messager.confirm(title, msg, function (r) {
if (r) {
$.ajax({
url: url + "?keys=" + ids,
type: "post",
success: function (result) {
if (!result.HasError) {
$.messager.alert("提示", "预约成功");
var rows = $("#" + datagrid).datagrid('getSelections');
for (var i = 0; i < result.Data.length; i++) {
var indexs = $("#" + datagrid).datagrid('getRowIndex', rows[i]);
$("#" + datagrid).datagrid('updateRow', {
index: indexs, row: result.Data[i]
});
toolIsShow();//刷新tool按钮状态
}
}
else {
$.messager.alert("提示", result.ErrorMessage);
}
},
error: function (xmlhttprequest, text, error) {
showError(error);
}
});
}
else {
cancel();
}
});
}
}
//预约面试邮件发送界面
function showActDlg_DG_YuYueEmails(datagrid, title, url, width, height) {
checkOnline()
var ids = [];
var flag = 0;
var msg = [];
var rows = $("#" + datagrid).datagrid('getSelections');
for (var i = 0; i < rows.length; i++) {
if (rows[i]['AppointmentRresult'].trim() == '预约成功') {
if (rows[i]["AuditionRresult"].trim() == '通过' || rows[i]["AuditionRresult"].trim() == '未通过')
{ msg = "面试已结束,不能发送预约邮件!"; flag = 1; break; }
else ids.push(rows[i]['RID']);
}
else { msg = "面试预约未成功,不能发送预约邮件!"; flag = 1; break; }
}
if (flag == 0) {
url = url + "?keys=" + ids;
showDialog(url, title, width, height);
}
else {
$.messager.alert("提示", msg);
}
}
//通知报到邮件发送界面
function showActDlg_DG_BaoDaoEmails(datagrid, title, url, width, height) {
checkOnline()
var ids = [];
var flag = 0;
var msg = [];
var rows = $("#" + datagrid).datagrid('getSelections');
for (var i = 0; i < rows.length; i++) {
if (rows[i]['Noticed'].trim() == '同意报到') {
if (rows[i]["IsToEmployee"].trim() == '已转员工')
{ msg = "已转员工,不能发送通知报到邮件!"; flag = 1; break; }
else ids.push(rows[i]['RID']);
}
else { msg = "通知报到未成功,不能发送通知报到邮件!"; flag = 1; break; }
}
if (flag == 0) {
url = url + "?keys=" + ids;
showDialog(url, title, width, height);
}
else {
$.messager.alert("提示", msg);
}
}
//邮件发送
function funcForSendEmail(data, url, datagrid) {
checkOnline()
$.ajax({
url: url,
type: "post",
data: data,
dataType: "json",
success: function (result) {
if (!result.HasError) {
$.messager.alert('提示', '邮件发送成功!')
var rows = $("#" + datagrid).datagrid('getSelections');
for (var i = 0; i < result.Data.length; i++) {
var indexs = $("#" + datagrid).datagrid('getRowIndex', rows[i]);
$("#" + datagrid).datagrid('updateRow', { index: indexs, row: result.Data[i] });
}
toolIsShow();//刷新tool按钮状态
setTimeout("cancel()", 3000);
}
else {
showError(result.ErrorMessage);
}
},
error: function (d, error) {
showError(error);
}
});
}
//添加预约结果 李晓彤 2014-10-23
function showActDlg_DGItemActDlgYuYue(datagrid, title, url, width, height) {
checkOnline()
var rows = $("#" + datagrid).datagrid('getSelected');
if (rows["Done"] == 0) {
$.messager.alert("提示", "请先创建预约信息");
}
else if (rows["AuditionRresult"].trim() == '未通过' || rows["AuditionRresult"].trim() == '通过') {
$.messager.alert("提示", "面试已结束,预约信息无法修改");
}
else {
url = url + "?ID=" + rows["RID"];
showDialog(url, title, width, height);
toolIsShow();//刷新tool按钮状态
}
}
//面试结果录入 李晓彤 2014-10-23
function showActDlg_DGItemActDlgMianShi(datagrid, title, url, width, height) {
checkOnline()
var rows = $("#" + datagrid).datagrid('getSelected');
if (rows["AuditRresult"].trim() == '未通过' || rows["AuditRresult"].trim() == '通过') {
$.messager.alert("提示", "审核已结束,面试信息无法修改");
}
else {
url = url + "?ID=" + rows["RID"];
showDialog(url, title, width, height)
}
}
//入职审核 李晓彤 2014-10-23
function showActDlg_DGItemActDlgShenHe(datagrid, title, url, width, height) {
checkOnline()
var rows = $("#" + datagrid).datagrid('getSelected');
if (rows["Noticed"].trim() == '同意报到' || rows["Noticed"].trim() == '不同意报到') {
$.messager.alert("提示", "通知报到已结束,审核信息无法修改");
}
else {
url = url + "?ID=" + rows["RID"];
showDialog(url, title, width, height)
}
}
//通知报到 李晓彤 2014-10-23
function showActDlg_DGItemActDlgBaoDao(datagrid, title, url, width, height) {
checkOnline()
var rows = $("#" + datagrid).datagrid('getSelected');
if (rows["IsToEmployee"].trim() == '已转员工') {
$.messager.alert("提示", "已转员工,信息无法修改");
}
else {
url = url + "?ID=" + rows["RID"];
showDialog(url, title, width, height)
toolIsShow();//刷新tool按钮状态
}
}
//转员工 李晓彤 2014-10-23
function showActDlg_DGItemActDlgToEmployee(datagrid, title, url, width, height) {
var rows = $("#" + datagrid).datagrid('getSelected');
if (rows["IsToEmployee"].trim() == '已转员工') {
$.messager.alert("提示", "已转员工,无需再次操作");
}
else {
url = url + "?ID=" + rows["RID"];
showDialog(url, title, width, height)
}
}
//清理表中数据(无参数)
function showActDlg_DGItemsClearData(datagrid, title, msg, url) {
checkOnline()
$.messager.confirm(title, msg, function (r) {
if (r) {
$.ajax({
url: url,
type: 'post',
success: function (result) {
if (!result.HasError) {
var rows = result.Data;
$.messager.alert('提示', '已清理' + rows.length + '条数据');
var gridrows = $("#" + datagrid).datagrid('getRows')
for (var i = 0; i < gridrows.length; i++) {
for (var j = 0; j < rows.length; j++) {
if (gridrows[i]['RID'] == rows[j].RID) {
$('#' + datagrid).datagrid('updateRow', {
index: i,
row: {
IsToEmployee: '已无效'
}
});
break;
}
}
}
}
}
})
}
})
}
//结束招聘
function showActDlg_DGItemsOver(datagrid, title, msg, url, width, height) {
checkOnline()
$.extend($.messager.defaults, { ok: "确定", cancel: "取消" })
$.messager.confirm(title, msg, function (r) {
if (r) {
var ids = [];
var rows = $("#" + datagrid).datagrid('getSelections');
getDeleteIDs(ids, rows, url, datagrid)
$.ajax({
url: url + "?keys=" + ids,
type: "post",
success: function (result) {
if (!result.HasError) {
$.messager.alert("提示", "操作成功!");
var rows = $("#" +datagrid).datagrid('getSelections') ;
for (var i = 0; i < result.Data.length; i++) {
var indexs = $("#" +datagrid).datagrid('getRowIndex', rows[i]);
$("#" +datagrid).datagrid('updateRow', {index: indexs, row: result.Data[i]});
}
toolHide();
}
else {
$.messager.alert("提示", result.ErrorMessage);
}
},
error: function (xmlhttprequest, text, error) {
showError(error);
}
});
}
else {
cancel();
}
});
}
//员工建档-创建账户 李晓彤 2014-11-21
function showActDlg_DGItemCreateUser(datagrid, title, msg, url) {
checkOnline()
$.messager.confirm(title, msg, function (r) {
if (r) {
var rows = $("#" + datagrid).datagrid("getSelections");
var selectCol = $("#" +datagrid).datagrid('options').columns[0][0].field;
var error = 0;
var errorMsg = '';
for (var i = 0; i < rows.length; i++) {
$.ajax({
url: url + '?ID=' + rows[i]['EmployeeID'],
type: 'post',
success: function (result) {
if (!result.HasError) {
$("#" + datagrid).datagrid('reload');
$('#' + datagrid).datagrid('updateRow', {
index: $("#" + datagrid).datagrid("getRowIndex", rows[i]),
row: result.Data[0]
});
toolIsShow();//刷新tool按钮状态
}
else {
error = 1;
errorMsg = result.ErrorMessage;
}
}
})
if (error == 1)
break;
}
if (error == 0) {
$.messager.alert('提示', '创建账户成功!');
}
else {
$.messager.alert('提示', errorMsg);
}
}
});
}
//----------------------------------------------------------客户管理-------------------------------------------------------------------
//批量编辑(多字段) 李晓彤2014-11-11(没用上)
function showActDlg_DGItems_ActDlg(datagrid, colunms, title, url, width, height) {
url = url + "?"
var items = colunms.split(",");
var rows = $("#" + datagrid).datagrid('getSelections');
for (var i = 0; i < items.length; i++) {
var colunmName = [];
for (var j = 0; j < rows.length; j++) {
colunmName.push(rows[j][items[i]]);
}
url = url + items[i] + "=" + colunmName;
if (i + 1 < items.length)
url = url + "&";
}
alert(url);
showDialog(url, title, width, height)
}
//打开对话框操作数据,保存后表中数据隐藏(title为操作方法)李晓彤2014-11-12(管理员公海领取)
function submitAct_DGOperate(form, title, url, datagrid) {
checkOnline()
if ($("#" + form).form('validate')) {
var rows = $("#" + datagrid).datagrid('getSelections');
$.ajax({
url: url,
type: "post",
data: $("#" + form).serialize(),
dataType: "json",
success: function (result) {
if (!result.HasError) {
cancel();
for (var i = 0; i < rows.length; i++) {
var index = $("#" + datagrid).datagrid('getRowIndex', rows[i]);
$("#" + datagrid).datagrid('deleteRow', index);
}
toolHide();
//if (title.charAt(0) == ' ') {
// $.messager.alert("提示", title);
//}
//else {
// $.messager.alert("提示", "已" + title + rows.length + "条记录");//李晓彤 2014光棍节,打开对话框对数据进行操作(操作完不显示)也可以引用
//}
$.messager.alert("提示", "已" + title + rows.length + "条记录");//李晓彤 2014光棍节,打开对话框对数据进行操作(操作完不显示)也可以引用
}
else {
showError(result.ErrorMessage);
}
},
error: function (d, error) {
showError(error);
}
});
}
}
//带有上限个数的新增 李晓彤 2014-11-13
function showActDlg_LimitAdd(title, msg, url, limitUrl, limitColumnName) {
checkOnline()
$.ajax({
url: limitUrl,
type: 'post',
success: function (result) {
if (!result.HasError) {
var num = result.Data[0][limitColumnName];
if (num <= 0)
$.messager.alert('提示', msg, 'info');
else
showDialog(url, title, 400, 300)
}
else {
$.messager.alert("提示", result.ErrorMessage);
}
}
})
}
//带有上限个数的公海领取 李晓彤 2014-11-13
function showActDlg_DGItemsCheckResidue(datagrid, title, msg, url) {
checkOnline()
var rows = $("#" + datagrid).datagrid('getSelections');
$.ajax({
url: '/Page/P01072/GetResidue',
type: 'post',
success: function (result) {
if (!result.HasError) {
var num = result.Data[0]['Residue'];
if (rows.length > num) {
$.messager.alert('提示', '新增及领取客户已达上限,无法选取!', 'info');
}
else {
showActDlg_DGItemsConfirm(datagrid, title, msg, url, 400, 300)
}
}
else {
$.messager.alert("提示", result.ErrorMessage);
}
}
});
}
function changeDG(datagrid) {//测试用
alert("45")
var rows = $("#" + datagrid).datagrid('getSelections');
for (var i = 0; i < rows.length; i++) {
alert(rows[i].RID)
var index = $("#" + datagrid).datagrid('getRowIndex', rows[i].RID);
alert(index)
$('#' + datagrid).datagrid('updateRow', {
index: index,
row: {
AuditRresult: '新消息'
}
});
}
}
//----------------------------------------------------------固定资产-------------------------------------------------------------------
var reload_dataPanDian = {};
function submitAct_DGReplacePanDian(form, url, datagrid) {
reload_dataPanDian = $("#" + form).serialize();
if ($("#" + form).form('validate')) {
var grid = $("#" + datagrid);
if (grid.datagrid('options').url != null) {
grid.datagrid('load', serializeObject($("#" + form).form()));
grid.datagrid({
onLoadSuccess: function (data) {
if (data.total == 0) {
grid.datagrid('options').queryParams = '';
$('#btn-export').linkbutton('disable');
}
else {
$('#btn-export').linkbutton('enable');
}
}
});
}
else {
grid.datagrid({
url: url,
queryParams: serializeObject($("#" + form).form()),
});
}
cancel();
toolHide();
}
}
//导出盘点文件
function funcExportPanDian(url) {
console.log(reload_dataPanDian)
$.download(url, reload_dataPanDian, 'post');
//$.ajax({
// url: url,
// type: 'post',
// data: reload_dataPanDian,
// success: function (result) {
// console.log('4545')
// // var data = $.parseJSON(result);
// // if (data.HasError) {
// // if (data.ErrorMessage == '') {
// // }
// // }
// },
// error: function (d, error) {
// showError(error);
// }
//});
}
|
var page = new tabris.Page({
title: 'Hello, World!',
topLevel: true
});
var button = new tabris.Button({
text: 'Login',
layoutData: {centerX: 0, top: 100}
}).appendTo(page);
button.on('select', function() {
window.plugins.googleplus.login(
{
},
function (obj) {
navigator.notification.alert(obj);
},
function (msg) {
navigator.notification.alert(msg)
}
);
});
page.open();
|
import react from "react";
import Hook from "./styletheme";
import LearnMore from "./LearnMore";
import { useState, useEffect } from "react";
import * as React from "react";
import Card from "@mui/material/Card";
import CardActions from "@mui/material/CardActions";
import CardContent from "@mui/material/CardContent";
import CardMedia from "@mui/material/CardMedia";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import { Grid } from "@material-ui/core";
import { BrowserRouter as Router, Link, Switch, Route } from "react-router-dom";
import Pagination from "@mui/material/Pagination";
import Stack from "@mui/material/Stack";
import { textAlign } from "@mui/system";
import Divider from "@mui/material/Divider";
const FetchData = ({ card, setCard }) => {
const [Data, setData] = useState([]);
// const [date,setDate]= useState(["2021-10-10"]);
const getData = async () => {
const response = await fetch(
`https://newsapi.org/v2/everything?q=Apple&from=2021-10-10&sortBy=popularity&apiKey=${process.env.REACT_APP_apiKey}&pageSize=100`
// "https://newsapi.org/v2/everything?q=Apple&from=2021-10-10&sortBy=popularity&apiKey=12e4f2419663442e871227574db19ac6"
);
const arr = await response.json();
console.log(arr);
setData(arr);
};
useEffect(() => {
getData();
// getData(2021-9-11);
}, []);
console.log(Data);
const [currentPage, setCurrentPage] = useState(1);
function changeData(event) {
const pageNumber = Number(event.target.textContent);
setCurrentPage(pageNumber);
}
let dataPerPage = 10;
const indexOfFirst = currentPage * dataPerPage - dataPerPage;
const indexOfLast = indexOfFirst + dataPerPage;
return (
<>
<div>
<h1 className="mainheader">Media Application</h1>
</div>
<Divider />
<Stack spacing={2}>
<Pagination count={10} onClick={changeData} color="primary" />
</Stack>
<Grid container spacing={4} className="grid">
{Data.articles &&
Data.articles
.slice(indexOfFirst, indexOfLast)
.map((currentElement) => {
return (
<>
<Grid
item
xs={12}
sm={6}
md={4}
xl={3}
justifyContent="space-evenly"
key={currentElement.publishedAt}
>
<Card elevation={12} className="cards">
<CardMedia
component="img"
alt=""
height="140"
image={currentElement.urlToImage}
/>
<CardContent>
<Typography gutterBottom variant="h5" component="div">
{currentElement.title}
</Typography>
<Typography variant="body2" color="text.secondary">
{/* {currentElement.description} */}
</Typography>
</CardContent>
<CardActions>
{/* <Router>
<Switch>
<Route path ={currentElement.title.replaceAll(" ","/")} component={LearnMore} description={currentElement.description}/>
</Switch>
</Router> */}
{/* {currentElement.title.replaceAll(" ","/")} */}
<Button
size="small"
onClick={() => {
setCard(currentElement);
}}
>
<Link to={currentElement.title.replaceAll(" ", "-")}>
LearnMore
</Link>
</Button>
</CardActions>
</Card>
</Grid>
</>
);
})}
{/* {setDate("2021-10-11")} */}
</Grid>
</>
);
};
export default FetchData;
|
define([
'angular'
, './namespace'
, 'ngTimeline'
],
function (angular, namespace) {
'use strict';
/*
Sepacial for search engine
diff widgets:
1. abbr. widgets according to the query string
2. categoried result page according to the query string with loadMore pager={page:n, pageSize:n, count:n}
add a state parameter coming from to maintain the indicator for naving page back
directive indicates with links about which state to go to
search within each module itself
$ionicFilterBar.show
an directive to detect if any go back workable for tab view
two sets of state but the same templates
*/
return angular.module(namespace, ['angular-timeline']);
});
|
import { Platform } from 'react-native';
import Firebase from './index';
// TODO:
// move services/Firebase functionality to services FBKit,
// and refuse to use services/Firebase in project
export default class FBStorage {
static uploadFile(
file, type, objectId, path,
metadata = { contentType: 'application/octet-stream' },
) {
return new Promise((resolve, reject) => {
const fileRef = Firebase.storage.ref(`${path}/${type}/${objectId}`);
fileRef.put(file, metadata)
.then(() => {
return fileRef.getDownloadURL();
}).then((url) => {
console.log(`File succeeded to upload with URL: ${url}`);
resolve(url);
}).catch((error) => {
console.log(`File ${file} failed to upload with error: ${error}`);
reject(error);
});
});
}
static uploadDocument(document, type, objectId) {
const documentsPath = 'documents';
if (Platform.OS === 'web') {
const metadata = {
contentType: type || 'application/octet-stream',
};
return FBStorage.uploadFile(document, type, objectId, documentsPath, metadata);
}
}
}
|
/* eslint-disable no-unused-vars */
import React, { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { Modal } from "react-bootstrap";
import styles from "../../styles/confirmdelete.module.css";
export default function ConfirmDelete(props) {
const {isDeletePending} = useSelector(state => state.products)
return (
<Modal
{...props}
style={{ zIndex: 1050, outline: "none" }}
size='md'
aria-labelledby='contained-modal-title-vcenter'
centered>
<Modal.Body>
<div className={styles.body}>
<div className={styles.title}>
<h5>Delete Product</h5>
</div>
<h6 style={{marginTop:"15px"}} >Are you sure to delete <span style={{color:"#f24f8a", fontSize: "1.3em" ,fontWeight:"900"}}>{props.name}</span> from Food Items ?</h6>
<div className={styles.btncontainer} >
<button
onClick={() => {
props.onHide()
}}
style={{
outline: "none",
}}
className={styles.btncancel}>
Cancel
</button>
<button
onClick={() => {
props.handleDelete()
}}
style={{
outline: "none",
}}
className={styles.btndelete}>
{isDeletePending?(<i className='fa fa-spinner fa-spin fa-2x fa-fw'></i>):"Delete"}
</button>
</div>
</div>
</Modal.Body>
</Modal>
);
}
|
import * as actions from '../actions/actionTypes';
const initialState = {
category:[],
isPending:false,
isFulfilled: false,
isRejected: false,
};
const categoryReducers = (state = initialState,action)=>{
switch (action.type){
case actions.fetchCategory + actions.pending:
return {
...state,
isPending:true,
};
case actions.fetchCategory + actions.rejected:
return {
...state,
isRejected:true,
error:action.payload,
isPending:false,
};
case actions.fetchCategory + actions.fulfilled:
return {
...state,
isFulfilled:true,
category:action.payload.data.results,
isPending:false,
};
default:
return state;
}
};
export default categoryReducers;
|
// block_huntingPost.js
// for DanIdle version 4
// The place where players hunt for nearby game animals. Produces meats, along with other animal-based resources (such as furs, bones and feathers)
import { blockOutputsItems, blockShowsOutputItems, blockHasWorkerPriority, blockDeletesClean } from "./activeBlock.js";
import { blockHasRandomizedOutput } from "./blockAddon_HasRandomizedOutput.js";
import { blockRequiresTool } from "./blockAddon_RequiresTool.js";
import { game } from "./game.js";
import $ from "jquery";
export const huntingPost = mapSquare => {
let state = {
name: "huntingPost",
tile: mapSquare,
id: game.getNextBlockId(),
counter: 0,
allowOutput: true,
//outputitems: [{name: "None"}] - but wait - this has randomized output - not user-selected output
outputItems: [
{ name: "Dead Deer", isFood: false },
{ name: "Dead Wolf", isFood: false },
{ name: "Dead Chicken", isFood: false }
],
toolChoices: [{ groupName: "Spear", isRequired: true, choices: ["None", "Flint Spear"] }],
craftTime: 30,
// possibleOutputs is defined in HasRandomizedOutput
inputsAccepted() {
// This does not have any inputs
return [];
},
// willOutput() is already defined in blockOutputsItems
willAccept() {
// Returns true if this block will accept the specified item right now.
// This block has no (item) input
return false;
},
receiveItem() {
// Accepts an item as input. Returns true when successful, or false if not.
// This item does not accept any input items.
return false;
},
update() {
// Start by checking the size of our onhand array
if (state.onhand.length > 15) return;
// Next, verify our tools will allow us to continue
if (game.workPoints <= 0) return;
const eff = state.checkTool();
if (eff === null) return;
state.processCraft(eff);
},
drawPanel() {
$("#sidepanel").html(`
<b>Hunting Post</b><br />
<br />
Humans are not herbivores. They require meats equally as much as plants. Without good sources of both, the body will
struggle to survive.<br />
<br />
Uses weapons to hunt game animals in the area. Once killed, brings the animals back here for further uses.<br />
<br />
`);
state.showPriority();
$("#sidepanel").append(`
<br />
Hunting progress: <span id="sidepanelprogress">${Math.floor(
(this.counter * 100) / state.craftTime
)}</span>%<br />
`);
state.showDeleteLink();
$("#sidepanel").append("<br /><br />");
state.showOutput();
state.showTools();
},
updatePanel() {
// Handle updating any fields in the side panel that may change between ticks
$("#sidepanelprogress").html(Math.floor((this.counter * 100) / state.craftTime));
state.updateOutput();
state.updateToolPanel();
},
deleteBlock() {
state.finishDelete();
}
};
game.blockList.push(state);
mapSquare.structure = state;
$("#" + state.tile.id + "imageholder").html('<img src="img/huntingPost.png" />');
return Object.assign(
state,
blockOutputsItems(state),
blockShowsOutputItems(state),
blockRequiresTool(state),
blockHasWorkerPriority(state),
blockDeletesClean(state),
blockHasRandomizedOutput(state)
);
};
|
/*
* @akoenig/website
*
* Copyright(c) 2017 André König <andre.koenig@gmail.com>
* MIT Licensed
*
*/
/**
* @author André König <andre.koenig@gmail.com>
*
*/
import styled from "styled-components";
const Social = styled.ul`
display: flex;
margin: 0;
padding: 0;
list-style-type: none;
@media (max-width: 390px) {
display: none;
}
`;
const SocialIcon = styled.li`
display: flex;
margin: 0;
margin-left: 0.6em;
padding: 0;
&:first-child {
margin-left: 0;
}
& svg {
fill: rgba(0, 0, 0, 0.2);
height: 18px;
width: 18px;
transition: fill 0.2s ease-in-out;
}
&:hover svg {
fill: #f44336;
}
`;
const SocialLink = styled.a`
color: rgba(0, 0, 0, 0.3);
transition: color 0.2s ease-in-out;
&:hover {
color: #f44336;
text-decoration: none;
}
`;
export { Social, SocialIcon, SocialLink };
|
const Example = require("../models/example.model");
module.exports.findAllExamples = (req, res) => {
console.log("im trying to find all the examples!!!");
Example.find()
.then((allExamples) => res.json({ results: allExamples }))
.catch((err) => res.json(err));
};
module.exports.createNewExample = (req, res) => {
console.log("im trying to create some examples here!!!!!");
Example.create(req.body)
.then((newExample) => res.json({ results: newExample }))
.catch((err) => res.json(err));
};
module.exports.findOneExample = (req, res) => {
console.log("example id to find", req.params.exampleId);
Example.findOne({ _id: req.params.exampleId })
.then((selectedExample) => res.json({ results: selectedExample }))
.catch((err) => res.json(err));
};
module.exports.updateExample = (req, res) => {
Example.findOneAndUpdate({ _id: req.params.exampleId }, req.body, {
new: true,
runValidators: true,
useFindAndModify: false,
})
.then((updatedExample) => res.json({ results: updatedExample }))
.catch((err) => res.json(err));
};
module.exports.deleteExample = (req, res) => {
Example.findByIdAndDelete(req.params.exampleId)
.then((deletedExample) => res.json({ results: deletedExample }))
.catch((err) => res.json(err));
};
|
// ROUTES
// app.get("/articles", (req, res) => {
// Article.find((err, result) => {
// if (err) {
// res.send(err);
// } else {
// res.send(result);
// }
// });
// });
// post data to db
// app.post("/articles", (req, res) => {
// const newArticle = new Article({
// title: req.body.title,
// content: req.body.content,
// });
// newArticle.save((err, result) => {
// if (err) {
// res.send(err);
// } else {
// res.send("Your new articale send succefully");
// }
// });
// });
// delete all data from db
// app.delete("/articles",(req,res)=>{
// Article.deleteMany((err)=>{
// if (err) {
// res.send(err);
// } else {
// res.send("All articales deleted succefully");
// }
// });
// });
|
var orm = require("../config/orm.js");
var burger = {
burgerAll : function(cb){
orm.burgerAll("burgerlist",function(err,data){
cb(err,data);
});
},
burgerCreate : function(burgeName,cb){
orm.burgerCreate("burgerlist","burger_name",burgeName,function(err,data){
cb(err,data);
});
},
burgerUpdateState : function(id,cb){
orm.burgerUpdateState("burgerlist", "eaten_state", "id",id,function(err,data){
cb(err,data);
});
},
burgerDelete : function(id,cb){
orm.burgerDelete("burgerlist", "id", id,function(err,data){
cb(err,data);
});
}
}
module.exports = burger;
|
module.exports = require('./configs/eslint/node');
|
/*!
* froala_editor v2.7.2 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2017 Froala Labs
*/
!function (a) {
"function" == typeof define && define.amd ? define(["jquery"], a) : "object" == typeof module && module.exports ? module.exports = function (b, c) {
return void 0 === c && (c = "undefined" != typeof window ? require("jquery") : require("jquery")(b)), a(c)
} : a(window.jQuery)
}
(function (a) {
a.extend(a.FE.POPUP_TEMPLATES, {
champions: "[_BUTTONS_][_CHAMPIONS_]"
}), a.extend(a.FE.DEFAULTS, {
emoticonsStep: 8, emoticonsSet: [{code: "Quinn", desc: "Quinn"},
{code: "Ezreal", desc: "Ezreal"},
{code: "Jinx", desc: "Jinx"},
{code: "Caitlyn", desc: "Caitlyn"}],
championsButtons: ["championsBack", "|"], championsUseImage: !0
}),
a.FE.PLUGINS.champions = function (b) {
function c() {
var a = b.$tb.find('.fr-command[data-cmd="champions"]'), c = b.popups.get("champions");
if (c || (c = e()), !c.hasClass("fr-active")) {
b.popups.refresh("champions"), b.popups.setContainer("champions", b.$tb);
var d = a.offset().left + a.outerWidth() / 2,
f = a.offset().top + (b.opts.toolbarBottom ? 10 : a.outerHeight() - 10);
b.popups.show("champions", d, f, a.outerHeight())
}
}
function d() {
b.popups.hide("champions")
}
function e() {
var a = "";
b.opts.toolbarInline && b.opts.championsButtons.length > 0 && (a = '<div class="fr-buttons fr-champions-buttons">' + b.button.buildList(b.opts.championsButtons) + "</div>");
var c = {
buttons: a, champions: g()
}, d = b.popups.create("champions", c);
return b.tooltip.bind(d, ".fr-emoticon"), h(d), d
}
function f() {
if (!b.selection.isCollapsed()) return !1;
var a = b.selection.element(), c = b.selection.endElement();
if (a && b.node.hasClass(a, "fr-emoticon")) return a;
if (c && b.node.hasClass(c, "fr-emoticon")) return c;
var d = b.selection.ranges(0), e = d.startContainer;
if (e.nodeType == Node.ELEMENT_NODE && e.childNodes.length > 0 && d.startOffset > 0) {
var f = e.childNodes[d.startOffset - 1];
if (b.node.hasClass(f, "fr-emoticon")) return f
}
return !1
}
function g() {
for (var a = '<div style="text-align: center"><p style="font-size: 12px; text-align: center; padding: 0 5px;">Champions</p>', c = 0; c < b.opts.emoticonsSet.length; c++) 0 !== c && c % b.opts.emoticonsStep == 0 && (a += "<br>"), a += '<span class="fr-command fr-emoticon" tabIndex="-1" data-cmd="insertEmoticon" title="' + b.language.translate(b.opts.emoticonsSet[c].desc) + '" role="button" data-param1="' + b.opts.emoticonsSet[c].code + '">' + (b.opts.emoticonsUseImage ? '<img src="http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/' + b.opts.emoticonsSet[c].code + '.png"/>' : "&#x" + b.opts.emoticonsSet[c].code + ";") + '<span class="fr-sr-only">' + b.language.translate(b.opts.emoticonsSet[c].desc) + " </span></span>";
return b.opts.emoticonsUseImage && (a += ''), a += "</div>"
}
function h(c) {
b.events.on("popup.tab", function (d) {
var e = a(d.currentTarget);
if (!b.popups.isVisible("champions") || !e.is("span, a")) return !0;
var f, g, h, i = d.which;
if (a.FE.KEYCODE.TAB == i) {
if (e.is("span.fr-emoticon") && d.shiftKey || e.is("a") && !d.shiftKey) {
var j = c.find(".fr-buttons");
f = !b.accessibility.focusToolbar(j, !!d.shiftKey)
}
if (!1 !== f) {
var k = c.find("span.fr-emoticon:focus:first, span.fr-emoticon:visible:first, a");
e.is("span.fr-emoticon") && (k = k.not("span.fr-emoticon:not(:focus)")), g = k.index(e), g = d.shiftKey ? ((g - 1) % k.length + k.length) % k.length : (g + 1) % k.length, h = k.get(g), b.events.disableBlur(), h.focus(), f = !1
}
} else if (a.FE.KEYCODE.ARROW_UP == i || a.FE.KEYCODE.ARROW_DOWN == i || a.FE.KEYCODE.ARROW_LEFT == i || a.FE.KEYCODE.ARROW_RIGHT == i) {
if (e.is("span.fr-emoticon")) {
var l = e.parent().find("span.fr-emoticon");
g = l.index(e);
var m = b.opts.emoticonsStep, n = Math.floor(l.length / m), o = g % m,
p = Math.floor(g / m), q = p * m + o, r = n * m;
a.FE.KEYCODE.ARROW_UP == i ? q = ((q - m) % r + r) % r : a.FE.KEYCODE.ARROW_DOWN == i ? q = (q + m) % r : a.FE.KEYCODE.ARROW_LEFT == i ? q = ((q - 1) % r + r) % r : a.FE.KEYCODE.ARROW_RIGHT == i && (q = (q + 1) % r), h = a(l.get(q)), b.events.disableBlur(), h.focus(), f = !1
}
} else a.FE.KEYCODE.ENTER == i && (e.is("a") ? e[0].click() : b.button.exec(e), f = !1);
return !1 === f && (d.preventDefault(), d.stopPropagation()), f
}, !0)
}
function i(c, d) {
var e = f(), g = b.selection.ranges(0);
e ? (0 === g.startOffset && b.selection.element() === e ? a(e).before(a.FE.MARKERS + a.FE.INVISIBLE_SPACE) : g.startOffset > 0 && b.selection.element() === e && g.commonAncestorContainer.parentNode.classList.contains("fr-emoticon") && a(e).after(a.FE.INVISIBLE_SPACE + a.FE.MARKERS), b.selection.restore(), b.html.insert('<span class="fr-emoticon fr-deletable' + (d ? " fr-emoticon-img" : "") + '"' + (d ? ' style="background: url(' + d + ');"' : "") + ">" + (d ? " " : c) + "</span> " + a.FE.MARKERS, !0)) : b.html.insert('<span class="fr-emoticon fr-deletable' + (d ? " fr-emoticon-img" : "") + '"' + (d ? ' style="background: url(' + d + ');"' : "") + ">" + (d ? " " : c) + "</span> ", !0)
}
function j() {
b.popups.hide("champions"), b.toolbar.showInline()
}
function k() {
var c = function () {
for (var a = b.el.querySelectorAll(".fr-emoticon:not(.fr-deletable)"), c = 0; c < a.length; c++) a[c].className += " fr-deletable"
};
c(), b.events.on("html.set", c), b.events.on("keydown", function (c) {
if (b.keys.isCharacter(c.which) && b.selection.inEditor()) {
var d = b.selection.ranges(0), e = f();
b.node.hasClass(e, "fr-emoticon-img") && e && (0 === d.startOffset && b.selection.element() === e ? a(e).before(a.FE.MARKERS + a.FE.INVISIBLE_SPACE) : a(e).after(a.FE.INVISIBLE_SPACE + a.FE.MARKERS), b.selection.restore())
}
}), b.events.on("keyup", function (c) {
for (var d = b.el.querySelectorAll(".fr-emoticon"), e = 0; e < d.length; e++) void 0 !== d[e].textContent && 0 === d[e].textContent.replace(/\u200B/gi, "").length && a(d[e]).remove();
if (!(c.which >= a.FE.KEYCODE.ARROW_LEFT && c.which <= a.FE.KEYCODE.ARROW_DOWN)) {
var g = f();
b.node.hasClass(g, "fr-emoticon-img") && (a(g).append(a.FE.MARKERS), b.selection.restore())
}
})
}
return {_init: k, insert: i, showEmoticonsPopup: c, hideEmoticonsPopup: d, back: j}
}, a.FE.DefineIcon("champions", {NAME: "smile-o"}), a.FE.RegisterCommand("champions", {
title: "Champions",
undo: !1,
focus: !0,
refreshOnCallback: !1,
popup: !0,
callback: function () {
this.popups.isVisible("champions") ? (this.$el.find(".fr-marker").length && (this.events.disableBlur(), this.selection.restore()), this.popups.hide("champions")) : this.champions.showEmoticonsPopup()
},
plugin: "champions"
}), a.FE.RegisterCommand("insertChampion", {
callback: function (a, b) {
this.champions.insert("&#x" + b + ";", this.opts.emoticonsUseImage ? "http://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/" + b + ".png" : null), this.champions.hideEmoticonsPopup()
}
}), a.FE.DefineIcon("championsBack", {NAME: "arrow-left"}), a.FE.RegisterCommand("championsBack", {
title: "Back",
undo: !1,
focus: !1,
back: !0,
refreshAfterCallback: !1,
callback: function () {
this.champions.back()
}
})
});
|
const mongoose = require("mongoose");
const DonutStoreSchema = new mongoose.Schema({
place_id: String,
name: String,
formatted_address: String,
rating: Number,
photo: {
html_attributions: String,
height: Number,
width: Number,
photo_reference: String,
},
weekday_text: String,
bucketlists: {
type: [mongoose.Schema.Types.ObjectId],
ref: "Bucketlist"
}
})
const DonutStore = mongoose.model("DonutStore", DonutStoreSchema);
module.exports = DonutStore;
|
import React, { Component, lazy, Suspense } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import Layout from './components/layout/Layout';
import BurgerBuilder from './container/BurgerBuilder';
// import Checkout from './container/Checkout/Checkout';
// import Orders from './container/Orders/Oreders';
import Auth from './container/Auth/Auth';
import Logout from './container/Auth/Logout/Logout';
import * as actions from './store/actions/index';
import asyncComponent from './hoc/asyncComponent/asyncComponent';
// import Spinner from './components/UI/Spinner/Spinner';
const asynCheckout = asyncComponent(() => import('./container/Checkout/Checkout'));
const asynOrder = asyncComponent(() => import('./container/Orders/Oreders'));
const asynAuth = asyncComponent(() => import('./container/Auth/Auth'));
class App extends Component {
componentDidMount() {
this.props.onTryAutoSignup();
}
render() {
let routes = (
<Switch>
<Route path="/auth" component={asynAuth} />
<Route path="/" exact component={BurgerBuilder} />
<Redirect to="/" />
</Switch>
);
if (this.props.isAuth) {
routes = (
<Switch>
<Route path="/auth" component={asynAuth} />
<Route path="/checkout" component={asynCheckout} />
<Route path='/orders' component={asynOrder} />
<Route path='/logout' component={Logout} />
<Route path="/" exact component={BurgerBuilder} />
<Redirect to="/" />
</Switch>
)
}
return (
<div>
<Layout>
{routes}
</Layout>
</div>
);
}
}
const mapStateToProps = state => {
return {
isAuth: state.auth.token !== null
}
}
const mapDispatchToProps = dispatch => {
return {
onTryAutoSignup: () => dispatch(actions.checkAuthState())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
import React from "react"
import { Link, graphql } from "gatsby"
import { node } from "prop-types"
import { css } from "@emotion/core"
import Layout from "../components/layout"
const AllProducts = ({ data }) => {
const product = data.allShopifyProduct
console.log("this is product: ", product)
console.log("this is img", product.nodes[0].images[0].originalSrc)
let productMap = product.nodes.map((product, i) => (
<div key={product.id} className="col-md-4">
<Link to={`/product/${product.handle}/`}>
<div className="card card-product-grid">
<div className="img-wrap">
<img src={product.images[0].originalSrc} alt={product.title} />
</div>
<h3>{product.title}</h3>
<div className="price-wrap mt-2">
<span className="price">
${product.priceRange.maxVariantPrice.amount}
</span>
</div>
{/* {product.variants.length > 1
? product.variants.map(variant => (
<div key={variant.title}>
<p>{variant.title}</p>
</div>
))
: null} */}
</div>
</Link>
</div>
))
return <Layout>{productMap}</Layout>
}
export const query = graphql`
{
allShopifyProduct(filter: { availableForSale: { eq: true } }) {
nodes {
title
shopifyId
tags
id
handle
productType
images {
originalSrc
}
priceRange {
maxVariantPrice {
amount
}
}
productType
variants {
title
shopifyId
image {
localFile {
childImageSharp {
original {
width
height
src
}
}
}
}
title
priceV2 {
amount
currencyCode
}
sku
product {
productType
}
}
}
}
}
`
export default AllProducts
// ref:
// https://dev.to/idiglove/display-shopify-collections-in-your-gatsby-ecommerce-site-2459
// https://owlypixel.com/build-a-store-with-shopify-and-gatsby/#create-account
// const Product = ({ product }) => {
// return (
// <div>
// <h2>{product.title}</h2>
// </div>
// )
// };
// export default ({ data }) => {
// return (
// <>
// <h1>test homepage</h1>
// {data.allShopifyProduct.nodes.map(({ product }) => (
// <Product key={product.id} product={product} />
// ))}
// <pre>{JSON.stringify(data, null, 2)}</pre>
// </>
// )
// }
|
import React from 'react'
import { AppContainer } from '../components'
export default () => (
<AppContainer>
<h1>Hello About!</h1>
</AppContainer>
)
|
import React from "react";
import { View } from "react-native";
import { StyleSheet, Text, Image, TouchableOpacity, FlatList } from 'react-native';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { Feather } from '@expo/vector-icons';
import { Ionicons } from '@expo/vector-icons';
import Bikelist from "../components/bikelist";
export default function cartlist({navigation}){
return(
<View>
<View style={styles.topnav}>
<TouchableOpacity onPress={() => {navigation.navigate("home")}}>
<Ionicons name="arrow-back" size={30} color="black" />
</TouchableOpacity>
<Text style={styles.cartText}>Cart list</Text>
</View>
<Text style={styles.title2}>(3 items)</Text>
<View style={styles.bikes}>
<FlatList
data={Bicycles}
renderItem={({item}) => {
return (
<Bikelist
bikename={item.bikename}
price={item.price}
type={item.type}
image={item.image}
/>
);
}}
keyExtractor={item => {
item.id;
}}
/>
</View>
<View style={styles.cost}>
<View style={styles.subtotal}>
<Text style={styles.look}>Subtotal</Text>
<Text style={styles.dollar}> $</Text>
<Text style={styles.money}> 64,180.00</Text>
</View>
<View style = {styles.shipfee}>
<Text style={styles.look}>Shipping fee</Text>
<Text style={styles.dollar}> $</Text>
<Text style={styles.money}> 1,000.00</Text>
</View>
<View>
<Text>........................................................................................</Text>
</View>
<View style={styles.total}>
<Text style={styles.money}>Total</Text>
<Text style={styles.dollar}> $</Text>
<Text style={styles.money}> 65,180.00</Text>
</View>
</View>
<View style={styles.checkoutView}>
<TouchableOpacity style ={styles.checkoutbutton}>
<Text style={styles.checkoutText}>Proceed to Checkout</Text>
</TouchableOpacity>
</View>
<View style = {styles.hometab}>
<TouchableOpacity onPress={() => {navigation.navigate("home")}} style = {styles.homebutton}>
<AntDesign name="home" size={35} color="black" />
</TouchableOpacity>
<TouchableOpacity style = {styles.MicButton}>
<Ionicons name="mic-circle-sharp" size={75} color="black" />
</TouchableOpacity>
<TouchableOpacity style={styles.bagbutton}>
<Feather name="shopping-bag" size={35} color="#ff792f" />
</TouchableOpacity>
</View>
</View>
);
}
const Bicycles = [
{
id: '1',
bikename: 'Santa Cruzz Bike',
type: "Urban",
price: '1,700.00',
image: require('../assets/blue.png'),
},
{
id: '2',
bikename: 'Polygod Bike',
type: "Mountain",
price: '1,500.00',
image: require('../assets/polygod.png'),
},
{
id: '4',
bikename: 'H2R Bike',
type:"Roadbike",
price: '60,980.00',
image: require('../assets/h2r1000.png'),
},
];
const styles = StyleSheet.create({
topnav:{
flexDirection:"row",
marginTop:50,
marginLeft:15,
},
cartText:{
fontSize:20,
fontWeight:"bold",
marginLeft:120,
},
title2:{
fontSize:17,
marginLeft:168,
marginTop:-8,
color:"gray",
},
checkoutView:{
},
checkoutbutton:{
marginTop:3,
margin:"8%",
backgroundColor:"#ff792f",
borderRadius:15,
padding:20,
},
checkoutText:{
color:"white",
textAlign:"center",
fontSize: 20,
fontWeight:"bold",
},
hometab: {
backgroundColor:"#e6e6e6",
marginTop:20,
flexDirection: "row",
paddingBottom:50,
paddingTop:15,
},
homebutton: {
marginLeft: 70,
},
MicButton: {
marginLeft: 70,
marginTop: -55,
},
bagbutton: {
left: 70,
},
bikes:{
margin:"5%",
marginTop:5,
},
cost:{
marginTop:10,
backgroundColor:"#e6e6e6",
margin:"7%",
borderRadius:30,
},
subtotal:{
flexDirection:"row",
marginLeft:30,
marginTop:30,
},
shipfee:{
flexDirection:"row",
marginLeft:30,
marginTop:20,
},
total:{
flexDirection:"row",
marginTop:30,
marginBottom:25,
marginLeft:30,
},
dollar:{
fontSize:12,
fontWeight:"bold",
color:"#ff792f",
marginTop:-10,
marginLeft:115,
},
money:{
fontSize:18,
fontWeight:"bold",
marginTop:-15,
},
look:{
fontSize: 17,
color:"gray",
marginTop:-15,
}
});
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { AppBar, MenuItem, Divider } from 'material-ui';
import NavDrawer from '../navigators/NavDrawer';
import { fetchMenus, nextMenu, prevMenu } from '../actions/MenuActions';
import { grey800 } from 'material-ui/styles/colors';
const SCREEN_WIDTH = window.innerWidth;
const SCREEN_HEIGHT = window.innerHeight;
class Menu extends Component {
state = {
drawerOpen: false
};
componentDidMount = () => {
this.props.fetchMenus();
}
rendeAppBar = () => (
<AppBar
title="CAIRS"
zDepth={2}
onLeftIconButtonClick={() => this.setState({ drawerOpen: true })}
/>
);
renderDrawer = () => (
<NavDrawer
open={this.state.drawerOpen}
menu={this.props.mainMenuChildren}
close={() => this.setState({ drawerOpen: false })}
/>
);
renderMenu = () => {
const { currentMenuChildren, menuHash, currentMenu, menuBreadCrumbs } = this.props;
const menu = currentMenuChildren.map((menu, index) =>
<MenuItem key={index} onClick={() => this.props.nextMenu(menu, menuHash, currentMenu, menuBreadCrumbs)}>
<h5>{`${index + 1}. ${menu.Caption}`}</h5>
<p>{menu.Description}</p>
</MenuItem>
);
return (
<div style={styles.menu}>
<div style={styles.justifyLeft}>
{menu}
</div>
</div>
);
}
renderBreadCrumbs = () => {
const { menuBreadCrumbs, menuHash, currentMenu } = this.props;
const breadCrumbs = menuBreadCrumbs.map((crumb, index) =>
<MenuItem
key={index}
primaryText={`${crumb.Caption} >`}
onClick={() => this.props.prevMenu(crumb, index, menuHash, menuBreadCrumbs)}
/>
);
return (
<div style={styles.breadCrumbContainer}>
{breadCrumbs}
<MenuItem
primaryText={`${currentMenu.Caption} >`}
/>
</div>
)
}
render = () => (
<div style={{ backgroundColor: grey800 }}>
{this.rendeAppBar()}
{this.renderDrawer()}
{this.renderBreadCrumbs()}
{this.renderMenu()}
</div>
);
}
const mapStateToProps = (state) => {
const {
currentMenuChildren,
currentMenu,
mainMenu,
mainMenuChildren,
menuBreadCrumbs,
menuHash,
} = state.menu;
return {
currentMenuChildren,
currentMenu,
mainMenu,
mainMenuChildren,
menuBreadCrumbs,
menuHash,
};
}
const styles = {
menu: {
display: 'flex',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'column'
},
justifyLeft: {
display: 'flex',
flex: 1,
justifyContent: 'center',
alignItems: 'flex-start',
flexDirection: 'column',
},
breadCrumbContainer: {
width: SCREEN_WIDTH,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row'
}
}
export default connect(mapStateToProps, { fetchMenus, nextMenu, prevMenu })(Menu);
|
import axios from 'axios';
import { USER_DETAILS_FAIL, USER_DETAILS_REQUEST, USER_DETAILS_SUCCESS, USER_REGISTER_FAIL, USER_REGISTER_REQUEST, USER_REGISTER_SUCCESS, USER_SIGNIN_FAIL, USER_SIGNIN_REQUEST, USER_SIGNIN_SUCCESS, USER_SIGNOUT, USER_UPDATE_PROFILE_FAIL, USER_UPDATE_PROFILE_REQUEST, USER_UPDATE_PROFILE_SUCCESS, RESET_USER, RESET_USER_ERROR } from '../constants/userConstants';
//register action
export const register = (name, email, password) => async (dispatch) => {
dispatch({ type: USER_REGISTER_REQUEST, payload: { name, email, password } });
try {
// use axios for http post request when user REGISTERg in
const { data } = await axios.post('http://localhost:8000/api/user/register', { name, email, password });
// if success, dispatch success and set payload to data
dispatch({ type: USER_REGISTER_SUCCESS, payload: data });
//also dispatch SignIn_Success because userSignin.userInfo is what we use to valid user
dispatch({ type: USER_SIGNIN_SUCCESS, payload: data });
// save data to localStorage
localStorage.setItem('userInfo', JSON.stringify(data));
} catch (error) {
// if error, dispatch FAIL, set payload to error message
dispatch({ type: USER_REGISTER_FAIL, payload: error.response && error.response.data.message ? error.response.data.message : error.message });
}
};
// signin action
export const signin = (email, password) => async (dispatch) => {
dispatch({ type: USER_SIGNIN_REQUEST, payload: { email, password } });
try {
// use axios for http post request when user signing in
const { data } = await axios.post('http://localhost:8000/api/user/login', { email, password });
// if success, dispatch success and set payload to data
dispatch({ type: USER_SIGNIN_SUCCESS, payload: data });
// save data to localStorage
localStorage.setItem('userInfo', JSON.stringify(data));
} catch (error) {
// if error, dispatch FAIL, set payload to error message
dispatch({ type: USER_SIGNIN_FAIL, payload: error.response && error.response.data.message ? error.response.data.message : error.message });
}
};
// signout action
export const signout = () => (dispatch) => {
//remove userInfo and cartItems from localStorage upon user signout
localStorage.removeItem('userInfo');
localStorage.removeItem('cartItems');
dispatch({ type: USER_SIGNOUT });
};
//user profile detail action
export const detailsUser = (userId) => async (dispatch, getState) => {
dispatch({ type: USER_DETAILS_REQUEST, payload: userId });
//get userInfo from store
const { userSignin: { userInfo } } = getState();
try {
//send ajax request
console.log(userId)
const { data } = await axios.get(`http://localhost:8000/api/user/${userId}`, {
headers: {
Authorization: `${userInfo?.token}`
}
});
dispatch({ type: USER_DETAILS_SUCCESS, payload: data });
} catch (error) {
// if error, dispatch FAIL, set payload to error message
dispatch({ type: USER_DETAILS_FAIL, payload: error.response && error.response.data.message ? error.response.data.message : error.message });
}
};
//user Profile update action
export const updateUserProfile = (user) => async (dispatch, getState) => {
dispatch({ type: USER_UPDATE_PROFILE_REQUEST, payload: user });
//get userInfo from store
const { userSignin: { userInfo } } = getState();
try {
const userInfo2 = localStorage.getItem('userInfo')
console.log(userInfo2)
//send ajax request
const { data } = await axios.put('http://localhost:8000/api/user/profile', user, {
headers: {
Authorization: `${userInfo?.token}`
}
});
dispatch({ type: USER_UPDATE_PROFILE_SUCCESS, payload: data });
//update userSignin as well to update the display
dispatch({ type: USER_SIGNIN_SUCCESS, payload: data });
//update localStorage after profile updated
localStorage.getItem('userInfo', JSON.stringify(data));
} catch (error) {
// if error, dispatch FAIL, set payload to error message
dispatch({ type: USER_UPDATE_PROFILE_FAIL, payload: error.response && error.response.data.message ? error.response.data.message : error.message });
}
};
export const attemptResetPassword = (password, id) => async (dispatch) => {
dispatch({ type: RESET_USER, payload: { password, id } });
try {
const resetPassword = await axios.post(`http://localhost:8000/api/user/resetPassword/password/${id}`,{password})
await resetPassword(password, id)
} catch (error) {
dispatch({ type: RESET_USER_ERROR })
}
};
export const attemptSendResetPasswordLink = (email) => async (dispatch) => {
dispatch({ type: RESET_USER, payload: email });
try {
const sendResetPasswordLink = await axios.post(`http://localhost:8000/api/user/forgetpassword`, { email })
await sendResetPasswordLink(email)
} catch (error) {
dispatch({ type: RESET_USER_ERROR })
}
};
|
import React from "react";
import PropTypes from "prop-types";
import {citiesTypes, cityTypes} from "../../mocks/cities.proptypes";
const LocationsList = (props) => {
const {cities, currentCity, clickHandler} = props;
return <ul className="locations__list tabs__list">
{cities.map((city) => (
<li key={city.cityId} className="locations__item" onClick={() => clickHandler(city)}>
<a className={
`locations__item-link tabs__item${city.cityId === currentCity.cityId ? ` tabs__item--active` : ``}`
} href="#">
<span>{city.cityName}</span>
</a>
</li>))}
</ul>;
};
LocationsList.propTypes = {
cities: citiesTypes,
currentCity: cityTypes,
clickHandler: PropTypes.func.isRequired
};
export default LocationsList;
|
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const Product = require('../models/product')
const Review = require('../models/review')
mongoose.connect('mongodb://127.0.0.1:27017/customer', { useNewUrlParser: true });
mongoose.set('useFindAndModify', false);
router.post('/addProducts', (req, res) => {
// console.log(req.body)
const {vendorEmail, status, price, total, available, readyToDispatch, dispatched, productName} = req.body
if(!vendorEmail) {
return res.send({
success: 'False',
message: 'Missing vendor email'
})
}
if(!status) {
return res.send({
success: 'False',
message: 'Missing product status'
})
}
if(!price) {
return res.send({
success: 'False',
message: 'Missing product price'
})
}
if(!total) {
return res.send({
success: 'False',
message: 'Missing total amount'
})
}
if(!available) {
return res.send({
success: 'False',
message: 'Missing availibility field'
})
}
if(!readyToDispatch) {
return res.send({
success: 'False',
message: 'Missing readyToDispatchstill'
})
}
if(!dispatched) {
return res.send({
success: 'False',
message: 'Missing dispatched status'
})
}
if(!productName) {
return res.send({
success: 'False',
message: 'Missing product name'
})
}
const product = new Product;
product.vendorEmail = vendorEmail;
product.status = status;
product.price = price;
product.total = total;
product.available = available;
product.readyToDispatch = readyToDispatch;
product.dispatched = dispatched
product.productName = productName
// console.log(product.vendorEmail, product.status, product.price, product.total, product.available, product.readyToDispatch)
// console.log('Reached heress')
product.save((err, product) => {
if(err) {
console.log(err)
return res.send({
success: 'False',
message: 'Server error'
})
}
console.log('New product added :)')
return res.send({
success: 'True',
message: 'Product Added'
})
})
})
router.post('/getCurrentProducts', (req, res) => {
const {vendorEmail} =req.body
Product.find({
vendorEmail: vendorEmail,
status: 'valid',
readyToDispatch: false,
dispatched: false
}, (err, products) => {
if(err) {
return res.send({
success: 'False',
message: 'server error'
})
}
return res.send({
success: 'True',
message: products
})
})
})
router.post('/removeCurrentProduct', (req, res) => {
const {id} = req.body
console.log(req.body)
Product.findByIdAndUpdate({_id: id}, {status: "Invalid"}, (err, docs) => {
if(err) {
return res.send({
succes: 'False',
message: 'server error'
})
}
return res.send({
success: 'True',
message: 'Updated'
})
})
})
router.post('/getReadyProducts', (req, res) => {
const {vendorEmail} =req.body
Product.find({
vendorEmail: vendorEmail,
status: 'valid',
readyToDispatch: true,
dispatched: false
}, (err, products) => {
if(err) {
return res.send({
success: 'False',
message: 'server error'
})
}
return res.send({
success: 'True',
message: products
})
})
})
router.post('/dispatchProduct', (req, res) => {
const {id} = req.body
console.log(req.body)
Product.findByIdAndUpdate({_id: id}, {dispatched: true}, (err, docs) => {
if(err) {
return res.send({
succes: 'False',
message: 'server error'
})
}
return res.send({
success: 'True',
message: 'Dispatching'
})
})
})
router.post('/getDispatchedProducts', (req, res) => {
const {vendorEmail} =req.body
Product.find({
vendorEmail: vendorEmail,
status: 'valid',
readyToDispatch: true,
dispatched: true
}, (err, products) => {
if(err) {
return res.send({
success: 'False',
message: 'server error'
})
}
return res.send({
success: 'True',
message: products
})
})
})
router.post('/getDispatchedProductsReview', (req, res) => {
const {vendorEmail, productId} = req.body
Review.find({
vendorEmail: vendorEmail,
productId: productId
}, (err, reviews) => {
if(err) {
return res.send({
success: 'False',
message: 'server error'
})
}
return res.send({
success: 'True',
message: reviews
})
})
})
module.exports = router;
|
/*
* description: 基于原生Javascript封装cookie操作
* 本类实现像localStorage和sessionStorage一样的存储API,
* 不同的是,这是基于HTTP cookie实现
* author: fanyong@gmail.com
*/
function cookieStorage(maxage, path) { // 两个参数分别代表存储有效期和作用域
// 获取一个存储全部cookie信息的对象
var cookie = (function() {
var cookie = {};
var all = document.cookie;
if (all === '')
return cookie;
var list = all.split('; '); // 以 '; ' 分理出名/值对
for (var i = 0; i < list.length; i++) {
var cookie = list[i];
var p = cookie.indexOf('=');
var name = cookie.substring(0, p);
var value = cookie.substring(p + 1);
value = decodeURIComponent(value); // 对其值进行编码
cookie[name] = value;
}
return cookie;
})();
// 将所有cookie的名字存储到一个数组中
var keys = [];
for (var key in cookie)
keys.push(key);
// 定义存储API公共的属性和方法
// 存储cookie的个数
this.length = keys.length;
// 返回第n个cookie的名字,如果越界则返回null
this.key = function(n) {
if (n < 0 || n >= keys.length)
return null;
return keys[n];
};
// 检查cookie功能是否开启
this.isCookieEnabled = function() {
if(!navigator.cookieEnabled) {
return false;
}
return true;
};
// 返回指定名字的cookie值,如果不存在则返回null
this.getItem = function(name) {
return cookie[name] || null;
};
// 存储cookie值
this.setItem = function (key, value) {
if (!(key in cookie)) { // 如果要存储的cookie不存在
keys.push(key); // 将指定的名字加入到存储所有cookie名的数组中
this.length++;
}
// 将该名/值对数据存储到cookie对象中
cookie[key] = value;
// 开始正式设置cookie
// 首先要将存储的cookie的值进行编码,同时创建一个"名=编码后的值"形式的字符串
var cookie = key + '=' + encodeURIComponent(value);
// 将cookie的属性也加入到该字符串中
if (maxage) cookie += '; max-age=' + maxage;
if (path) cookie += '; path=' + path;
// 通过document.cookie属性来设置cookie
document.cookie = cookie;
};
// 删除指定的cookie
this.removeItem = function (key) {
if (!(key in cookie)) return; // 如果cookie不存在,则什么也不做
// 从内部维护的cookie数组中删除指定的cookie
delete cookie[key];
// 同时将cookie中的名字也在内部数组中删除
// 如果使用ES5定义的数组indexOf()方法会更加简单
for (var i = 0; i < keys.length; i++) {
if (keys[i] === key) {
keys.splice(i, 1); // 将它从数组中删除
break;
}
}
this.length--; // cookie 的个数减1
// 最终通过将该cookie值设置为空字符串以及将有效期设置为0来删除指定的cookie
document.cookie = key + '=; max-age=0';
};
// 循环删除所有的cookie
this.clear = function() {
// 循环删除所有的cookie的名字,并将cookie删除
for (var i = 0; i < keys.length; i++) {
document.cookie = keys[i] + '=; max-age=0';
}
// 重置所有的内部状态
cookie = {};
keys = [];
this.length = 0;
};
}
|
import React from 'react'
import { action as MetaAction, AppLoader } from 'edf-meta-engine'
import config from './config'
import { Map, fromJS } from 'immutable'
import { TableOperate, Select, Button, Modal, Checkbox, ActiveLabelSelect, PrintOption } from 'edf-component'
import moment from 'moment'
import { FormDecorator } from 'edf-component'
const Option = Select.Option
import { consts } from 'edf-consts'
import renderColumns from './utils/renderColumns'
import { sortBaseArchives, sortSearchOption, changeToOption } from './utils/app-auxbalancesum-rpt-common'
import { LoadingMask } from 'edf-component'
class action {
constructor(option) {
this.metaAction = option.metaAction
this.config = config.current
this.webapi = this.config.webapi
this.voucherAction = option.voucherAction
this.selectedOption = []
}
onInit = ({ component, injections }) => {
this.component = component
this.injections = injections
injections.reduce('init')
let addEventListener = this.component.props.addEventListener
if (addEventListener) {
addEventListener('onTabFocus', :: this.onTabFocus)
}
this.load()
}
//页签切换
onTabFocus = () => {
this.load('tab')
}
// 初始化基础信息选项
getInitOption = async (type = 'load') => {
//科目
const accountList = await this.webapi.auxBalanceSumRpt.queryAccountList({ isCalc:true})
//级次
const accountDepthList = await this.webapi.auxBalanceSumRpt.queryAccountDepth()
//初始化查询界面辅助项
const auxBaseArchives = await this.webapi.auxBalanceSumRpt.queryBaseArchives({isContentEmpty:true})
const auxGroupList = sortBaseArchives(auxBaseArchives)
const maxDocPeriod = await this.getMaxDocPeriod()
//从上下文获取财务开账期间
const currentOrg = this.metaAction.context.get("currentOrg")
const enabledPeriod = currentOrg.enabledYear + '-' + `${currentOrg.enabledMonth}`.padStart(2, '0')
let res = { accountList, accountDepthList, enabledPeriod}
const isChangeSipmleDate = this.metaAction.gf('data.other.changeSipmleDate')
if (type == 'tab') {
//页签切换,判断简单日期是否修改过。
if (!isChangeSipmleDate) {
res[3] = { maxDocPeriod }
}
this.updateBaseArchives(auxGroupList)
} else {
res = { accountList, accountDepthList, enabledPeriod, maxDocPeriod, auxGroupList }
}
this.injections.reduce('initOption', { ...res })
}
load = (type = 'load') => {
this.getInitOption(type).then(() => {
const searchValue = this.metaAction.gf('data.searchValue').toJS()
const { assistFormOption, assistFormSelectValue } = this.metaAction.gf('data.assistForm').toJS()
const whereStr = searchValue.whereStr || assistFormSelectValue.join(',')
const groupStr = searchValue.groupStr || assistFormSelectValue.join(',')
let tmpstr=''
if(whereStr!=groupStr){
tmpstr = whereStr
}
this.searchValueChange({
...searchValue,
groupStr: groupStr,
whereStr: tmpstr
})
setTimeout(() => {
this.onResize()
}, 20)
})
}
updateBaseArchives = (data) => {
const { assistFormOption, initOption, assistFormSelectValue } = this.metaAction.gf('data.assistForm').toJS()
const arrAssitForm = []
data.forEach(item => {
const oldItem = assistFormOption.find(index => index.key == item.key)
if (oldItem) {
const oldValue = oldItem.value
if (oldValue) {
// 附上刚才选择的值
const newArr = oldValue.filter(x => {
const flag = item.children.find(y => y.value == x)
return flag ? true : false
})
item.value = newArr
}
}
arrAssitForm.push(item)
})
const arrAssitFormSelectValue = []
assistFormSelectValue.forEach(item => {
const flag = data.find(index => index.key == item)
if (flag) {
arrAssitFormSelectValue.push(item)
}
})
this.injections.reduce('updateBathState', [
{
path: 'data.assistForm.initOption',
value: data
}, {
path: 'data.assistForm.assistFormOption',
value: arrAssitForm
}, {
path: 'data.assistForm.assistFormSelectValue',
value: assistFormSelectValue
}
])
}
//1、渲染查询条件
renderCheckBox = () => {
return (
<Checkbox.Group className="app-proof-of-list-accountQuery-search-checkbox">
<Checkbox value="1">显示余额为0,发生额不为0的记录</Checkbox>
</Checkbox.Group>
)
}
//2、渲染查询条件
renderAuxSearchItem = () => {
const { assistFormOption, assistFormSelectValue } = this.metaAction.gf('data.assistForm').toJS()
const { accountList, startAccountDepthList, endAccountDepthList } = this.metaAction.gf('data.other').toJS()
const searchType = this.metaAction.gf('data.showOption.searchType')
let auxSearchItem;
switch (searchType) {
case 0:
auxSearchItem = [
{
name: 'date',
range: true,
label: '会计期间',
centerContent: '到',
isTime: true,
pre: {
type: 'DatePicker.MonthPicker',
mode: ['month', 'month'],
format: 'YYYY-MM',
allowClear: false,
decoratorDate: (value, value2)=> {return this.disabledDate(value, value2, "pre")}
},
next: {
type: 'DatePicker.MonthPicker',
mode: ['month', 'month'],
format: 'YYYY-MM',
allowClear: false,
decoratorDate: (value, value2) => {return this.disabledDate(value, value2, "next")}
}
}, {
name: 'assitform',
type: 'AssistForm',
assistFormOption: assistFormOption,
assistFormSelectValue: assistFormSelectValue
}, {
name: 'accountCodeList',
label: '会计科目',
type: 'Select',
mode: 'multiple',
allowClear: true,
childType: 'Option',
showSearch: '{{true}}',
optionFilterProp: "children",
filterOption: (inputValue, option) => { return this.filterAccountOption(inputValue, option)},
// title: '{{data.other.startAccountList}}',
option: accountList
}, {
name: 'accountDepth',
range: true,
label: '科目级次',
centerContent: '~',
pre: {
name: 'beginAccountGrade',
type: 'Select',
childType: 'Option',
option: startAccountDepthList,
allowClear: false
},
next: {
name: 'endAccountGrade',
type: 'Select',
childType: 'Option',
option: endAccountDepthList,
allowClear: false
}
},
{
name: 'showZero',
label: '',
type: 'Checkbox.Group',
render: this.renderCheckBox,
allowClear: false
}
]
break
case 1:
auxSearchItem = [
{
name: 'date',
range: true,
label: '会计期间',
centerContent: '到',
isTime: true,
pre: {
type: 'DatePicker.MonthPicker',
mode: ['month', 'month'],
format: 'YYYY-MM',
allowClear: false,
decoratorDate: (value, value2) => {return this.disabledDate(value, value2, "pre")}
},
next: {
type: 'DatePicker.MonthPicker',
mode: ['month', 'month'],
format: 'YYYY-MM',
allowClear: false,
decoratorDate: (value, value2) => {return this.disabledDate(value, value2, "next")}
}
}, {
name: 'accountCodeList',
label: '会计科目',
type: 'Select',
mode: 'multiple',
allowClear: true,
childType: 'Option',
filterOption: (inputValue, option) => { return this.filterAccountOption(inputValue, option) },
option: accountList
}, {
name: 'accountDepth',
range: true,
label: '科目级次',
centerContent: '~',
pre: {
name: 'beginAccountGrade',
type: 'Select',
childType: 'Option',
option: startAccountDepthList,
allowClear: false
},
next: {
name: 'endAccountGrade',
type: 'Select',
childType: 'Option',
option: endAccountDepthList,
allowClear: false
}
}, {
name: 'assitform',
type: 'AssistForm',
assistFormOption: assistFormOption,
assistFormSelectValue: assistFormSelectValue
},
{
name: 'showZero',
label: '',
type: 'Checkbox.Group',
render: this.renderCheckBox,
allowClear: false
}
]
break
default:
break
}
return [...auxSearchItem]
}
filterAccountOption = (inputValue, option, code = 'value', name = 'label', datalist = 'data.other.accountList') => {
if (option && option.props && option.props.value) {
let accountingSubjects = this.metaAction.gf(datalist)
let itemData = accountingSubjects.find(o => o.get(code) == option.props.value)
let accountName = ''
if (itemData.get(name) && itemData.get(code)) {
accountName = itemData.get(name).replace(itemData.get(code), '')
}
if ((itemData.get(code) && itemData.get(code).indexOf(inputValue) == 0)
|| (accountName.indexOf(inputValue) != -1)) {
//将滚动条置顶
let select = document.getElementsByClassName('ant-select-dropdown-menu')
if (select.length > 0 && select[0].scrollTop > 0) {
select[0].scrollTop = 0
}
return true
}
else {
return false
}
}
return true
}
filterSingleAccountOption = (inputValue, option)=>{
return this.filterAccountOption(inputValue, option, 'code', 'name', 'data.other.sigleAccountList')
}
sigleAccountIsShow = () => {
const accountSimpleStyle = this.metaAction.gf('data.other.accountSimpleStyle')
return { display: accountSimpleStyle ? 'inline-block' : 'none' }
}
//渲染简单查询条件
renderActiveSearch = () => {
const { assistFormSelectValue, assistFormOption } = this.metaAction.gf('data.assistForm').toJS()
// 找到排名靠前的并且选中的辅助项
const one = assistFormOption.find(item => {
return assistFormSelectValue.includes(item.key)
})
return <ActiveLabelSelect
option={assistFormOption}
selectLabel={one && one.key ? one.key : ''}
value={''}
onChange={this.activeLabelSelectChange}
/>
}
//获取凭证所在的最大期间座位默认日期
getMaxDocPeriod = async () => {
const docVoucherDate = await this.webapi.auxBalanceSumRpt.getDocVoucherDate()
const maxDocPeriod = docVoucherDate.year + '-' + `${docVoucherDate.period}`.padStart(2, '0')
return maxDocPeriod
}
disabledDate = (current, pointTime, type) => {
const enableddate = this.metaAction.gf('data.other.enabledDate')
if (type == 'pre') {
let currentMonth = this.transformDateToNum(current)
let pointTimeMonth = this.transformDateToNum(pointTime)
let enableddateMonth = this.transformDateToNum(enableddate)
return currentMonth > pointTimeMonth || currentMonth < enableddateMonth
} else {
let currentMonth = this.transformDateToNum(current)
let pointTimeMonth = this.transformDateToNum(pointTime)
let enableddateMonth = this.transformDateToNum(enableddate)
return currentMonth < pointTimeMonth || currentMonth < enableddateMonth
}
}
transformDateToNum = (date) => {
let time = date
if (typeof date == 'string') {
time = moment(new Date(date))
}
return parseInt(`${time.year()}${time.month() < 10 ? `0${time.month()}` : `${time.month()}`}`)
}
// 简单搜索辅助项选择发生改变
activeLabelSelectChange = (label, value) => {
let { initOption } = this.metaAction.gf('data.assistForm').toJS()
const init = JSON.parse(JSON.stringify(initOption))
let assistFormSelectValue = []
assistFormSelectValue.push(label)
const index = initOption.findIndex(item => item.key == label)
if (index != -1) {
if (value) {
initOption[index].value = [value]
} else {
initOption[index].value = []
}
}
this.injections.reduce('update', {
path: 'data.assistForm',
value: {
initOption: init,
assistFormOption: initOption,
assistFormSelectValue: assistFormSelectValue
}
})
const searchValue = this.metaAction.gf('data.searchValue').toJS()
const showOption = this.metaAction.gf('data.showOption').toJS()
searchValue.groupStr = label
if (value) {
searchValue.whereStr = `${label}:${value}`
} else {
searchValue.whereStr = ``
}
//更新查询条件辅助项是否显示
this.injections.reduce('updateBathState', [
{
path: 'data.other.accountSimpleStyle',
value: showOption.searchType == 0 ? false : true
}
])
this.searchValueChange(searchValue)
}
componentWillUnmount = () => {
let removeEventListener = this.component.props.removeEventListener
if (window.removeEventListener) {
window.removeEventListener('resize', this.onResize, false)
} else if (window.detachEvent) {
window.detachEvent('onresize', this.onResize)
} else {
window.onresize = undefined
}
}
componentDidMount = () => {
if (window.addEventListener) {
window.addEventListener('resize', this.onResize, false)
} else if (window.attachEvent) {
window.attachEvent('onresize', this.onResize)
} else {
window.onresize = this.onResize
}
}
componentWillReceiveProps = ({ keydown }) => {
if (keydown && keydown.event) {
let e = keydown.event
if (e.keyCode == 39 || e.keyCode == 40) {
this.accountlistBtn('right')
} else if (e.keyCode == 37 || e.keyCode == 38) {
this.accountlistBtn('left')
}
}
}
// 高级搜索组件搜索条件发生变化
searchValueChange = async (value, assitForm) => {
const { accountList, startAccountDepthList, endAccountDepthList, sigleAccountList } = this.metaAction.gf('data.other').toJS()
const arr = []
arr.push(
{
path: 'data.searchValue',
value: {
...value
}
}
)
if (assitForm && assitForm.selectValue) {
arr.push({
path: 'data.assistForm.assistFormSelectValue',
value: assitForm.selectValue
}, {
path: 'data.assistForm.assistFormOption',
value: assitForm.option
})
}
arr.push({
path: 'data.other.accountList',
value: accountList
}, {
path: 'data.other.startAccountDepthList',
value: startAccountDepthList
}, {
path: 'data.other.endAccountDepthList',
value: endAccountDepthList
})
if (value.accountCodeList && value.accountCodeList.length==1){
this.injections.reduce('update', { path: 'data.other.sigleAccountCode', value: value.accountCodeList[0] })
}else{
this.injections.reduce('update', { path: 'data.other.sigleAccountCode', value:'0000' })
}
this.injections.reduce('updateBathState', arr)
this.sortParmas({...value})
this.getAuxAccountList(value)
}
// 科目简单搜索条件发生变化 点击左右按钮进行改变
accountlistBtn = (type) => {
//简单查询科目集合
const accountlist = this.metaAction.gf('data.other.sigleAccountList').toJS()
//当前选择科目对于的code
const accountCode = this.metaAction.gf('data.other.sigleAccountCode')
//查找在accountlist中存在并且选择了的对于科目
let index = accountlist.findIndex(item => item.code == accountCode)
let code
switch (type) {
case 'right':
code = accountlist[index + 1] && accountlist[index + 1].code ? accountlist[index + 1].code : accountCode
break
case 'left':
code = accountlist[index - 1] && accountlist[index - 1].code ? accountlist[index - 1].code : accountCode
break
default:
code = accountCode
break
}
this.accountlistChange(code)
}
//日期切换
onPanelChange = (value) => {
let date = {
date_end: value[1],
date_start: value[0]
}
//记录是否变更过日期
this.metaAction.sf('data.other.changeSipmleDate', true)
const searchValue = this.metaAction.gf('data.searchValue').toJS()
this.injections.reduce('searchUpdate', { ...searchValue, ...date })
this.sortParmas({ ...searchValue, ...date })
}
//科目发生改变直接点击搜索项
accountlistChange = (value) => {
const accountlist = this.metaAction.gf('data.other.sigleAccountList').toJS()
const item = accountlist.find(index => {
return index.code == value
})
this.injections.reduce('update', { path: 'data.other.sigleAccountCode', value:value })
this.injections.reduce('update', { path: 'data.searchValue.accountCodeList', value:value == '0000' ? [] : [value]})
this.sortParmas()
}
//查询类型按钮切换-科目辅助余额表
searchTypeRptChange = (key, value) => {
//searchType=0 查询类型,0 为辅助科目余额表, 1 为科目辅助余额表
const searchType = [
{ lable: "辅助科目余额表", value: 0 },
{ lable: "科目辅助余额表", value: 1 }
]
let tmpRpt, currentValue
for (let item of searchType) {
if (item.lable != value) {
tmpRpt = item
}
else {
currentValue = item.value
}
}
//当前页面证实得查询类型
this.injections.reduce('showOptionsChange', {
path: 'data.showOption.searchType',
value: currentValue
})
//下个页面得标题
this.injections.reduce('showOptionsChange', {
path: `data.showOption.${key}`,
value: tmpRpt.lable
})
//更新查询条件辅助项是否显示
this.injections.reduce('updateBathState', [
{
path: 'data.other.accountSimpleStyle',
value: currentValue == "0" ? false : true
}
])
const searchValue = this.metaAction.gf('data.searchValue').toJS()
this.getAuxAccountList(searchValue)
this.sortParmas()
}
//组装搜索条件
sortParmas = async (search,type) => {
//辅助余额表查询,
//具体参数:* @apiParam {Number} beginYear 起始年份
// * @apiParam {Number} beginPeriod 起始期间
// * @apiParam {Number} endYear 结束年份
// * @apiParam {Number} endPeriod 结束期间
// * @apiParam {Array} accountCodeList 科目编码列表
// * @apiParam {Number} beginAccountGrade 起始科目级次
// * @apiParam {Number} endAccountGrade 结束科目级次
// * @apiParam {Array} auxInfo 辅助核算信息
// * 示例 ["departmentId:1,2", "personId:1,2", "customerId:1,2", "supplierId:1,2", "inventoryId:1,2", "projectId:1,2", "bankAccountId:1,2"]
// * 分别对应部门、人员、客户、供应商、存货、项目、银行账号
// * 如果勾选对应辅助核算,则数组中传入对应字符串"xxId:",如果选择了辅助核算进行过滤,同时把 id (以,分隔)传入
// * @apiParam {Boolean} showZero=true 余额为 0 是否显示
// * @apiParam {Number} searchType=0 查询类型,0 为辅助科目余额表, 1 为科目辅助余额表
// * @apiParam {Boolean} includeSum=true 查询结果是否包含小计
// 处理搜索参数
if (!search) {
search = this.metaAction.gf('data.searchValue').toJS()
}
const changeData = {
'date_start': {
'beginYear': (data) => data ? data.format('YYYY') : null,
'beginPeriod': (data) => data ? data.format('MM') : null,
},
'date_end': {
'endYear': (data) => data ? data.format('YYYY') : null,
'endPeriod': (data) => data ? data.format('MM') : null,
}
}
const searchValue = sortSearchOption(search, changeData)
//获取辅助项
searchValue.auxInfo = this.getAux(search)
searchValue.showZero = searchValue.showZero && searchValue.showZero.length > 0 ? 'true' : 'false'
const searchType = this.metaAction.gf('data.showOption.searchType')
searchValue.printType = searchType == '0' ? 4 : searchType
const sigleAccountCode = this.metaAction.gf('data.other.sigleAccountCode')
if (searchType == '1' && sigleAccountCode != '0000') {
searchValue.sigleAccountCode = sigleAccountCode
searchValue.accountCodeList=[]
}
searchValue.searchType = searchType
searchValue.isIncludeAllTotal = this.metaAction.gf('data.showOption.isIncludeAllTotal')
searchValue.includeSum = this.metaAction.gf('data.showOption.includeSum')
if (type == 'get') {
return { ...searchValue }
}
this.requestData({ ...searchValue }).then((res) => {
const searchType = this.metaAction.gf('data.showOption.searchType')
const sigleAccountCode = this.metaAction.gf('data.other.sigleAccountCode')
let details=null
if (searchType == 1 && sigleAccountCode != '0000' && res && res.details){
//todo 此处代码特殊处理,科目辅助余额表选择对应科目后,返回的小计多一行数据,前台特殊处理
if (res.auxType && res.auxType.length>2){
const startIndex = res.details.findIndex(item => item.accountName == '小计')
if (startIndex != -1) {
res.details.splice(startIndex, 1)
}
}
this.injections.reduce('load', res.details)
}else{
this.injections.reduce('load', res && res.details ? res.details : [])
}
this.injections.reduce('update', {
path: 'data.style',
value: this.getRowStyle(res && res.style ? res.style : ''),
})
setTimeout(() => {
this.onResize()
}, 20)
})
}
//获取辅助项
getAux = (searchValue) => {
let aux = []
const groupStr = searchValue.groupStr && searchValue.groupStr.split(',')
const whereStr = searchValue.whereStr && searchValue.whereStr.split(';')
if (groupStr) {
groupStr.forEach(item=>{
if (!whereStr){
aux.push(`${item}:`)
}else{
const tmpStr = whereStr.find(x => x.indexOf(item) > -1)
if (tmpStr) {
aux.push(`${tmpStr}`)
}else{
aux.push(`${item}:`)
}
}
})
}
return aux
}
// 发送请求
requestData = async (params) => {
let loading = this.metaAction.gf('data.loading')
if(!loading){
this.injections.reduce('tableLoading', true)
}
//清理无用属性
delete params.groupStr
delete params.whereStr
const response = await this.webapi.auxBalanceSumRpt.queryRptList(params)
this.injections.reduce('tableLoading', false)
return response
}
getAuxAccountList = async(params) => {
const searchType=this.metaAction.gf('data.showOption.searchType')
if (searchType==1){
let result = []
const res = await this.webapi.auxBalanceSumRpt.queryAccountList({
isCalc: true
})
let initAccountArray = [{ code: '0000', codeAndName: '所有科目' }]
if (!res || !res.glAccounts) {
this.injections.reduce('updateBathState', [
{
path: 'data.other.sigleAccountList',
value: initAccountArray
}])
this.injections.reduce('update', [
{
path: 'data.searchValue.accountCodeList',
value: []
}])
} else {
result = [...initAccountArray, ...res.glAccounts]
this.injections.reduce('updateBathState', [
{
path: 'data.other.sigleAccountList',
value: result
}])
this.injections.reduce('update', { path: 'data.other.accountList', value: fromJS(changeToOption(res.glAccounts, 'codeAndName', 'code')) })
}
}
}
// 点击刷新按钮
refreshBtnClick = () => {
const searchValue = this.metaAction.gf('data.searchValue').toJS()
this.getAuxAccountList(searchValue)
this.sortParmas()
}
//获取时间选项
getNormalDateValue = () => {
const data = this.metaAction.gf('data.searchValue').toJS()
const arr = []
arr.push(data.date_start)
arr.push(data.date_end)
return arr
}
//简单查询日期改变搜索
normalSearchChange = (path, value) => {
if (path == 'date') {
let date = {
date_end: value[1],
date_start: value[0]
}
//记录是否变更过日期
this.metaAction.sf('data.other.changeSipmleDate', true)
const searchValue = this.metaAction.gf('data.searchValue').toJS()
this.injections.reduce('searchUpdate', { ...searchValue, ...date })
this.getAuxAccountList(searchValue)
}
}
getNormalSearchValue = () => {
const data = this.metaAction.gf('data.searchValue').toJS()
let date = [data.date_start, data.date_end]
return { date, query: data.query }
}
shareClick = (e) => {
switch (e.key) {
case 'weixinShare':
this.weixinShare()
break;
case 'mailShare':
this.mailShare()
break;
}
}
weixinShare = async () => {
if (this.metaAction.gf('data.list').toJS().length == 0) {
this.metaAction.toast('warning', '当前暂无数据可分享!')
return
}
// let data = await this.sortParmas(null, 'get')
let data = 'https://thethreekingdoms.github.io/'
const ret = this.metaAction.modal('show', {
title: '微信/QQ分享',
width: 300,
footer: null,
// closable: false,
children: this.metaAction.loadApp('ttk-edf-app-weixinshare', {
store: this.component.props.store,
initData: '/v1/gl/report/balanceauxrpt/share',
params: data
})
})
}
mailShare = async () => {
if (this.metaAction.gf('data.list').toJS().length == 0) {
this.metaAction.toast('warning', '当前暂无数据可分享!')
return
}
// let data = await this.sortParmas(null, 'get')
let data = {beginYear:2018,beginPeriod:3,endYear:2018,endPeriod:3}
const ret = await this.metaAction.modal('show', {
title: '邮件分享',
width: 400,
children: this.metaAction.loadApp('ttk-edf-app-mailshare', {
store: this.component.props.store,
params: data,
shareUrl: '/v1/gl/report/balanceauxrpt/share',
mailShareUrl: '/v1/gl/report/balanceauxrpt/sendShareMail',
printShareUrl: '/v1/gl/report/balanceauxrpt/print',
period: `${data.beginYear}.${data.beginPeriod}-${data.endYear}.${data.endPeriod}`
})
})
if (ret) {
this.metaAction.toast('warning', '功能暂未实现!')
}
}
//导出
export = async () => {
if (this.metaAction.gf('data.list').toJS().length == 0) {
this.metaAction.toast('warning', '当前暂无数据可导出!')
return
}
// const parmas =await this.sortParmas(null, 'get')
// await this.webapi.auxBalanceSumRpt.export(parmas)
this.metaAction.toast('warning', '功能暂未实现!')
}
//打印
print = async () => {
if (this.metaAction.gf('data.list').toJS().length == 0) {
this.metaAction.toast('warning', '当前暂无数据可打印!')
return
}
// const parmas =await this.sortParmas(null, 'get')
// await this.webapi.auxBalanceSumRpt.print(parmas)
const _this = this
this.metaAction.modal('show', {
title: '打印',
width: 400,
footer: null,
iconType: null,
okText: '打印',
className: 'mk-app-proof-of-list-modal-container',
children: <PrintOption
callBack={ _this.submitPrintOption }
/>
})
}
submitPrintOption = async (form, target) => {
this.metaAction.toast('warning', '功能暂未实现!')
}
//小计
showOptionsChange = (key, value) => {
this.injections.reduce('showOptionsChange', {
path: `data.showOption.${key}`,
value: value
})
this.sortParmas()
}
getRowStyle = (data) => {
let result = {}
const arr = data.split(';')
arr.forEach(item => {
if (!item) {
return
}
const str = item.replace(/\]\[/g, '\];\[')
let [key, valueArr] = str.split(':')
if (!result[key]) {
result[key] = {}
}
const arr2 = valueArr.split(';')
arr2.forEach(x => {
const y = JSON.parse(x)
result[key][y[0]] = y[1] - y[0] + 1
})
})
return result
}
checkRowSpan = (index, data) => {
let num = 1
if (!data) {
return num
}
for (const [key, value] of Object.entries(data)) {
if (index > parseInt(key) && index <= key + value) {
num = 0
}
}
return num
}
renderRowSpan = (text, row, index, key, colNum = 1, isdisplay=false) => {
let rowNum = 1
if (this.metaAction.gf('data.style')){
const style = this.metaAction.gf('data.style').toJS()
if (style[key] && style[key][index]) {
rowNum = style[key][index]
} else if (style[key]) {
rowNum = this.checkRowSpan(index, style[key])
}
}
let obj = {
children: <span title={text}>{text}</span>,
props: {
rowSpan: rowNum,
colSpan: 1
}
}
if (row && row.accountName == '合计') {
obj.children = <span title={row.accountName}>{row.accountName}</span>
obj.props.colSpan = colNum
}
if (row && row.accountName == '小计') {
obj.children = <span title={row.accountName}>{row.accountName}</span>
obj.props.colSpan = colNum
}
if (isdisplay && row && row.accountName == '小计') {
obj.children = <span title={row.accountName}>{row.accountName}</span>
}
return obj
}
renderColSpan = (text, row, index, num,isdisplay) => {
const obj = {
children: <span title={text}>{text}</span>,
props: { colSpan: 1 },
}
if (row && row.accountName == '合计') {
obj.children = <span title={row.accountName}>{row.accountName}</span>
obj.props.colSpan = num
}
if (row && row.accountName == '小计') {
obj.children = <span title={row.accountName}>{row.accountName}</span>
obj.props.colSpan = num
}
if (isdisplay && row && row.accountName == '小计') {
obj.children = <span title={row.accountName}>{row.accountName}</span>
}
return obj
}
rowShowTitle = (text, row, index) => {
let obj = {
children: <span title={text}>{text}</span>
}
return obj
}
//表格列处理
tableColumns = () => {
const [accountColumns,baseColumns] = renderColumns(this.rowShowTitle)
let auxColumns = []
const searchType = this.metaAction.gf('data.showOption.searchType')
const includeSum = this.metaAction.gf('data.showOption.includeSum')
const sigleAccountCode = this.metaAction.gf('data.other.sigleAccountCode')
const { assistFormOption, assistFormSelectValue } = this.metaAction.gf('data.assistForm').toJS()
assistFormOption.forEach(item => {
if (assistFormSelectValue.includes(item.key)) {
if (item.key.includes('isExCalc')) {
let keyStr = item.key ? `e${item.key.slice(3)}Name` : item.key
auxColumns.push({
title: <span title={item.name}>{item.name}</span>,
name: keyStr,
dataIndex: keyStr,
key: keyStr
// render: (text, record, index) => this.renderRowSpan(text, record, index, item.key,0)
})
} else {
auxColumns.push({
title: <span title={item.name}>{item.name}</span>,
name: item.key ? item.key.replace(/Id/, 'Name') : item.key,
dataIndex: item.key ? item.key.replace(/Id/, 'Name') : item.key,
key: item.key ? item.key.replace(/Id/, 'Name') : item.key
// render: (text, record, index) => this.renderRowSpan(text, record, index, item.key,0)
})
}
}
})
// searchType = 0 查询类型,0 为辅助科目余额表, 1 为科目辅助余额表
if (searchType == 0) {
if (accountColumns && auxColumns && auxColumns.length > 0){
accountColumns.forEach(element => {
element.render = (text, record, index) => this.renderColSpan(text, record, index, 0)
})
auxColumns.forEach(item => {
let auxId
if (item.key.includes('exCalc')){
auxId =`isE${item.key.replace(/Name/,'').slice(1)}`
}else{
auxId = item.key.replace(/Name/, 'Id')
}
item.render = (text, record, index) => this.renderRowSpan(text, record, index, auxId, 0)
})
const num = auxColumns.length + 2
let fisrtAuxId
if (auxColumns[0].key.includes('exCalc')) {
fisrtAuxId = `isE${auxColumns[0].key.replace(/Name/, '').slice(1)}`
} else {
fisrtAuxId = auxColumns[0].key.replace(/Name/, 'Id')
}
auxColumns[0].render = (text, record, index) => this.renderRowSpan(text, record, index, fisrtAuxId,num)
}
return [...auxColumns, ...accountColumns, ...baseColumns]
}
//科目辅助余额表
if (searchType == 1 && sigleAccountCode == '0000') {
if (accountColumns && auxColumns && auxColumns.length > 0) {
if (includeSum){
accountColumns.forEach(item => {
item.render = (text, record, index) => this.renderRowSpan(text, record, index, 'accountId',0)
})
auxColumns.forEach(item => {
let auxId
if (item.key.includes('exCalc')) {
auxId = `isE${item.key.replace(/Name/, '').slice(1)}`
} else {
auxId = item.key.replace(/Name/, 'Id')
}
item.render = (text, record, index) => this.renderRowSpan(text, record, index, auxId, 0)
})
const num = auxColumns.length + 2
accountColumns[0].render = (text, record, index) => this.renderRowSpan(text, record, index, 'accountId', num)
}else{
accountColumns.forEach(item => {
item.render = (text, record, index) => this.renderColSpan(text, record, index, 0)
})
auxColumns.forEach(item => {
item.render = (text, record, index) => this.renderColSpan(text, record, index, 0)
})
const num = auxColumns.length + 2
accountColumns[0].render = (text, record, index) => this.renderColSpan(text, record, index, num)
}
}
return [...accountColumns, ...auxColumns, ...baseColumns]
} else {
if (auxColumns && auxColumns.length > 1) {
auxColumns.forEach(item => {
item.render = (text, record, index) => this.renderColSpan(text, record, index, 0)
})
let fisrtAuxId
if (auxColumns[0].key.includes('exCalc')) {
fisrtAuxId = `isE${auxColumns[0].key.replace(/Name/, '').slice(1)}`
} else {
fisrtAuxId = auxColumns[0].key.replace(/Name/, 'Id')
}
const num = auxColumns.length
auxColumns[0].render = (text, record, index) => this.renderRowSpan(text, record, index, fisrtAuxId,num, true)
} else{
auxColumns.forEach(item => {
item.render = (text, record, index) => this.renderColSpan(text, record, index, 1, true)
})
}
return [...auxColumns, ...baseColumns]
}
}
onResize = (e) => {
let keyRandomTab = Math.floor(Math.random() * 10000)
this.keyRandomTab = keyRandomTab
setTimeout(() => {
if (keyRandomTab == this.keyRandomTab) {
this.getTableScroll('app-auxbalancesum-rpt-table-tbody', 'ant-table-thead', 0, 'ant-table-body', 'data.tableOption', e)
}
}, 20)
}
getTableScroll = (contaienr, head, num, target, path, e) => {
try {
const tableCon = document.getElementsByClassName(contaienr)[0]
if (!tableCon) {
if (e) {
return
}
setTimeout(() => {
this.getTableScroll(contaienr, head, num, target, path)
}, 200)
return
}
const header = tableCon.getElementsByClassName(head)[0]
const body = tableCon.getElementsByClassName(target)[0].getElementsByTagName('table')[0]
const pre = this.metaAction.gf(path).toJS()
const y = tableCon.offsetHeight - header.offsetHeight - num
const bodyHeight = body.offsetHeight
if (bodyHeight > y && y != pre.y) {
this.metaAction.sf(path, fromJS({ ...pre, y }))
} else if (bodyHeight < y && pre.y != null) {
this.metaAction.sf(path, fromJS({ ...pre, y: null }))
} else {
return false
}
} catch (err) {
}
}
}
export default function creator(option) {
const metaAction = new MetaAction(option),
voucherAction = FormDecorator.actionCreator({ ...option, metaAction }),
o = new action({ ...option, metaAction, voucherAction }),
ret = { ...metaAction, ...voucherAction, ...o }
metaAction.config({ metaHandlers: ret })
return ret
}
|
class ItemsSearchResponse {
constructor(items, categories, author) {
this.items = items
this.author = author
this.categories = categories
}
}
class ItemResponse {
constructor(author, item) {
this.author = author
this.item = item
}
}
class Price {
constructor(currency, amount) {
this.currency = currency
this.amount = amount
this.decimals = "00"
}
}
class Item {
constructor(id, title, price, picture, condition, freeShiping, city, soldQuantity = null, description = null) {
this.id = id
this.title = title
this.price = price
this.picture = picture
this.condition = condition
this.free_shipping = freeShiping
this.city = city
this.sold_quantity = soldQuantity
this.description = description
}
}
class Author {
constructor(name, lastname) {
this.name = name
this.lastname = lastname
}
}
module.exports = {
Price,
Author,
ItemResponse,
ItemsSearchResponse,
Item
};
|
// JavaScript Document
$(function (){
//官网4
(function (){
var oBtnPrev = document.getElementById("btn_prev");
var oBtnNext = document.getElementById("btn_next");
var oUl = document.getElementById("ul1");
var aLi = oUl.children;
var len = aLi.length;
function rnd(n, m) {
return parseInt(n + Math.random() * (m - n));
}
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, false)[attr];
}
}
//存class
var aClass = [];
for(var i = 0; i < len; i++){
aClass.push(aLi[i].className);
}
var bReady = true;//准备好了
oBtnNext.onclick = function(){
if(!bReady) return ;
bReady = false;
aClass.unshift(aClass.pop());
aClass.unshift(aClass.pop());
tab();
};
oBtnPrev.onclick = function(){
if(!bReady) return ;
bReady = false;
aClass.push(aClass.shift());
aClass.push(aClass.shift());
tab();
};
function tab(){
for(var i = 0; i < len; i++){
aLi[i].className = aClass[i];
}
var oCur = oUl.querySelector(".cur");
oCur.addEventListener("transitionend",function(){
bReady = true;
},false);
}
})();
////
$(function (){
$("#close").click(function (){
$("#dialog").hide(100);
});
$("#ul1 li div").click(function (){
$("#dialog").show(100);
switch (this.className){
case 'zp1':
$("#iframeResult").attr({
src:"demo/demo1.html"
});
show1();
break;
case 'zp2':
$("#iframeResult").attr({
src:"demo/demo2.html"
});
break;
case 'zp3':
$("#iframeResult").attr({
src:"demo/demo3.html"
});
break;
case 'zp4':
$("#iframeResult").attr({
src:"demo/demo4.html"
});
break;
case 'zp5':
$("#iframeResult").attr({
src:"demo/demo5.html"
});
break;
case 'zp6':
$("#iframeResult").attr({
src:"demo/demo6.html"
});
break;
case 'zp7':
$("#iframeResult").attr({
src:"demo/demo7.html"
});
break;
case 'zp8':
$("#iframeResult").attr({
src:"demo/drag/index.html"
});
break;
case 'zp9':
$("#iframeResult").attr({
src:"demo/demo10.html"
});
break;
case 'zp10':
$("#iframeResult").attr({
src:"demo/demo9.html"
});
break;
case 'zp11':
$("#iframeResult").attr({
src:"demo/demo8.html"
});
break;
}
})
////
});
//////////////////
});
|
class ShopItem {
constructor(id, price) {
this.id = id;
this.price = price;
}
}
var shopItems = {
bummleHat: new ShopItem(8, 100),
strawHat: new ShopItem(2, 500),
winterCap: new ShopItem(15, 1000),
cowboyHat: new ShopItem(5, 1000),
rangerHat: new ShopItem(4, 2000),
explorerHat: new ShopItem(18, 2000),
marksmanCap: new ShopItem(1, 3000),
soldierHelm: new ShopItem(6, 5000),
honeycrisp: new ShopItem(13, 5000),
minerHelm: new ShopItem(9, 5000),
boostHat: new ShopItem(12, 6000),
bushGear: new ShopItem(10, 10000),
spikeGear: new ShopItem(11, 10000),
bushido: new ShopItem(16, 15000),
samurai: new ShopItem(20, 15000)
}
module.exports = {
ShopItem: ShopItem,
items: shopItems
}
|
import React from 'react';
import MainPage from './MainPage';
import { connect } from 'react-redux';
import { setUsers, setSearchKey } from '../../Redux/MainGridReducer';
import Axios from 'axios';
class MainPageAPI extends React.Component {
searchUsers = (searchKey) => {
debugger;
let actionType = 'SEARCH';
let object = { actionType, searchKey };
Axios.post( 'http://testcrm/actions/index.php',object
)
.then(res => {
debugger;
let users = res.data;
let usersCopy = [];
users.map(u => {
u.id = parseInt(u.id);
u.showUser = parseInt(u.showUser);
u.remoteWorking = parseInt(u.remoteWorking);
usersCopy.push(u);
})
this.props.setUsers(usersCopy);
}
);
}
setSearchKey = (searchKey) => {
this.props.setSearchKey(searchKey);
}
render () {
return (
<MainPage choosenUser={this.props.choosenUser}
searchUsers={this.searchUsers}
setSearchKey={this.setSearchKey} />
)
}
}
let mapStateToProps = (state) => {
return {
users: state.MainGrid.users,
choosenUser: state.MainGrid.choosenUser,
searchKey: state.MainGrid.searchKey,
}
}
export default connect(mapStateToProps, { setUsers, setSearchKey })(MainPageAPI);
|
$(document).ready(function () {
$("#saveControl").click(function () {
var sensor = $('#inputjson').val();
$.ajax({
async: true,
crossDomain: true,
url: 'http://{{HOST}}:8080/setup/control',
type: 'POST',
dataType: 'json',
data: sensor,
success: function (data, textStatus, xhr) {
window.alert("Control loaded successfully");
location.reload();
},
error: function (data){
window.alert("Remember to stop the alarm before...");
}
});
});
$("#scanControl").click(function () {
$('#inputjson').val("Scanning...Press any Control button!");
$.ajax({
async: true,
crossDomain: true,
url: 'http://{{HOST}}:8080/scan/control',
type: "get",
dataType: "json",
data: '',
success: function (data) {
$('#inputjson').val('[{"Code":"'+data.Code+'","Description":"mando1","TypeOf":"inactive"}]');
},
error: function (data){
window.alert("Control key not pressed");
},
});
});
$("#deleteControl").click(function () {
var code = $('#code').val();
var urldelete = 'http://{{HOST}}:8080/setup/control/'+code;
$.ajax({
async: true,
url: urldelete,
type: 'delete',
success: function () {
window.alert("Control delete successfully");
location.reload();
},
error: function (data){
window.alert("Remember to stop the alarm before...");
}
});
});
$("#example").click(function () {
document.getElementById("inputjson").value = "[{\"Code\":\"3462412\",\"Description\":\"mando1\",\"TypeOf\":\"inactive\"},{\"Code\":\"3462448\",\"Description\":\"mando1\",\"TypeOf\":\"full\"},{\"Code\":\"3462592\",\"Description\":\"mando1\",\"TypeOf\":\"partial\"}]";
});
$("#controltable").show(function (){
$.ajax({
url: 'http://{{HOST}}:8080/controls',
type: "get",
dataType: "json",
data: '',
success: function(data, textStatus, jqXHR) {
// since we are using jQuery, you don't need to parse response
for (var i = 0; i < data.length; i++) {
var row = $("<tr />");
$("#controltable").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
row.append($("<td>" + data[i].Code + "</td>"));
row.append($("<td>" + data[i].Description + "</td>"));
row.append($("<td>" + data[i].TypeOf + "</td>"));
}
}
});
});
});
|
import { withPluginApi } from 'discourse/lib/plugin-api';
export default {
name: 'bbf',
initialize() {
let timer = 0;
let apiUser;
let warningID = 0;
let requestOut = false;
let requestValid = false;
function setLogoutTimer(eventType) {
if(requestOut) { return; }
if(requestValid) { return; }
if(apiUser === null) { return; }
requestOut = true;
clearTimeout(warningID);
const loc = window.location;
const url = loc.protocol + '//api.' + loc.hostname + '/out/' + apiUser.id
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4) {
requestOut = false;
requestValid = true;
var obj = JSON.parse(this.responseText);
var warnSeconds = (obj.timeoutMinutes - 5) * 60;
if(warnSeconds > 0) {
warningID = setTimeout( function() {
bootbox.alert('Er is al enige tijd geen activiteit. Wanneer je nog 5 minuten inactief blijft, word je automatisch uitgelogd.', function() {
});
},warnSeconds*1000);
}
clearTimeout( timer );
timer = setTimeout( ()=> {
requestValid = false;
}, 5 * 1000);
}
}
xhttp.open('GET', url, true);
xhttp.send();
}
withPluginApi('0.3', api => {
apiUser = api.getCurrentUser();
api.onPageChange( ()=> {
setLogoutTimer('navigation');
});
[ 'mousemove', 'scroll' ].forEach( (eventType) => {
window.addEventListener(eventType, ()=> {
setLogoutTimer(eventType);
},true);
});
setLogoutTimer('init');
});
}
}
|
var ColorShader,
__hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; };
ColorShader = (function(_super) {
__extends(ColorShader, _super);
function ColorShader() {
this.drawSolid = false;
this.color = 0;
}
ColorShader.prototype.apply = function(p, dt, index) {
p.graphics.clear();
if (this.drawSolid) {
p.graphics.beginFill(this.getColor(p.t));
} else {
p.graphics.beginStroke(this.getColor(p.t));
}
return p.graphics.drawCircle(0, 0, p.radius);
};
ColorShader.prototype.getColor = function(c) {
c = Math.floor(c * 256);
if (this.color === 0) {
return "rgba(" + (c - 120) + ",255," + (255 - c) + "," + (c / 255) + ")";
} else if (this.color === 1) {
return "rgba(" + c + ",20," + (255 - c) + "," + (c / 255) + ")";
} else {
return "rgba(" + c + "," + c + "," + c + "," + (c / 255) + ")";
}
};
return ColorShader;
})(Behaviour);
|
describe('Image label fixer', function () {
// This should only be included for browsers (IE6/7)
// that do not correctly treat labels correctly when
// they contain an image. When the image is clicked,
// the event should trigger a click on the label element,
// which in turn should place focus on the related input
var fixer;
var mockImage;
var mockProxy;
var mockLabel;
var mockFor;
var mockFormControl;
beforeEach(function () {
mockFormControl = {
"0": {
tagName: "",
type: "",
checked: false
},
trigger: jasmine.createSpy()
};
mockFor = "mockFor";
mockImage = jasmine.createSpyObj('mockImage', ['on', 'parents']);
mockLabel = jasmine.createSpyObj('mockLabel', ['attr']);
mockLabel.attr = jasmine.createSpy().and.returnValue(mockFor);
mockImage.parents = jasmine.createSpy().and.returnValue(mockLabel);
mockProxy = {};
spyOn($, 'proxy').and.returnValue(mockProxy);
spyOn(window, '$').and.returnValue(mockFormControl);
fixer = new kitty.ImageLabelFixer(mockImage);
});
describe('Creating a new label fixer', function () {
it('Creates an img property', function () {
expect(fixer.img).toBe(mockImage);
});
it('Listens for the click event on the image', function () {
expect(mockImage.on).toHaveBeenCalledWith('click', mockProxy);
expect($.proxy).toHaveBeenCalledWith(jasmine.any(Object), "onImageClicked");
});
});
describe('Image clicked', function () {
describe('Always', function () {
beforeEach(function () {
fixer.onImageClicked();
})
it('Retrieves the parent label', function () {
expect(mockImage.parents).toHaveBeenCalledWith('label');
});
it('Retrieves the for attribute', function () {
expect(mockLabel.attr).toHaveBeenCalledWith('for');
});
it('Retrieves the related form control', function () {
expect($).toHaveBeenCalledWith('#'+mockFor);
});
});
describe('Related control is a textarea', function () {
beforeEach(function () {
mockFormControl[0].tagName = 'textarea';
fixer.onImageClicked();
});
it('Focuses on the related form control', function () {
expect(mockFormControl.trigger).toHaveBeenCalledWith('focus');
});
});
describe('Related control is a select', function () {
beforeEach(function () {
mockFormControl[0].tagName = 'select';
fixer.onImageClicked();
});
it('Focuses on the related form control', function () {
expect(mockFormControl.trigger).toHaveBeenCalledWith('focus');
});
});
describe('Related control is an input', function () {
beforeEach(function () {
mockFormControl[0].tagName = 'input';
});
describe('Text input', function () {
it('Focus on the related form control', function () {
mockFormControl[0].type = 'text';
fixer.onImageClicked();
expect(mockFormControl.trigger).toHaveBeenCalledWith('focus');
});
});
describe('Password input', function () {
it('Focus on the related form control', function () {
mockFormControl[0].type = 'password';
fixer.onImageClicked();
expect(mockFormControl.trigger).toHaveBeenCalledWith('focus');
});
});
describe('Radio input', function () {
beforeEach(function() {
mockFormControl[0].type = 'radio';
fixer.onImageClicked();
});
it('Marks the radio as checked', function () {
expect(mockFormControl[0].checked).toBe(true);
});
});
describe('Checkbox input', function () {
beforeEach(function() {
mockFormControl[0].type = 'checkbox';
});
describe('Checkbox is checked', function () {
it('Marks the checkbox as unchecked', function () {
mockFormControl[0].checked = true;
fixer.onImageClicked();
expect(mockFormControl[0].checked).toBe(false);
});
});
describe('Checkbox is not checked', function () {
it('Marks the checkbox as checked', function () {
mockFormControl[0].checked = false;
fixer.onImageClicked();
expect(mockFormControl[0].checked).toBe(true);
});
});
});
});
});
});
|
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const {interface,bytecode} = require('./compile');
const provider = new HDWalletProvider(
'recycle diamond reward swift insect fault suit measure friend bundle dinosaur observe',
'https://ropsten.infura.io/v3/2ec2a1f3b4714294907cd7bd4ae1d3ef'
);
const web3 = new Web3(provider);
var helloworld;
// async function testDeplopy () {
// const Web4 = require('web3aaa');
// const accounts = await web3.eth.getAccounts();
// aconsole.log('Attemp to deploy contract', accounts[0]);
// };
// testDeplopy();
const deploy = async()=>{
console.log(interface);
const accounts = await web3.eth.getAccounts();
//const Web4 = require('web3aaa');
//console.log('Attemp to deploy contract', accounts[0]);
//0x12F35167617906786b8DB438e5eA2754a63c8758
//helloworld = await new web3.eth.Contract(JSON.parse(interface)).deploy({data:'0x' + bytecode,arguments:['sky']}).send({from:accounts[0],gas:'1000000'});
console.log('account : '+accounts[0]);
console.log('web3 version : '+web3.version);
helloworld = await new web3.eth.Contract(JSON.parse(interface)).deploy({data:'0x' + bytecode}).send({from:accounts[0],gas:'1000000'});
//下载这个是答应出当前合约部署的目标地址
console.log('contract deployed to', helloworld.options.address);
};
deploy();
// beforeEach(async()=>{
// const accounts = await web3.eth.getAccounts();
// aconsole.log('Attemp to deploy contract', accounts[0]);
// })
// describe('deploy test',()=>{
// it('Attemp to deploy contract', ()=>{
// //var me = new person();
//
// })
// })
|
import React from 'react'
import {Switch, Redirect} from 'react-router'
import {Public, Private} from './Layout'
export default() => (
<Switch>
<Public path="/auth"/>
<Private path="/app"/>
<Redirect to="/auth"/>
</Switch>
)
|
let savedArray = [];
export function saveExpression() {
//Grabs the Screen element in which to put the answers.
let calcScreen = $('.screen')[0];
let a = calcScreen.innerHTML;
//Checks if the answer includes either Error or Infinity in which cause it doesnt push it.
if (a != "Error" && a != "Infinity" && a != "function Error() { [native code] }" && a != "undefined" && a != "NaN") {
//Checks if array length is 50, in that case pops the last index and unshifts new index
if (savedArray.length == 50) {
savedArray.pop();
savedArray.unshift(calcScreen.innerHTML);
//Removes item 50 in the list created by previous code. (51 fråga Andreas varför/hur)
$('ol li:nth-child(50)').remove();
//Adds the expression from calculator to a list and saves it in html.
$('ol').prepend("<li>" + 'Svar: ' + savedArray[0] + "</li>");
} else {
//If array.length is not 50 this just adds last expression first in the array.
savedArray.unshift(calcScreen.innerHTML);
//Adds the expression from calculator to a list and saves it in html.
$('ol').prepend("<li>" + 'Svar: ' + savedArray[0] + "</li>");
}
}
}
//TEST FUNKTIONEN FÖR SAVEDEXPRESSIONS
export function saveExpressionTest(input) {
if (input != "Error" && input != "Infinity" && input != "function Error() { [native code] }" && input != "undefined") {
if (savedArray.length == 50) {
savedArray.pop();
savedArray.unshift(input);
return savedArray;
} else {
savedArray.unshift(input);
return savedArray;
}
return null;
}
}
|
import React, { useEffect,useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import {View, StatusBar, StyleSheet, TextInput, FlatList,Pressable} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import CardHome from './CardMenuHome';
import {getAllMenus} from '../redux/actions/menu';
import {getAllCategory} from '../redux/actions/category';
import {searchMenuCreator} from '../redux/actions/serachMenu';
const Menu = () => {
// const [menu, setMenu] = useState(null);
const category = useSelector(state=>state.category.category);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getAllCategory());
dispatch(getAllMenus());
}, [dispatch]);
return (
<View style={Styles.container}>
<StatusBar style ={Styles.statusBar} barStyle="light-content" backgroundColor="#f75252"/>
<View style={Styles.header}>
<View style={Styles.search}>
<TextInput style={Styles.textInput}
placeholder="Search for dish or meal"
// onChangeText={(val)=>setMenu(val)}
// onSubmitEditing={()=>{dispatch(searchMenuCreator(menu,'menu'));
// setMenu(null);
// }}
/>
<Pressable>
<Icon style={Styles.iconSearch} name="search-outline"/>
</Pressable>
</View>
</View>
<View style={Styles.footer}>
<FlatList
data={category}
renderItem={({item})=>{
return (
<CardHome item={item}/>
);
}}
/>
</View>
</View>
);
};
const Styles = StyleSheet.create({
statusBar:{
backgroundColor:'#009387',
},
container :{
flex:1,
backgroundColor:'#f75252',
},
header:{
justifyContent: 'flex-end',
},
search:{
marginVertical:15,
marginHorizontal:10,
borderRadius:20,
backgroundColor:'white',
borderColor:'white',
flexDirection:'row',
justifyContent:'space-between',
},
textInput:{
width:'80%',
marginLeft:10,
},
iconSearch:{
fontSize:40,
marginRight:10,
marginVertical:2,
},
footer :{
flex: 6,
backgroundColor:'white',
borderTopLeftRadius: 30,
borderTopRightRadius: 30,
paddingHorizontal: 20,
paddingTop:15,
},
imgMenu:{
width:100,
height:100,
},
});
export default Menu;
|
// alert("Hello world");
// let message = "Hello world";
// alert(message);
// message = 'Hallo Welt';
// alert(message);
const LINK_COLOR = '#FF0000'
console.log("Link bitte in der Farbe", LINK_COLOR);
let highscore = 523434;
let fullname = "Jeffrey 'The Dude' Lebowski";
fullname = 'Jeffrey "The Dude" Lebowski'; // geht beides
console.log(fullname)
let template = `Dein Highscore sind ${highscore} Punkte`;
console.log(template);
// listen oder array
let participants = ["John", "Peter", "Reto"];
console.log(participants);
console.log(participants.length);
console.log(participants[0]);
let user = {
Firstname: "John",
lastname: "Smith",
age: 25
}
console.log(user);
console.log(user.Firstname);
user.highscore = 200;
user["highscore ever"] = 400
console.log(user);
// let myAge = prompt("Wie alt bist du?");
// console.log(`Du bist ${myAge} alt.`);
// if (myAge > 18) {
// console.log("Glückwunsch über 18");
// } else {
// console.log("Leider unter 18");
// }
for (let i = 0; i < 10; i++) {
console.log(`Schleife ${i}`);
}
participants.forEach(participants => {
console.log(`Teilnehmer*in ${participants}`)
});
// Fuktionen
function showAge(birthYear) {
console.log(`Du bist ca. ${2020 - birthYear} Jahre alt.`);
}
showAge(1993)
function calcAge(birthYear) {
return 2020 - birthYear;
}
console.log(`Max ist ${calcAge(1977)} Jahre alt (ca.)`);
let users = [
{ firstname: "John", lastname: "Smith", birthYear: 1960},
{ firstname: "Peter", lastname: "Halle", birthYear: 1970},
{ firstname: "Ale", lastname: "Lenk", birthYear: 1980},
];
console.log(users); // hier hatter schleife mit funktion
let firstParagraph = document.querySelector("#pFirst");
// console.log(firstParagraph);
firstParagraph.innerHTML = "Test";
firstParagraph.style.color = "red";
let indetedParas = document.querySelectorAll(".indent"); // wenn nicht querySelectorAll dann wird immer nur das erste Benutzt
console.log(indetedParas);
indetedParas.innerHTML = "Test2";
indetedParas.forEach((para, index) => {
console.log(`Data attribut LAT ${para.CDATA_SECTION_NODE.lat}`);
para.innerHTML = `Absatz ${index}`;
if ( index % 2 == 0) {
para.style.color = "red";
} else {
para.style.color = "blue";
}
});
|
var Hexo = require('../hexo');
var pathFn = require('path');
var fs = require('hexo-fs');
var cwd = process.cwd();
var lastCwd = cwd;
var byeWords = [
'Good bye',
'See you again',
'Farewell',
'Have a nice day',
'Bye!',
'Catch you later'
];
// Find Hexo folder recursively
function findConfigFile(){
// TODO: support for _config.yaml, _config.json or other extension name
return fs.exists(pathFn.join(cwd, '_config.yml')).then(function(exist){
if (exist) return;
lastCwd = cwd;
cwd = pathFn.dirname(cwd);
// Stop on root folder
if (lastCwd === cwd) return;
return findConfigFile();
});
}
function sayGoodbye(){
return byeWords[(Math.random() * byeWords.length) | 0];
}
module.exports = function(args){
var hexo;
findConfigFile().then(function(){
// Use CWD if config file is not found
if (cwd === lastCwd){
hexo = new Hexo(process.cwd(), args);
} else {
hexo = new Hexo(cwd, args);
}
return hexo.init();
}).then(function(){
var command = args._.shift();
if (command){
var c = hexo.extend.console.get(command);
if (!c || (!hexo.env.init && !c.options.init)){
command = 'help';
}
} else if (args.v || args.version){
command = 'version';
} else {
command = 'help';
}
// Listen to Ctrl+C (SIGINT) signal
process.on('SIGINT', function(){
hexo.log.info(sayGoodbye());
hexo.unwatch();
hexo.exit().then(function(){
process.exit();
});
});
return hexo.call(command, args);
}).then(function(err){
return hexo.exit(err);
});
};
|
// Require.js compliant bootstrap for whole application. See ../js/app/amicfg.js for further information
// Require.js allows us to configure shortcut alias
// There usage will become more apparent futher along in the tutorial.
requirejs.config({
// script load statement for require.js implicitly defines baseUrl as ../js/app
baseUrl: '../js',
shim: {
'underscore': {
exports: '_'
},
'jquery' : {
exports: '$'
},
'backbone': {
//These script dependencies should be loaded before loading
//backbone.js
deps: ['underscore', 'jquery'],
//Once loaded, use the global 'Backbone' as the
//module value.
exports: 'Backbone'
},
},
paths: {
jquery: 'lib/jquery/jquery',
underscore: 'lib/underscore/underscore',
backbone: 'lib/backbone/backbone',
jsDebugWrapper: 'lib/js-debug/js-debug-wrapper',
jsColorWrapper: 'lib/jscolor/jscolor-wrapper',
amChartsWrapper: 'lib/amcharts/amcharts-wrapper',
sprintf: 'lib/sprintf/sprintf',
chartDataPoints: 'collections/chart-data-points',
chartDataPoint: 'models/chart-data-point'
},
});
requirejs([
'app/application'
], function(application){
application.initialize(application);
});
|
/**
* Created by campitos on 14/10/14.
*/
|
UploadFiles = (function () {
var _submodule,
submodule,
resourceDropzone,
arrRoles = [],
sirenCode = '';
_submodule = {
getFileType: function (file_path) {
var file_ext = '';
if (file_path.lastIndexOf('.') > 0) {
file_ext = file_path.substring(file_path.lastIndexOf('.') + 1).toLowerCase();
}
return file_ext;
},
addRowForFile: function (file) {
var $preview = $(file.previewElement);
$preview
.find('.dz-details').append('<div data-dz-remove="" class="dz-remove"><button type="button" remove_res_btn="yes" class="btn btn-link"><span class="fa fa-lg fa-trash-o"></span></button></div>');
$preview.attr('data-item-type', _submodule.getFileType(file.name))
$('button[remove_res_btn="yes"]').on('click', _submodule.removeRowWithResource);
},
removeRowWithResource: function () {
$(this).closest('.dz-preview').remove();
},
addDropZone: function (url) {
sendUrl = url;
Dropzone.autoDiscover = false;
$('form').attr('enctype','multipart/form-data');
new Dropzone('div#dsn_dropzone', {
url: url,
uploadMultiple: true,
autoProcessQueue: false,
maxFiles: 10,
parallelUploads: 10,
dictDefaultMessage: 'Glisser / Déposer les fichiers ici<br />ou<br />Cliquez pour sélectionner les fichiers',
//addRemoveLinks: true,
init: function () {
resourceDropzone = this;
this.on("addedfile", function (file) {
console.log('add file', file);
_submodule.addRowForFile(file);
});
this.on("sending", function(file, xhr, formData) {
console.log('sending...');
console.log(arrRoles, sirenCode);
formData.append('roles', arrRoles);
formData.append('siren', sirenCode);
});
this.on("complete", function(file) {
//console.log('init', file);
//resourceDropzone.removeFile(file);
});
}
});
return resourceDropzone;
}
},
submodule = {
run: function (parameters) {
if(!parameters.url) {
parameters.url = '/';
}
if(parameters.roles) {
arrRoles = parameters.roles;
}
if(parameters.siren) {
sirenCode = parameters.siren;
}
return _submodule.addDropZone(parameters.url);
},
setRoles: function (roles) {
arrRoles = roles;
},
saveFiles: function (event) {
if(resourceDropzone) {
resourceDropzone.processQueue();
} else {
console.log("Undefined DropZone");
}
}
}
return submodule;
})()
|
/*
* @Description: 全局自定义指令
* @Author: 彭善智
* @LastEditors: 彭善智
* @Date: 2019-04-30 11:29:34
* @LastEditTime: 2019-04-30 11:51:11
*/
//锚点跳转
Vue.directive('href',{
inserted : function(el,binding){
el.onclick = function(){
document.documentElement.scrollTop = $("#"+binding.value).offset().top
}
}
})
|
import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import { addPaymentMethod } from '../../actions/cart'
import Checkout from '../../components/Checkout'
const Payment = ({ history }) => {
const [paymentMethod, setPaymentMethod] = useState('PayPal')
const dispatch = useDispatch()
const submitHandler = (e) => {
e.preventDefault()
dispatch(addPaymentMethod(paymentMethod))
history.push('/placeorder')
}
return (
<section className="py-5">
<Checkout step1 step2 step3 />
<div className="bg-dark py-2">
<h2 className="text-center text-white">Choose Payment Method</h2>
</div>
<div className="container text-center">
<form onSubmit={submitHandler}>
<div className="form-check">
<input type="radio" className="form-check-input" name="paymentMethod" value={paymentMethod} onChange={e => setPaymentMethod(e.target.value)} checked />
<label className="form-check-label">PayPal</label>
</div>
<div className="form-check">
<input type="radio" className="form-check-input" name="paymentMethod" value="Credit Card" onChange={e => setPaymentMethod(e.target.value)} />
<label className="form-check-label">Credit Card</label>
</div>
<button type="submit" className="btn btn-dark">Proceed To Payment</button>
</form>
</div>
</section>
)
}
export default Payment
|
import { tableColumnsByDomain } from '../../../../../scripts/utils/table-utils'
import Refund from '../../../../../models/ecommerse/refund'
import Order from '../../../../../models/ecommerse/order'
import RefundOrder from '../../../../../models/ecommerse/refundOrder'
const width = App.options.styles.table.width
const options = {
sn: {
width: width.w_12,
title: '订单编号',
render(h, context) {
const row = context.row
const onClick = async() => {
const orderPage = await Order.page(1, 10, [{ property: 'id', filterType: 'EQ', value: row.paymentOrderId }], [])
const order = orderPage.content[0]
App.modal({
width: 900,
okText: '关闭',
render: h => {
h = this.$root.$createElement
return <view-order-details order={order}></view-order-details>
}
}, 'info')
}
return <a onClick={onClick}><span>{row.extStr2}</span></a>
}
},
amount: {
width: width.w_16,
title: '金额',
render(h, context) {
return <span>{context.row.amount}</span>
}
},
refundOrderSn: {
width: width.w_12,
title: '售后单号',
render(h, context) {
const row = context.row
const onClick = async() => {
const orderPage = await RefundOrder.page(1, 10, [{ property: 'id', filterType: 'EQ', value: row.metadata.refundOrderId }], [])
const order = orderPage.content[0]
App.modal({
width: 900,
okText: '关闭',
render: h => {
h = this.$root.$createElement
return <view-refund-details refundOrder={order}></view-refund-details>
}
}, 'info')
}
return <a onClick={onClick}><span>{row.metadata.refundOrderSn}</span></a>
}
},
ctime: {
width: width.w_16,
title: '创建时间',
render(h, context) {
return <span>{dateformat(new Date(context.row.ctime), 'yyyy-mm-dd HH:MM:ss')}</span>
}
}
}
export default tableColumnsByDomain(Refund, options)
|
const request = require('request')
//Authenticates with the Control Room and returns the JWT
const auth = (crURL, userName, apiKey, callback) => {
const url = crURL + '/v1/authentication'
request({
url : url,
method :"POST",
headers : {
"content-type": "application/json",
},
body: {
'username':userName,
'password':apiKey
},
json: true
}, (e, r, body)=>{
if(e){
callback('Authorization failed. Please try again.', undefined)
} else if (r.body.message){
callback(body.message, undefined)
} else{
callback(undefined, {
token: r.body.token
})
}
})
}
module.exports = auth
|
var js = {
set:function($elem,obj){
$elem.show();
if(obj){
setWHB($elem,obj);
};
$elem.on("click",function(){
})
}
}
function setWHB($elem,obj){
$elem.css(obj);
}
|
import React, {Component,PropTypes} from 'react';
import {Link} from 'react-router';
import {connect} from 'react-redux';
import {logOut} from '../../actions/signupActions';
class BottomHeader extends React.Component {
constructor(props){
super(props);
this.state={
account:{}
}
this.logOut=this.logOut.bind(this);
}
logOut(){
this.props.logOut(this.state);
}
render(){
var accountInfo;
if(this.props.account.userName && this.props.account.accessToken){
accountInfo=(<ul className="login">
<li>Welcome <a href="#">{this.props.account.userName}</a></li> |
<li><a href="#" onClick={this.logOut}>Logout</a></li>
</ul>);
}
else{
accountInfo=( <ul className="login">
<li><Link to="/login"><span> </span>Login</Link></li> |
<li><Link to="/signup">Register</Link></li>
</ul>);
}
return (
<div className="bottom-header">
<div className="container">
<div className="header-bottom-left">
<div className="logo">
<Link to="/"><img src="../../assets/images/logo.png" alt="" /></Link>
</div>
<div className="search">
<form method="get" action="/tim-kiem.html">
<input type="text" id="txtKeyword" name="keyword" placeholder="Keyword"/>
<input type="submit" value="Search" id="btnSearch"/>
</form>
</div>
<div className="clearfix"> </div>
</div>
<div className="header-bottom-right">
{accountInfo}
<div className="cart"><Link to="/shoppingcart"><span></span>Carts</Link></div>
<div className="clearfix"> </div>
</div>
<div className="clearfix"> </div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => ({
account: state.account
});
export default connect(mapStateToProps,{logOut})(BottomHeader);
|
import {DefaultLogger as winston} from "@dracul/logger-backend";
import RBAC from "../rbac";
import RoleModel from "../models/RoleModel";
const rbacFactory = function () {
return new Promise((resolve, reject) => {
RoleModel.find({}).then(roles => {
resolve(new RBAC(roles))
}).catch(err => {
winston.error("RbacService.RbacFactory ", err)
reject(err)
})
})
}
const UserRbacFactory = async function (user) {
return new Promise((resolve, reject) => {
rbacFactory()
.then(rbac => {
if (user && user.role && user.role.name) {
rbac.addUserRoles(user.id, [user.role.name])
} else {
reject("UserRbacFactory need user.role.name")
}
resolve(rbac)
}
)
.catch(err => {
winston.error("RbacService.UserRbacFactory ", err)
reject(err)
})
})
}
export {rbacFactory, UserRbacFactory}
|
/// <reference name="MicrosoftAjax.js" />
function PBR_ApplicationInit()
{
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(PBR_BeginRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(PBR_EndRequest);
var PBR_oldText;
var PBR_oldImage;
}
function PBR_BeginRequest(sender, args)
{
var sendingPanel = sender._postBackSettings.panelID.split('|')[0];
if (PBR_IsMonitoredRequest(sendingPanel))
{
if (args.get_postBackElement().type == 'submit')
{
args.get_postBackElement().disabled = true;
args.get_postBackElement().blur();
args.get_postBackElement().style.cursor = 'wait';
PBR_oldText = args.get_postBackElement().value;
if (PBR_GetWaitText(sendingPanel) != null)
args.get_postBackElement().value = PBR_GetWaitText(sendingPanel);
}
else if (args.get_postBackElement().type == 'image')
{
args.get_postBackElement().disabled = true;
args.get_postBackElement().blur();
args.get_postBackElement().style.cursor = 'wait';
PBR_oldImage = args.get_postBackElement().src;
if (PBR_GetWaitImage(sendingPanel) != null)
args.get_postBackElement().src = PBR_GetWaitImage(sendingPanel);
}
}
}
function PBR_EndRequest(sender, args)
{
// Check to make sure the item hasn't been removed during the postback.
if ($get(sender._postBackSettings.sourceElement.id) != null && PBR_IsMonitoredRequest(sender._postBackSettings.panelID))
{
$get(sender._postBackSettings.sourceElement.id).disabled = false;
// Handles regular submit buttons.
if (sender._postBackSettings.sourceElement.type == 'submit')
$get(sender._postBackSettings.sourceElement.id).value = PBR_oldText;
// Handles image buttons.
if (sender._postBackSettings.sourceElement.type == 'image')
$get(sender._postBackSettings.sourceElement.id).src = PBR_oldImage;
}
}
function PBR_IsMonitoredRequest(panelID)
{
if (typeof(PBR_MonitoredUpdatePanels) == 'undefined')
return true;
for (i = 0; i < PBR_MonitoredUpdatePanels.length; i++)
if (panelID.match(PBR_MonitoredUpdatePanels[i]) != null)
return true;
return false;
}
function PBR_GetWaitImage(panelID)
{
for (i in PBR_WaitImages)
if (panelID.match(i) != null)
return PBR_WaitImages[i];
if (typeof(PBR_WaitImage) != 'undefined')
return PBR_WaitImage;
else
return null;
}
function PBR_GetWaitText(panelID)
{
for (i in PBR_WaitTexts)
if (panelID.match(i) != null)
return PBR_WaitTexts[i];
if (typeof(PBR_WaitText) != 'undefined')
return PBR_WaitText;
else
return null;
}
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();
|
import React from "react";
import { useHistory } from "react-router-dom";
import styled from "styled-components";
import { FaLaptopCode } from "react-icons/fa";
import { Colors } from "../Global/Color";
export const Logo = () => {
const history = useHistory();
return (
<Wrapper onClick={() => history.push("/")}>
<FaLaptopCode />
<Name>SamSTPL</Name>
</Wrapper>
);
};
const Wrapper = styled.button`
z-index: 20;
position: absolute;
top: 5%;
left: 10%;
background: transparent;
border: none;
transform: translate(-50%, -50%);
display: flex;
align-items: center;
color: ${Colors.blue};
font-size: 2.2rem;
@media (max-width: 1024px) {
font-size: 1.5rem;
}
@media (max-width: 770px) {
font-size: 1.3rem;
left: 15%;
}
@media (max-width: 500px) {
top: 95%;
font-size: 1.2rem;
left: 50%;
}
&:hover {
cursor: pointer;
}
&:focus {
outline: none;
}
`;
const Name = styled.p`
margin-left: 10px;
letter-spacing: 0.15em;
background: -webkit-linear-gradient(${Colors.hoverBlue}, #333);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
`;
|
var xspacing = 16;
var w;
var theta = 0.0;
var amplitude = 75.0;
var period = 500.0;
function setup() {
createCanvas(1024, 768);
}
function draw() {
background(0);
lock_draw_line();
}
/*
* Modification of
* https://github.com/mortehu/cantera-lock/../lock.c
*/
function lock_draw_line() {
var i, j;
var x_count;
var ys;
var now = new Date().getTime() / 1000;
x_count = 200 * width / 1366;
if (x_count < 50) x_count = 50;
ys = new Array();
for (i = 0; i < x_count; ++i)
ys[i] =
0.07 * sin(i * 0.035 + cos(i * 0.021 + now + sin(i * 0.043 + now) * 0.22));
strokeWeight(0.5);
for (j = 0; j < 5; ++j) {
for (i = 0; i < x_count; ++i) {
var x, y, theta, twist, scale, a, r, g, b;
x = i * width / (x_count - 1);
twist = sin(-0.7 * now + i * 0.021 + cos(1.1 * now + i * 0.031));
theta = j + i * 0.1 + 2.0 * now + 3.2 * twist;
a = 0.6 + 0.6 * cos(theta);
scale = 0.05 - 0.03 * (1.0 - abs(twist));
y = ys[i] + scale * sin(theta);
r = 0.2 * a;
g = 0.7 * twist;
b = scale * 0.3;
if (r > 1.0) r = 1.0;
if (g > 1.0) g = 1.0;
if (b > 1.0) b = 1.0;
fill(color(r, g * 255, b * 255, 200))
y = y * height + height * 0.5;
ellipse(x, y, 16, 16);
console.log(x + ", " + y);
}
}
}
|
$(document).ready(function () {
function earzymodel(artist, title, album) {
this.artist = ko.observable(artist);
this.title = ko.observable(title);
this.album = ko.observable(album);
this.nosongs = ko.observable(0);
this.mp3 = ko.observable();
this.url = ko.observable();
};
var myvm = new earzymodel("-", "-", "-", 0);
ko.applyBindings(myvm);
var uriPrefix;
var uriSuffix;
var oTable;
var uri = 'api/tracks';
$(function () {
$("#jquery_jplayer_1").jPlayer({
ready: function () {
//$(this).jPlayer("setMedia", {
// mp3: "https://jacobsmedia.blob.core.windows.net/uploads/01%20Anguish.mp3?sr=c&si=media&sig=J5%2B5IqsN2TcwlLgEK%2FMF%2Ft7VVAb1qwG2eDvLybrddHU%3D" // Defines the m4v url
//});
},
supplied: "mp3",
wmode: "window",
smoothPlayBar: true,
keyEnabled: true,
error: function (event) {
var time = $("#jquery_jplayer_1").data().jPlayer.status.currentTime;
if (time > 0) {
$("#jquery_jplayer_1").jPlayer("play", time);
}
else {
function Breath() {
setTimeout(function () {
$("#jquery_jplayer_1").jPlayer("play", 0);
}, 5000);
}
}
}
});
$("#jquery_jplayer_1").bind($.jPlayer.event.ended + ".repeat", function () {
var randomnumber = Math.floor(Math.random() * (myvm.nosongs() - +1));
var row = oTable.fnGetData(randomnumber);
myvm.artist(row.artist);
myvm.title(row.title);
myvm.album(row.album);
myvm.mp3(row.mp3);
var blobpath = myvm.mp3();
if (blobpath.substring(blobpath.length - 4, blobpath.length) != ".mp3") {
blobpath += ".mp3"
}
myvm.url(uriPrefix + blobpath + uriSuffix);
$(this).jPlayer("setMedia", { mp3: myvm.url() });
$(this).jPlayer("play");
});
});
$("#stopbutton").click(function () {
$("#jquery_jplayer_1").jPlayer("stop");
});
$.getJSON(uri)
.done(function (data) {
myvm.nosongs(data.length);
$('#tablecontainer').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
oTable = $('#example').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bInfo": false,
"bAutoWidth": false,
"bScrollCollapse": false,
"sScrollY": "220px",
"bProcessing": true,
"sAjaxSource": 'api/tracks/',
"sAjaxDataProp": "",
"aoColumns": [
{
"mDataProp": "artist"
},
{
"mDataProp": "title"
},
{
"mDataProp": "album"
},
{
"bVisible": false, "mDataProp": "mp3"
}
]
});
$.getJSON('api/tracks/geturitemplate')
.done(function (data) {
uriPrefix = data.Prefix.substring(0, data.Prefix.length - 1);
uriSuffix = data.Suffix;
var accesSignature = data;
$('#nextbutton').live("click", function () {
var time = $("#jquery_jplayer_1").data().jPlayer.status.duration;
$("#jquery_jplayer_1").jPlayer("play", time - 0.1);
});
$('#nosongs').live("click", function () {
$.getJSON('api/tracks/GetFreshData')
.done(function (data) {
var x = data;
});
});
$('#example tbody td').live('click', function () {
var aPos = oTable.fnGetPosition(this);
var aData = oTable.fnGetData(aPos[3]);
//ko.applyBindings(new myvm(aData[aPos[0]].artist, aData[aPos[0]].title, aData[aPos[0]].album)); data.artist = aData[aPos[0]].artist;
myvm.artist(aData[aPos[0]].artist);
myvm.title(aData[aPos[0]].title);
myvm.album(aData[aPos[0]].album);
myvm.mp3(aData[aPos[0]].mp3);
var blobpath = aData[aPos[0]].mp3;
if (blobpath.substring(blobpath.length - 4, blobpath.length) != ".mp3") {
blobpath += ".mp3"
}
myvm.url(uriPrefix + blobpath + uriSuffix);
$("#jquery_jplayer_1").jPlayer("setMedia", { mp3: myvm.url() });
$("#jquery_jplayer_1").jPlayer("play");
});
});
var uriartitst = 'api/tracks/getartists';
$.getJSON(uriartitst)
.done(function (data) {
var availableTags = data;
//$("#artistssearch").autocomplete({
// source: availableTags
//});
//$("#auto").autocomplete({
// source: function (request, response) {
// var results = $.ui.autocomplete.filter(myarray, request.term);
// response(results.slice(0, 10));
// },
// select: function (event, ui) {
// alert('fdfd' + ui.item.value);
// return false;
// }
//});
});
});
});
|
$(".message a").click(function () {
$("form").animate({
height: "toggle",
opacity: "toggle"
}, "slow")
})
const FName = document.getElementById("fname")
const LName = document.getElementById("lname")
const Phone = document.getElementById("phone")
const Address = document.getElementById("address")
const Email = document.getElementById("email")
const Pass = document.getElementById("password")
const CPass = document.getElementById("cpassword")
const FNameError = document.getElementById("error1")
const LNameError = document.getElementById("error2")
const PhoneError = document.getElementById("error3")
const AddressError = document.getElementById("error4")
const EmailError = document.getElementById("error5")
const PassError = document.getElementById("error6")
const CPassError = document.getElementById("error7")
const Strength = document.getElementById("strength")
const RegisterForm = document.getElementById("register-form")
const indicator = document.querySelector(".indicator");
const input = document.getElementById("password")
const weak = document.querySelector(".weak");
const medium = document.querySelector(".medium");
const strong = document.querySelector(".strong");
const text = document.querySelector(".strength");
let regExpWeak = /[a-zA-Z]+/;
let regExpMedium = /\d+/;
let regExpStrong = /[!@#$%^&*?_~(),-]+/;
function trigger() {
let no;
if (input.value !== "") {
indicator.style.display = "block";
indicator.style.display = "flex";
if (input.value.length <= 3 && (input.value.match(regExpWeak) || input.value.match(regExpMedium) || input.value.match(regExpStrong))) no = 1;
if (input.value.length >= 6 && ((input.value.match(regExpWeak) && input.value.match(regExpMedium)) || (input.value.match(regExpMedium) && input.value.match(regExpStrong)) || (input.value.match(regExpWeak) && input.value.match(regExpStrong)))) no = 2;
if (input.value.length >= 6 && input.value.match(regExpWeak) && input.value.match(regExpMedium) && input.value.match(regExpStrong)) no = 3;
if (no === 1) {
weak.classList.add("active");
text.style.display = "block";
text.textContent = "Your password is too week";
text.classList.add("weak");
}
if (no === 2) {
medium.classList.add("active");
text.textContent = "Your password is medium";
text.classList.add("medium");
} else {
medium.classList.remove("active");
text.classList.remove("medium");
}
if (no === 3) {
weak.classList.add("active");
medium.classList.add("active");
strong.classList.add("active");
text.textContent = "Your password is strong";
text.classList.add("strong");
} else {
strong.classList.remove("active");
text.classList.remove("strong");
}
} else {
indicator.style.display = "none";
text.style.display = "none";
}
}
function validateEmail(emailText) {
const re = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
return re.test(String(emailText).toLowerCase());
}
function validatePhone(phoneText) {
const re = /^[\d\.\-]+$/;
return re.test(String(phoneText));
}
function validateName(nameText) {
const re = /^[a-zA-Z]*$/;
return re.test(String(nameText));
}
Pass.addEventListener('change', () => {
console.log("Yo")
})
RegisterForm.addEventListener('submit', (e) => {
e.preventDefault()
FNameError.innerHTML = ""
LNameError.innerHTML = ""
PhoneError.innerHTML = ""
AddressError.innerHTML = ""
EmailError.innerHTML = ""
PassError.innerHTML = ""
CPassError.innerHTML = ""
if (!validateName(FName.value)) {
FNameError.innerText = "Please enter a valid first name."
}
if (!validateName(LName.value)) {
LNameError.innerText = "Please enter a valid last name."
}
if (!validatePhone(Phone.value)) {
PhoneError.innerText = "Please enter a valid phone number."
}
if (!validateEmail(Email.value)) {
EmailError.innerText = "Please enter a valid email."
}
if (Pass.value.length < 8) {
PassError.innerHTML = "Password must be at least 8 digits."
} else if (Pass.value !== CPass.value) {
CPassError.innerHTML = "Password is not matching."
Pass.value = ""
CPass.value = ""
}
})
|
$( "#començar" ).click(function() {
$( ".block" ).animate({
left: 420,
}, {
duration: 3000,
step: function( now, fx ){
$( ".block:gt(0)" ).css( "left", now );
}
});
});
$( "#començar" ).click(function() {
$( ".block" ).animate({
left: 600,
}, {
duration: 5000,
step: function( now, fx ){
$( ".block:gt(0)" ).css( "left", now );
}
});
});
$( "#començar" ).click(function() {
$( ".malamente" ).animate({
left: 390,
}, {
duration: 3000,
step: function( now, fx ){
$( ".malamente:gt(0)" ).css( "left", now );
}
});
});
$( "#començar" ).click(function() {
$( ".bien" ).animate({
left: 520,
}, {
duration: 7000,
step: function( now, fx ){
$( ".malamente:gt(0)" ).css( "left", now );
}
});
});
$( "#reset" ).click(function() {
$( ".block" ).css({
left: -100,
});
});
$( "#reset" ).click(function() {
$( ".malamente" ).css({
left: -200,
});
});
$( "#reset" ).click(function() {
$( ".bien" ).css({
left: -300,
});
});
|
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
EmployeeProvider = function(host, port) {
this.db = new Db('node-mongo-contact', new Server(host, port, {
safe: false
}, {
auto_reconnect: true
}, {}));
this.db.open(function() {});
};
EmployeeProvider.prototype.getCollection = function(callback) {
this.db.collection('contacts', function(error, contacts_collection) {
if (error) callback(error);
else callback(null, contacts_collection);
});
};
//find all employees
EmployeeProvider.prototype.findAll = function(callback) {
this.getCollection(function(error, contacts_collection) {
if (error) callback(error)
else {
contacts_collection.find().toArray(function(error, results) {
if (error) callback(error)
else callback(null, results)
});
}
});
};
//save new employee
EmployeeProvider.prototype.save = function(contacts, callback) {
this.getCollection(function(error, contacts_collection) {
if (error) callback(error)
else {
if (typeof(contacts.length) == "undefined")
contacts = [contacts];
for (var i = 0; i < contacts.length; i++) {
contacts = contacts[i];
contacts.datemet = new Date('03/20/2015');
}
contacts_collection.insert(contacts, function() {
callback(null, contacts);
});
}
});
};
//find an employee by ID
EmployeeProvider.prototype.findById = function(id, callback) {
this.getCollection(function(error, contacts_collection) {
if( error ) callback(error)
else {
contacts_collection.findOne({_id: contacts_collection.db.bson_serializer.ObjectID.createFromHexString(id)}, function(error, result) {
if( error ) callback(error)
else callback(null, result)
});
}
});
};
// update an employee
EmployeeProvider.prototype.update = function(employeeId, employees, callback) {
this.getCollection(function(error, contacts_collection) {
if (error) callback(error);
else {
contacts_collection.update({
_id: contacts_collection.db.bson_serializer.ObjectID.createFromHexString(employeeId)
},
employees,
function(error, employees) {
if (error) callback(error);
else callback(null, employees)
});
}
});
};
//delete employee
EmployeeProvider.prototype.delete = function(employeeId, callback) {
this.getCollection(function(error, contacts_collection) {
if (error) callback(error);
else {
contacts_collection.remove({
_id: contacts_collection.db.bson_serializer.ObjectID.createFromHexString(employeeId)
},
function(error, employee) {
if (error) callback(error);
else callback(null, employee)
});
}
});
};
exports.EmployeeProvider = EmployeeProvider;
|
import { Link } from "react-router-dom";
import React from "./topbar.css";
function Topbar() {
const user=true;
return (
<div className="top">
<div className="topLeft">
<i className="topIcon fab fa-facebook-square"></i>
<i className="topIcon fab fa-twitter"></i>
<i className="topIcon fab fa-instagram"></i>
<i className="topIcon fab fa-pinterest"></i>
</div>
<div className="topCenter">
<ul className="topList">
<li className="topListIcon">
<Link to="/"className="link">HOME</Link>
</li>
<li className="topListIcon"><Link to="/"className="link">ABOUT</Link></li>
<li className="topListIcon"><Link to="/"className="link">CONTACT</Link></li>
<li className="topListIcon"><Link to="/write"className="link">WRITE</Link></li>
<li className="topListIcon"> {user && "LOGOUT"} </li>
</ul>
</div>
<div className="topRight">
{
user?(
<img className="topImage"
src="https://pbs.twimg.com/profile_images/1134828661306212354/wsTX4Bx1.jpg" alt="" />
):(
<ul className="topList">
<li className="topListIcon"><Link to="/login"className="link">LOGIN</Link></li>
<li className="topListIcon"> <Link to="/register" className="link">REGISTER</Link> </li>
</ul>
)
}
<i className="topSearchIcon fas fa-search"></i>
</div>
</div>
)
}
export default Topbar;
|
import React, { Component } from 'react';
class Carregando extends Component {
render() {
return (
<div className="d-flex justify-content-center p-5">
<div className="spinner-border" role="status">
<span className="sr-only" />
</div>
</div>
// <div className="spinner-border text-secondary" role="status" />
);
}
}
export default Carregando;
|
import React, { Component } from 'react';
import {Text, View, StyleSheet,Picker,TextInput,Image,Button,ListView, TouchableOpacity,ScrollView,} from 'react-native';
import SearchPOC from './SearchPOC';
import axios from 'axios';
import { Container, Header, Content, Spinner } from 'native-base';
export default class LiveData extends Component{
static navigationOptions = {
title: 'PROCESSED',
headerStyle:{ backgroundColor: 'red', paddingTop:20,marginBottom:2},
headerTitleStyle:{ color: 'white'},
height:160,
};
constructor() {
super();
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(['C1234', 'C5678']),
data:''
};
}
componentDidMount(){
this.getData();
}
getData(){
axios.get('https://ns-idpovaimhn.now.sh/alert', {
headers: {
'Content-Type': 'application/json',
},
params: {
AlertStatus: "all"
}
})
.then((response) => {
this.setState({data: response.data});
})
.catch( (error) => {
//const response = error.response
console.log(response)
})
}
onRowClick(){
alert("onRowClick triggered");
}
render() {
// this.getData();
return (
<ScrollView style={{marginBottom:1}}>
{
this.state.data != '' ? <SearchPOC buttonShow={false} passedData={this.state.data}/> :<View>
<Spinner color='red' />
</View>
}
</ScrollView>
);
}
}
const styles = StyleSheet.create({
headerRight: {
justifyContent:'flex-start',
flexDirection:'row',
borderWidth:1,
paddingTop:25,
flex: 1,
margin:5,
paddingLeft:0,
},
textStyle: {
color:'black',
fontSize:20,
paddingTop:13,
borderBottomWidth:0,
borderColor:'#D1D1D1',
}
});
|
import React, { useRef, useEffect, useState } from 'react';
import _, {debounce} from 'lodash';
import ImageWrapper from '../image-wrapper';
import InputField from '../input-field';
import searchIcon from '../../static/icons8-search-192.png';
const SearchBar = (props) => {
const inputRef = useRef(null);
const [searchQuery, updateSearchQuery] = useState('');
const onChangeHandler = event => {
const query = event.target.value;
updateSearchQuery(query);
doSearch(query);
}
const doSearch = useRef(
debounce(query => {
props.doSearch(query)
}, 300)
).current
/*
* add auto-focus to the main search field
*/
useEffect(() => {
inputRef.current.focus();
}, []);
return (
<div className="search-bar-wrapper">
<ImageWrapper
src={searchIcon}
alt="search-icon"
width="20"
height="20"
customClassName="search-icon"/>
<InputField
type="text"
value={searchQuery}
onChangeHandler={onChangeHandler}
placeholder="search your favourite repository"
wrapperClassName="search-field-container"
className="search-input-field"
name="search-input-field"
id="search-input-field"
ref={inputRef}/>
</div>
)
}
export default SearchBar;
|
var animations = ['idle', 'crouch', 'walk', 'run', 'crouchWalk', 'die'];
class Enemy {
constructor(id, mesh, skeleton, weapon, shootingRangeUnits, accuracy, scene) {
this.id = id;
this.shootingRangeUnits = shootingRangeUnits;
this.accuracy = accuracy;
this.mesh = mesh;
// this.mesh.showBoundingBox = true;
this.mesh.position.y -= 10;
this.skeleton = skeleton;
this.skeleton.enableBlending(0.065);
this.scene = scene;
this.activeAnim = null;
this.activeAnimName = '';
this.weapon = weapon;
this.weapon.scaling = new BABYLON.Vector3(.8, .8, .8);
this.weapon.rotation.y += Math.PI / 2;
this.weapon.rotation.y -= .01;
this.weapon.rotation.z += Math.PI / 2;
// this.weapon.rotation.x += Math.PI;
this.weapon.rotation.x += .1;
this.weapon.attachToBone(this.skeleton.bones[20], this.mesh);
this.weapon.position.x += 5.0;
this.weapon.position.z += 1.0;
this.weapon.position.y -= .1;
this.times = 1;
this.frontVector = new BABYLON.Vector3(1, 0, 0);
this.speed = 0;
this.mesh.checkCollisions = true;
// this.mesh.position.y += 5.3;
//this.mesh.showBoundingBox = true;
this.mesh.actionManager = new BABYLON.ActionManager(scene);
this.nearObstacle = false;
this.originalRotation = this.mesh.rotation.y;
this.animationSwitchAfter = 400;
this.distance = 800;
this.reactToShotDistance = 1500;
this.ray = new BABYLON.Ray();
this.rayHelper = new BABYLON.RayHelper(this.ray);
this.rayHelper.attachToMesh(this.mesh, this.frontVector, new BABYLON.Vector3(33.6, 0, 0), this.reactToShotDistance);
//this.rayHelper.show(this.scene);
var localMeshDirection = this.frontVector;
var localMeshOrigin = this.mesh.position;
var length = 5;
this.timer = 5001;
this.enemyResult;
this.enemy3PathBlockIndex;
this.findPlayer;
this.headBox = new BABYLON.MeshBuilder.CreateBox("head", { width: 10, height: 10, depth: 7 }, this.scene);
this.headBox.parent = this.mesh;
this.headBox.position.y += 0;
this.headBox.position.x += 5;
this.headBox.position.z -= 0;
this.headBox.visibility = false;
this.headBox.enemy = this;
this.mesh.enemy = this;
this.headBox.attachToBone(
this.skeleton.bones[7], this.mesh);
this.dead = false;
this.deathSound = null;
this.lastPlayerPosition = null;
this.enemyPathBlockIndex = 0;
this.findPlayer = true;
this.previousBlock = null;
this.currentBlock = null;
this.mesh.ellipsoid = new BABYLON.Vector3(15.0, 30, 15.0);
this.waitBeforeNextShot = 100;
this.loopsFromLastShot = 0;
this.health = 100;
var enemy = this;
this.isAvoidingCollision = false;
this.mesh.computeWorldMatrix(true);
this.idle();
this.currentX = -10000;
this.currentY = -10000;
this.isShot = false;
// this.drawEllipsoid();
}
}
Enemy.prototype.getEnemeyPlayerDelta = function (rotatingObject, pointToRotateTo) {
// a directional vector from one object to the other one
var direction = pointToRotateTo.subtract(rotatingObject.position);
var v1 = this.frontVector.normalize();
var v2 = direction;
// caluculate the angel for the new direction
var angle = Math.acos(BABYLON.Vector3.Dot(v1, v2.normalize()));
//console.log(angle);
// decide it the angle has to be positive or negative
if (direction.z > 0) angle = angle * -1;
// calculate both angles in degrees
var angleDegrees = Math.floor(angle * 180 / Math.PI);
var playerRotationDegress = Math.floor(rotatingObject.rotation.y * 180 / Math.PI);
var deltaDegrees = playerRotationDegress - angleDegrees;
if (deltaDegrees > 180) {
deltaDegrees = deltaDegrees - 360;
} else if (deltaDegrees < -180) {
deltaDegrees = deltaDegrees + 360;
}
return deltaDegrees;
}
Enemy.prototype.start = function (enemy) {
var num = Math.floor(Math.random() * (animations.length - 1));
enemy.animate(animations[num]);
}
Enemy.prototype.animate = function (animation) {
if (this.activeAnim != null) {
this.activeAnim.stop();
}
switch (animation) {
case 'idle':
this.speed = 0;
this.activeAnim = this.animateIdle(true);
break;
case 'crouch':
this.speed = 0;
this.activeAnim = this.crouch();
break;
case 'walk':
this.speed = 0.9;
this.activeAnim = this.animateWalk(true);
break;
case 'run':
this.speed = 1.7;
this.activeAnim = this.animateRun(true);
break;
case 'crouchWalk':
this.speed = 0.6;
this.activeAnim = this.animateCrouchWalk(true);
break;
case 'jump':
this.speed = 1.1;
this.activeAnim = this.jump();
break;
case 'die':
this.speed = 0;
this.activeAnim = this.animateDie(false);
break;
}
}
Enemy.prototype.animateIdle = function (loop) {
var idleAnim = this.scene.beginAnimation(this.skeleton, 0, 64, loop);
return idleAnim;
}
Enemy.prototype.crouch = function (loop) {
var crouchAnim = this.scene.beginAnimation(this.skeleton, 66, 95, loop);
return crouchAnim;
}
Enemy.prototype.animateWalk = function (loop) {
var walkAnim = this.scene.beginAnimation(this.skeleton, 96, 128, loop);
return walkAnim;
}
Enemy.prototype.animateRun = function (loop) {
var runAnim = this.scene.beginAnimation(this.skeleton, 130, 165, loop, 2);
return runAnim;
}
Enemy.prototype.animateCrouchWalk = function (loop) {
var crouchWalkAnim = this.scene.beginAnimation(this.skeleton, 167, 196, loop, 1.5);
return crouchWalkAnim;
}
Enemy.prototype.jump = function (loop) {
var jumpAnim = this.scene.beginAnimation(this.skeleton, 197, 256, loop);
return jumpAnim;
}
Enemy.prototype.animateDie = function (loop) {
var enemy = this;
var dieAnim = this.scene.beginAnimation(this.skeleton, 695, 749, loop, 1, function () {
setTimeout(function () { enemy.mesh.dispose(); enemy.headBox.dispose(); enemy.weapon.dispose(); enemy.deathSound.dispose(); if (cells[this.currentX][this.currentY]) cells[this.currentX][this.currentY] = 0; }, 1000);
});
return dieAnim;
}
Enemy.prototype.gotHit = function (shotImpact) {
this.health -= shotImpact;
var distance = Math.floor(BABYLON.Vector3.Distance(this.mesh.position, player.position));
console.log(distance + ", " + this.distance);
if (distance <= this.reactToShotDistance)
this.isShot = true;
if (this.health < 0) {
this.die();
}
}
Enemy.prototype.die = function () {
if (this.dead) {
return;
}
if (audioEnabled) {
if (this.deathSound == null) {
this.deathSound = enemyDeath.clone();
}
this.deathSound.setPosition(this.mesh.position);
this.deathSound.play();
}
this.dead = true;
this.animate('die');
enemies.pop(this);
}
Enemy.prototype.walk = function () {
this.animate('walk');
}
Enemy.prototype.run = function () {
if (this.activeAnimName == 'run')
return;
this.activeAnimName = 'run';
this.animate('run');
}
Enemy.prototype.idle = function () {
if (this.activeAnimName == 'idle')
return;
this.activeAnimName = 'idle';
this.animate('idle');
}
Enemy.prototype.crouchWalk = function () {
if (this.activeAnimName == 'crouchWalk')
return;
this.activeAnimName = 'crouchWalk';
this.animate('crouchWalk');
}
Enemy.prototype.setBlending = function () {
this.skeleton.bones.forEach(function (bone) {
bone.animations.forEach(function (animation) {
animation.enableBlending = true;
animation.blendingSpeed = 1.75;
});
});
}
Enemy.prototype.predicate = function (mesh) {
if (mesh.name.startsWith("wall") || (this.mesh.name != mesh.name && mesh.name.startsWith("enemy"))) {
return true;
}
return false;
}
Enemy.prototype.castRay = function () {
var thisName = this.mesh.name;
var hit = this.scene.pickWithRay(this.ray, function (mesh) {
if (mesh.name == "player box") {
return true;
}
//now this always returns true to check if there are obstacles between me and player
return true;
});
if (hit.pickedMesh && hit.pickedMesh.name == "player box") {
this.destination = 600;
return hit.pickedMesh;
}
return null;
}
Enemy.prototype.runBeforeRender = function () {
var currentX = Math.floor(this.mesh.position.x / unit) + cells.length / 2;
var currentY = Math.floor(this.mesh.position.z / unit) + cells.length / 2;
if (this.currentX == -10000) {
this.currentX = currentX;
}
if (this.currentY == -10000) {
this.currentY = currentY;
}
if (this.currentX != currentX || this.currentY != currentY) {
// var block = this.scene.getMeshByName("block" + this.currentX + "_" + this.currentY);
// block.material.diffuseColor = new BABYLON.Color3.White();
cells[this.currentX][this.currentY] = Math.floor((Math.random() * 8) + 2);
cellEnemy[currentX + "_" + currentY] = null;
}
else {
// var block = this.scene.getMeshByName("block" + currentX + "_" + currentY);
// block.material.diffuseColor = new BABYLON.Color3.Yellow();
cells[currentX][currentY] = 0;
cellEnemy[currentX + "_" + currentY] = this.id;
}
this.currentX = currentX;
this.currentY = currentY;
if (this.dead)
return;
var target = player.position.clone();
var distance = Math.floor(BABYLON.Vector3.Distance(this.mesh.position, target));
if (this.playerMoved() && !this.findPlayer) {
this.findPath();
}
if (!this.isShot && this.findPlayer && distance > this.distance) {
if (this.enemyResult && this.enemyPathBlockIndex < this.enemyResult.length && this.findPlayer) {
var cell = cells[this.enemyResult[this.enemyPathBlockIndex].x][this.enemyResult[this.enemyPathBlockIndex].y];
if (cell == 0 && cellEnemy[this.enemyResult[this.enemyPathBlockIndex].x + "_" +
this.enemyResult[this.enemyPathBlockIndex].y] != this.id) {
this.idle();
this.findPath();
return;
}
var newPos = new BABYLON.Vector3((this.enemyResult[this.enemyPathBlockIndex].x) * unit - 1650,
this.mesh.position.y, (this.enemyResult[this.enemyPathBlockIndex].y) * unit - 1650);
//Not sure why this correction is needed
newPos.x += unit;
newPos.z += unit;
deltaDegrees = this.getEnemeyPlayerDelta(this.mesh, newPos);
if (Math.abs(deltaDegrees) > 2) {
this.facePoint(this.mesh, newPos, deltaDegrees);
}
this.moveToTarget(this.mesh, newPos, this.speed);
if (BABYLON.Vector3.Distance(this.mesh.position, newPos) < 20) {
this.enemyPathBlockIndex++;
}
}
if (distance > this.distance + (this.distance / 4)) {
this.run();
}
else
if (distance > this.distance + 20) {
this.crouchWalk();
}
}
else {
this.findPlayer = false;
this.idle();
var deltaDegrees = this.getEnemeyPlayerDelta(this.mesh, target);
if (Math.abs(deltaDegrees) > 0.5) {
this.facePoint(this.mesh, target, deltaDegrees);
}
var hitMesh = this.castRay();
if (hitMesh != null) {
if (this.loopsFromLastShot >= this.waitBeforeNextShot) {
if (audioEnabled) {
var soundTurn = Math.floor((Math.random() * 3) + 1);
if (soundTurn % 2 == 0)
whizz.play();
else
enemyShooting.play();
}
player.hit(Math.floor((Math.random() * 2000) + 1000) / distance);
this.loopsFromLastShot = 0;
}
else {
this.loopsFromLastShot++;
}
}
}
}
Enemy.prototype.avoidCollision = function (dir, collidingEnemy) {
this.isAvoidingCollision = true;
this.mesh.rotation.y = dir * this.mesh.rotation.y;
this.collidingEnemy = collidingEnemy;
}
Enemy.prototype.findPath = function () {
var start = graph.grid[Math.floor((this.mesh.position.x + (grounSideLength / 2)) / unit)][Math.floor((this.mesh.position.z + (grounSideLength / 2)) / unit)];
var end = graph.grid[Math.floor((player.position.x + (grounSideLength / 2)) / unit)][Math.floor((player.position.z + (grounSideLength / 2)) / unit)];
this.enemyResult = astar.search(graph, start, end/*, { heuristic: astar.heuristics.diagonal }*/);
if (this.enemyResult.length > 2) {
this.enemyPathBlockIndex = 0;
this.findPlayer = true;
this.isShot = false;
}
}
Enemy.prototype.playerMoved = function () {
if (this.lastPlayerPosition == null) {
this.lastPlayerPosition = player.position.clone();
this.lastPlayerPosition = player.position.clone();
this.findPlayer = false;
return true;
}
var playerMovement = Math.floor(BABYLON.Vector3.Distance(this.lastPlayerPosition, player.position));
if (playerMovement / unit > 2) {
this.lastPlayerPosition = player.position.clone();
this.findPlayer = false;
return true;
}
return false
}
Enemy.prototype.facePoint = function (rotatingObject, pointToRotateTo, deltaDegrees) {
var rotationSpeed = Math.abs(deltaDegrees) / 7;
if (deltaDegrees > 0) {
rotatingObject.rotation.y -= rotationSpeed * Math.PI / 180;
if (rotatingObject.rotation.y < -Math.PI) {
rotatingObject.rotation.y = Math.PI;
}
}
if (deltaDegrees < 0) {
rotatingObject.rotation.y += rotationSpeed * Math.PI / 180;
if (rotatingObject.rotation.y > Math.PI) {
rotatingObject.rotation.y = -Math.PI;
}
}
}
Enemy.prototype.moveToTarget = function (objectToMove, pointToMoveTo, speed, slowDown) {
var moveVector = pointToMoveTo.subtract(objectToMove.position);
moveVector.y = 0;
if (moveVector.length() > speed) {
moveVector = moveVector.normalize();
moveVector = moveVector.scale(speed);
moveVector.y = -9.8;
objectToMove.moveWithCollisions(moveVector);
}
}
Enemy.prototype.checkCollisions = function () {
for (var i = 0; i < enemies.length; i++) {
if (enemies[i].mesh.name != this.mesh.name) {
if (this.mesh.intersectsMesh(enemies[i].mesh, false)) {
collisionHandler(this.mesh, enemies[i].mesh);
}
}
}
}
Enemy.prototype.drawEllipsoid = function () {
var mesh = this.mesh;
mesh.computeWorldMatrix(true);
var ellipsoidMat = mesh.getScene().getMaterialByName("__ellipsoidMat__");
if (!ellipsoidMat) {
ellipsoidMat = new BABYLON.StandardMaterial("__ellipsoidMat__", mesh.getScene());
ellipsoidMat.wireframe = true;
ellipsoidMat.emissiveColor = BABYLON.Color3.Green();
ellipsoidMat.specularColor = BABYLON.Color3.Black();
}
var ellipsoid = BABYLON.Mesh.CreateSphere("__ellipsoid__", 9, 1, mesh.getScene());
ellipsoid.scaling = mesh.ellipsoid.clone();
ellipsoid.scaling.y *= 2;
ellipsoid.scaling.x *= 2;
ellipsoid.scaling.z *= 2;
ellipsoid.material = ellipsoidMat;
ellipsoid.parent = mesh;
ellipsoid.computeWorldMatrix(true);
}
var clearCollision = function (mesh1, mesh2) {
var index1 = -1;
var index2 = -1;
if (mesh1.enemy.id < mesh2.enemy.id) {
index1 = mesh1.enemy.id - 1;
index2 = mesh2.enemy.id - 1;
}
else {
index2 = mesh1.enemy.id - 1;
index1 = mesh2.enemy.id - 1;
}
collisionMatrix[index1][index2] = null;
}
var collisionHandler = function (mesh1, mesh2) {
var index1 = -1;
var index2 = -1;
if (mesh1.enemy.id < mesh2.enemy.id) {
index1 = mesh1.enemy.id - 1;
index2 = mesh2.enemy.id - 1;
}
else {
index2 = mesh1.enemy.id - 1;
index1 = mesh2.enemy.id - 1;
}
var collisionMatrixEntry = collisionMatrix[index1][index2];
if (collisionMatrixEntry == null) {
collisionMatrix[index1][index2] = mesh1;
console.log("rotation: " + mesh1.rotation.y + ", " + mesh2.rotation.y);
var delta = mesh1.enemy.getEnemeyPlayerDelta(mesh1, mesh2.position);
mesh1.enemy.avoidCollision(1, mesh2);
mesh2.enemy.avoidCollision(-1, mesh1);
}
else {
setTimeout(function () { collisionMatrix[index1][index2] = null; }, 2000);
}
}
|
import {
init
} from "./main.js";
window.onload = init;
|
//Question 3
//Suppose you have an array of 101 integers. This array is already sorted and all numbers in this array are consecutive. Each number only occurs once in the array except one number which occurs twice. Write a js code to find the repeated number.
//e.g $arr = array(0,1,2,3,4,5,6,7,7,8,9,10...................);
let myarry = [1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10];
let myduplicate = arr => arr.filter((item, index) => arr.indexOf(item) != index)
console.log(myduplicate(myarry));
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "a2ca2659137830ed3e9edd94ed43c488",
"url": "/index.html"
},
{
"revision": "6de434bc5f8bf9889572",
"url": "/static/css/main.f263bfb6.chunk.css"
},
{
"revision": "cc5b60f530ec9ef2959d",
"url": "/static/js/2.3dd64d21.chunk.js"
},
{
"revision": "e88a3e95b5364d46e95b35ae8c0dc27d",
"url": "/static/js/2.3dd64d21.chunk.js.LICENSE.txt"
},
{
"revision": "6de434bc5f8bf9889572",
"url": "/static/js/main.d2b872a8.chunk.js"
},
{
"revision": "415e9bcf6c081ea50565",
"url": "/static/js/runtime-main.f8c5b4be.js"
}
]);
|
'use strict';
const VersionAttribute = require('../lib/versionAttribute');
const versionedSuperObject = {
1: {
members: ['iron buddy', 'thorskaar', 'hulksta', 'aunt man', 'queen wasp'],
0: {
members: ['iron buddy', 'thorskaar', 'hulksta', 'aunt man', 'queen wasp'],
1: {
members: ['iron buddy', 'thorskaar', 'hulksta', 'aunt man', 'queen wasp', 'mr america']
}
}
},
2: {
0: {
members: [
'iron buddy',
'thorskaar',
'hulksta',
'aunt man',
'queen wasp',
'mr america',
'hork aye',
'quik sliver',
'red witch'
],
1: {
members: [
'iron buddy',
'thorskaar',
'hulksta',
'aunt man',
'queen wasp',
'mr america',
'hork aye',
'quik sliver',
'red witch',
'the sword'
],
}
}
},
3: {
0: {
otherProperty: 'Altrom hiding',
0: {
members: [
'iron buddy',
'thorskaar',
'hulksta',
'aunt man',
'queen wasp',
'mr america',
'hork aye',
'quik sliver',
'red witch',
'herc'
]
},
1: {
otherProperty: 'Dr. Dom hiding',
1: {}
}
},
1: {
1: {
1: {
otherProperty: 'The Leider hiding'
}
}
}
}
};
const versionedAttribute = new VersionAttribute(versionedSuperObject);
module.exports = {
descendPath: function descendPathTest(test) {
test.expect(5);
test.deepEqual(
versionedAttribute.descendPath([3, 1]),
[3, 1, 1, 1],
'Paths with deep children sure go the entire way.'
);
test.deepEqual(
versionedAttribute.descendPath([2]),
[2, 0, 1],
'Paths at base should go the entire way.'
);
test.deepEqual(
versionedAttribute.descendPath([2, 0, 1]),
[],
'Paths at the deepest level should return an empty array.'
);
test.deepEqual(
versionedAttribute.descendPath([3]),
[3, 1, 1, 1],
'Base paths should move to the deepest level.'
);
test.deepEqual(
versionedAttribute.descendPath([3, 0]),
[3, 0, 1, 1],
'Base paths should move to the deepest level.'
);
test.done();
},
ascendPath: function ascendPathTest(test) {
test.expect(8);
test.deepEqual(
versionedAttribute.ascendPath([3, 0, 1]),
[3, 0, 0],
'Paths at or below target at the targets length should return true.'
);
test.deepEqual(
versionedAttribute.ascendPath([3, 1]),
[3, 0],
'Sub paths of the target should return true.'
);
test.deepEqual(
versionedAttribute.ascendPath([3, 0, 0]),
[3, 0],
'Base paths should go down a level'
);
test.deepEqual(
versionedAttribute.ascendPath([0, 0, 0]),
[],
'Non existant zero paths should return empty.'
);
test.deepEqual(
versionedAttribute.ascendPath([1, 0, 0]),
[1, 0],
'A non existant path should resolve to an existing parent if available.'
);
test.deepEqual(
versionedAttribute.ascendPath([3, 1, 1, 1]),
[3, 1, 1],
'Base paths should go down a level'
);
test.deepEqual(
versionedAttribute.ascendPath([4]),
[3],
'Non existant path at the first level should resolve to next item at first level.'
);
test.deepEqual(
versionedAttribute.ascendPath([1]),
[],
'A final base bath with no sibling above should return empty.'
);
test.done();
},
invalidParams: function invalidParamsTest(test) {
test.expect(23);
test.throws(() => {
new VersionAttribute({}); // eslint-disable-line no-new
}, 'Empty object did not raise exception.');
test.throws(() => {
versionedAttribute.descendPath('');
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.ascendPath('');
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.getPreviousClosestVersion('');
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.getVersionHasTarget('', 'members');
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.getVersion('');
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.getVersionAttribute('', 'members');
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.descendPath([]);
}, 'Empty path did not raise exception');
test.throws(() => {
versionedAttribute.ascendPath([]);
}, 'Empty path did not raise exception');
test.throws(() => {
versionedAttribute.getPreviousClosestVersion([]);
}, 'Empty path did not raise exception');
test.throws(() => {
versionedAttribute.getVersionHasTarget([], 'members');
}, 'Empty path did not raise exception');
test.throws(() => {
versionedAttribute.getVersion([]);
}, 'Empty path did not raise exception');
test.throws(() => {
versionedAttribute.getVersionAttribute([], 'members');
}, 'Empty path did not raise exception');
test.throws(() => {
versionedAttribute.descendPath(['a', 4]);
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.ascendPath(['a', 4]);
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.getPreviousClosestVersion(['a', 4]);
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.getVersionHasTarget(['a', 4], 'members');
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.getVersion(['a', 4]);
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.getVersionAttribute(['a', 4], 'members');
}, 'Incorrect path did not raise exception');
test.throws(() => {
versionedAttribute.getVersionHasTarget([1, 0, 1], '');
}, 'Empty target did not raise exception');
test.throws(() => {
versionedAttribute.getVersionAttribute([1, 0, 1], '');
}, 'Empty target did not raise exception');
test.throws(() => {
versionedAttribute.getVersionHasTarget([], '');
}, 'Empty target did not raise exception');
test.throws(() => {
versionedAttribute.getVersionAttribute([], '');
}, 'Empty target did not raise exception');
test.done();
},
getPreviousClosestVersion: function getPreviousClosestVersionTest(test) {
test.expect(6);
// Empty version returns error.
test.deepEqual(
versionedAttribute.getPreviousClosestVersion([1, 0, 1]),
[1, 0],
'Base paths should go down a level'
);
test.deepEqual(
versionedAttribute.getPreviousClosestVersion([2, 0]),
[1, 0, 1],
'Base paths should go up and then down to get next closest.'
);
// Empty version returns error.
test.deepEqual(
versionedAttribute.getPreviousClosestVersion([3, 1, 1, 1]),
[3, 1, 1],
'Deeply nested paths should traverse upward until they find a matching property.'
);
test.deepEqual(
versionedAttribute.getPreviousClosestVersion([1], versionedSuperObject),
[],
'No property at any path on or above should return empty.'
);
test.deepEqual(
versionedAttribute.getPreviousClosestVersion([2, 0, 17], versionedSuperObject),
[2, 0, 1],
'Non Existant sibling returns correct sibling.'
);
test.deepEqual(
versionedAttribute.getPreviousClosestVersion([4], versionedSuperObject),
[3, 1, 1, 1],
'Non Existant Parent returns correct level.'
);
test.done();
},
getVersionHasTarget: function getVersionHasTargetTest(test) {
test.expect(5);
test.deepEqual(
versionedAttribute.getVersionHasTarget([1, 0, 1], 'members'),
[1, 0, 1],
'Base paths should go down a level'
);
test.deepEqual(
versionedAttribute.getVersionHasTarget([3, 1, 1, 1], 'members'),
[3, 0, 0],
'Deeply nested paths should traverse upward until they find a matching property.'
);
test.deepEqual(
versionedAttribute.getVersionHasTarget([1, 0, 1], 'otherProperty'),
[],
'No property at any path on or above should return empty.'
);
test.deepEqual(
versionedAttribute.getVersionHasTarget([3], 'members'),
[2, 0, 1],
'No property at any path on or above should return empty.'
);
test.deepEqual(
versionedAttribute.getVersionHasTarget([2, 0, 17], 'members'),
[2, 0, 1],
'Non Existant sibling returns correct sibling.'
);
test.done();
},
getVersion: function getVersionTest(test) {
test.expect(5);
test.deepEqual(
versionedAttribute.getVersion([1, 0, 1]),
[1, 0, 1],
'Existing paths should return the same path'
);
test.deepEqual(
versionedAttribute.getVersion([3, 1, 1, 1]),
[3, 1, 1, 1],
'Deeply nested paths should return the same path.'
);
test.deepEqual(
versionedAttribute.getVersion([0]),
[],
'No property at any path on or above should return empty.'
);
test.deepEqual(
versionedAttribute.getVersion([2, 0, 17]),
[2, 0, 1],
'Non Existant sibling returns correct sibling.'
);
test.deepEqual(
versionedAttribute.getVersion([4]),
[3, 1, 1, 1],
'Non Existant Parent returns correct level.'
);
test.done();
},
versionAttribute: function versionAttributeTest(test) {
test.expect(1);
test.deepEqual(
versionedAttribute.getVersionAttribute([1, 0, 1], 'members'),
['iron buddy', 'thorskaar', 'hulksta', 'aunt man', 'queen wasp', 'mr america'],
'Existing paths should return the same path'
);
test.done();
}
};
|
"use strict";
/* global document */
var simpleDice = {
sides: 6,
roll: function () {
var randomNumber = Math.floor(Math.random() * this.sides) + 1;
return randomNumber;
}
};
var diceResult = document.getElementById('diceResult');
var diceButton = document.getElementById('diceButton');
diceButton.addEventListener('click', function () {
var rollDice = simpleDice.roll();
diceResult.innerHTML = rollDice;
});
|
var mandrill = require('mandrill-api/mandrill');
var log = require('./log'),
smtpConfig = require('./smtp.json');
var mandrillClient = new mandrill.Mandrill(smtpConfig.pass);
module.exports = {
send: function(toEmail, toName) {
var message = {
"html": "<p>Example HTML content</p>",
"subject": "Hi Ali",
"from_email": "noreply@group.direct",
"from_name": "GroupDirect",
"to": [{
"email": toEmail,
"name": toName,
"type": "to"
}],
"headers": {
"Reply-To": "noreply@group.direct"
},
"important": false
};
mandrillClient.messages.send({
message: message,
async: 'Async'
});
}
};
|
//Questão 01//
var numeroum = 18;
var numerodois = 15;
if(numeroum>numerodois){
console.log("O valor maior é " + numeroum)
}
else{
console.log("O valor maior é " + numerodois)
}
|
import "./App.css";
import React from "react";
import { getGoogleUid } from "./util";
import CertClient, {clientWithoutAccount} from "./client";
import Login from "./views/Login";
import { IssueComponent } from "./views/Issue";
import { SettingComponent } from "./views/Setting";
import { BrowserRouter as Router, Route, Link, Switch, withRouter } from "react-router-dom";
import { MyPageComponent } from "./views/MyPage";
import { CertViewComponent } from "./views/CertView";
import UserComponent from "./views/User";
import BsModal from "./views/components/BsModal";
import BsExportModal from "./views/components/BsExportModal";
import BsIssueModal from "./views/components/BsIssueModal";
import ModalType from "./modalType";
const UI = {
byId: function(id) {
return document.getElementById(id);
},
showErrorMessage: function(message) {
console.error(message);
},
showMessage: function(message) {
console.log(message);
}
}
class App extends React.Component {
constructor() {
super();
this.myPageRef = React.createRef();
this.state = {
myPageIsLoading: true,
issuePageIsLoading: false,
certificates: [],
message: null,
}
}
closeModal() {
this.setState({
issuePageIsLoading: false,
message: null,
});
}
render() {
const that = this;
console.log(that.props);
let normalModal = "";
const profile = this.props.state.myProfile;
const client = this.props.state.client;
let name = "";
if (client !== null && client.profile !== null) {
name = client.profile.nameInIpfs;
}
let icon = "";
if (profile) {
icon = profile.icon;
}
const login = (
<Login onClick={this.props.loginWithGoogle} />
);
let modal = "";
if (this.props.state.modal === ModalType.EXPORT) {
modal = (
<BsExportModal
seed={this.props.state.client.uid}
exportFile={this.props.exportFile}
copyAccount={this.props.copyAccount}
closeModal={this.props.closeModal}
/>
);
} else if (this.props.state.modal === ModalType.NORMAL) {
modal = (
<BsModal show={true} closeModal={this.props.closeModal} isLoading={this.props.state.isLoading} message={this.props.state.message} errorMessage={this.props.state.errorMessage}/>
);
} else if (this.props.state.modal === ModalType.ISSUE) {
modal = (
<BsIssueModal show={true} closeModal={this.props.closeModal} isLoading={this.props.state.isIssuing} error={this.props.state.issueError}/>
);
}
const main = (
<div className="main">
<header>
<h2 className="brand-logo"><a href="/">GxCert</a></h2>
<Link to="/issue" className="header-issue-button header-button">Issue</Link>
<Link to="/" className="header-show-button header-button">{client !== null && client.profile && client.profile.nameInIpfs ? client.profile.nameInIpfs.substr(0, 6) + "..." : "Profile" }</Link>
</header>
<div className="main">
<Switch>
<Route exact path="/" render={ () => <MyPageComponent
address={client.address}
profile={client.profile}
isLoading={that.props.state.myPageIsLoading}
certificates={that.props.state.certificates}
certificatesIIssued={that.props.state.certificatesIIssued}
getCertificates={that.props.getCertificates}
getCertificatesIIssued={that.props.getCertificatesIIssued}
openExportModal={that.props.openExportModal}
onCopyId={that.props.onCopyId}
getInfoOfCertificates={that.props.getInfoOfCertificates}
getInfoOfCertificatesIIssued={that.props.getInfoOfCertificatesIIssued}
changeTabToIssuer={that.props.changeTabToIssuer}
changeTabToMyCertificates={that.props.changeTabToMyCertificates}
tab={that.props.state.tabInMyPage}
logout={that.props.logout}
/> } />
<Route exact path="/issue" render={ () => <IssueComponent
onClickIssueButton={this.props.issue}
onChangeCertificateImage={this.props.onChangeCertificateImage}
onChangeIssueTo={this.props.onChangeIssueTo}
onChangeTitle={this.props.onChangeTitle}
onChangeDescription={this.props.onChangeDescription}
/> } />
<Route exact path="/user" render={ () => <SettingComponent
onClickUpdateButton={this.props.updateUserSetting}
onChangeName={this.props.onChangeName}
onChangeIcon={this.props.onChangeIcon}
name={name}
/> } />
<Route exact path="/users/:id" render={ (routeProps) => <UserComponent
{ ...routeProps }
profile={that.props.state.profileInUserPage}
fetchProfile={that.props.fetchProfileInUserPage}
imageUrl={that.props.state.iconInUserPage}
name={that.props.state.nameInUserPage}
isLoading={that.props.state.userPageIsLoading}
certificates={that.props.state.certificatesInUserPage}
certificatesIIssued={that.props.state.certificatesIIssuedInUserPage}
getCertificates={that.props.getCertificatesInUserPage}
getCertificatesIIssued={that.props.getCertificatesIIssuedInUserPage}
getInfoOfCertificates={that.props.getInfoOfCertificatesInUserPage}
getInfoOfCertificatesIIssued={that.props.getInfoOfCertificatesIIssuedInUserPage}
changeTabToIssuer={that.props.changeTabInUserPageToIssuer}
changeTabToMyCertificates={that.props.changeTabInUserPageToMyCertificates}
tab={that.props.state.tabInUserPage}
isNotFound={that.props.state.userIsNotFound}
/> } />
<Route exact path="/users/:address/issued/:index" render={ (routeProps) => <CertViewComponent {...routeProps}
certificates={that.props.state.certificatesIIssuedInUserPage}
client={clientWithoutAccount}
getCertificates={that.props.getCertificatesInUserPage}
fromUserPage={true}
/> } />
<Route exact path="/users/:address/certs/:index" render={ (routeProps) => <CertViewComponent {...routeProps}
certificates={that.props.state.certificatesInUserPage}
client={clientWithoutAccount}
getCertificatesIIssued={that.props.getCertificatesIIssuedInUserPage}
fromUserPage={true}
/> } />
<Route exact path="/issued/:index" render={ (routeProps) => <CertViewComponent {...routeProps}
certificates={that.props.state.certificatesIIssued}
client={clientWithoutAccount}
/>} />
<Route exact path="/certs/:index" render={ (routeProps) => <CertViewComponent {...routeProps}
certificates={that.props.state.certificates}
client={clientWithoutAccount}
/>} />
</Switch>
</div>
{ modal }
</div>
);
return (
<div className="App">
{ !this.props.location.pathname.startsWith("/users/") && client === null ? login : main }
<BsModal show={true} closeModal={this.props.closeModal} isLoading={this.props.state.isLoading} message={this.props.state.message} errorMessage={this.props.state.errorMessage}/>
</div>
);
}
}
export default withRouter(App);
|
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import './Pagination.css';
/**
* Component: Navbar
* Props: dataHref
*/
class Pagination extends Component
{
render() {
return(
<ul className="pagination justify-content-center">
<li className="page-item">
<NavLink to={this.props.dataHref} className="page-link">
<span aria-hidden="true">«</span>
<span className="sr-only">Prev</span>
</NavLink>
</li>
<li className="page-item">
<NavLink to={this.props.dataHref} className="page-link">1</NavLink>
</li>
<li className="page-item active">
<NavLink to={this.props.dataHref} className="page-link">2</NavLink>
</li>
<li className="page-item">
<NavLink to={this.props.dataHref} className="page-link">3</NavLink>
</li>
<li className="page-item">
<NavLink to={this.props.dataHref} className="page-link">
<span aria-hidden="true">»</span>
<span className="sr-only">Next</span>
</NavLink>
</li>
</ul>
);
}
}
export default Pagination;
|
import React from "react";
import styled from "styled-components";
const FullRecipe = ({ recipe }) => {
const closeRecipe = () => {
recipe.handleActiveRecipe({});
};
return (
<Wrapper>
<Container>
<Button onClick={closeRecipe}>
<i class="fas fa-times" />
</Button>
<Header image={recipe.image}>{recipe.title}</Header>
<Content>
<ol style={{ textAlign: "left" }}>
{recipe.ingredients.map(ingredient => (
<li>{ingredient.text}</li>
))}
</ol>
</Content>
</Container>
</Wrapper>
);
};
export default FullRecipe;
// Styled Components
const Wrapper = styled.div`
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: 1000;
background: rgba(0, 0, 0, 0.8);
`;
const Container = styled.div`
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 80%;
min-width: 60%;
`;
const Button = styled.button`
background: none;
color: white;
border: none;
font-size: 18pt;
padding: 15px;
border-radius: 12px;
float: right;
cursor: grab;
&:hover {
border-radius: 50%;
background: rgba(0, 0, 0, 0.2);
}
`;
const Header = styled.div`
text-align: center;
float: down;
font-size: 40px;
color: white;
border-radius: 15px 15px 0 0;
width: 100%;
padding: 75px 0;
background-position: center;
background-repeat: no-repeat;
background: linear-gradient(to top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
url(${props => props.image});
`;
const Content = styled.div`
padding: 35px;
border-radius: 0 0 15px 15px;
background: white;
`;
|
import SpecialForm from './specialForm';
export default SpecialForm;
|
export class FreshnessValueConverter {
toView(value) {
var age = (new Date() - value)/1000;
if (Math.floor(age) > 10) return "red";
if (Math.floor(age) > 5) return "yellow";
return "white";
}
}
|
import React from 'react';
import '../../../assets/styles.css'
class First extends React.Component {
render() {
return (
<center>
<h1>I <span id='atom'>⚛</span> React.
<br/>An introduction.<br/><br/></h1>
</center>
);
}
}
export default First;
|
import React from "react";
import { Layout, PageHeader } from "antd";
import { Link } from "react-router-dom";
import Sidebar from "../../components/sidebar/Sidebar";
import SeeCard from "../../components/cards/card-see-all/SeeCard";
import './SeeAllSafe.scss'
import ArrowLeft from "../../assets/icons/arrow-left.png";
const SeeAllSafe = () => {
const { Sider, Content } = Layout;
return (
<div>
<Layout>
<Sider theme="light" width={326} className="sidebar">
<Sidebar />
</Sider>
<Layout>
<PageHeader>
<div className="header-detail">
<Link to="/my-profile">
<img src={ArrowLeft} alt="back" />
</Link>
<h2 style={{ fontWeight: "bold" }}>See All Safe</h2>
</div>
</PageHeader>
<Content>
<SeeCard />
</Content>
</Layout>
</Layout>
</div>
);
};
export default SeeAllSafe;
|
module.exports = {
port: 5000,
mongo: {
url: 'mongodb://localhost:27017/rueppellii'
}
};
|
/**
* First subscriber to btc price provider
* Listen to both ipfs and query dispatcher
*/
async function bondDots(){
}
async function subscribe(){
}
|
$(document).ready(function() {
$("#nav-btn").click(function() {
$("#nav-menu").fadeToggle();
});
$('#nav-menu li a').click(function() {
$('#nav-menu').hide();
});
});
$(document).ready(function() {
$("#back-top").hide();
$(function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('#back-top').fadeIn();
} else {
$('#back-top').fadeOut();
}
});
$('#back-top a').click(function() {
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});
});
$(document).ready(function() {
$("a").click(function(e) {
var target = $(this).attr('href') ;
if(target.charAt(0)=='#')
{
e.preventDefault();
$('html, body').animate({
scrollTop: $(target).offset().top
}, 1000);
}
})
$('html, body').animate({
scrollTop: 0
}, 1000);
});
|
import * as React from "react";
import Hero from "../components/Hero";
import PageLayout from "../components/PageLayout";
import Footer from "../components/Footer";
import { Link, graphql, StaticQuery } from "gatsby";
function CategoryTitle({ children }) {
return <h2 className="font-black text-gray-500 text-md">{children}</h2>;
}
function CategoryArticleList({ children }) {
return (
<div className="grid sm:grid-cols-2 md:grid-cols-3 gap-4 mb-12 mt-4">
{children}
</div>
);
}
function CategoryArticle({ frontmatter: { blurb, title }, slug }) {
return (
<Link className="block" to={`/article/${slug}`}>
<h3 className="font-black text-blue-500 text-lg underline">{title}</h3>
<p>{blurb}</p>
</Link>
);
}
export default function IndexPage() {
return (
<PageLayout>
<Hero />
</PageLayout>
);
}
|
/**
* Created by Administrator on 2016/5/23.
*/
// JavaScript Document
// Date: 2014-11-07
// Author: Agnes Xu
i = 0;
j = 0;
count = 0;
MM = 0;
SS = 90; // 秒 90s
MS = 0;
totle = (MM+1)*900;
d = 180*(MM+1);
MM = "0" + MM;
var gameTime = $("#qiangdanTime").val();
//count down
var showTime = function(){
totle = totle - 1;
if (totle == 0) {
alert("完毕");
clearInterval(s);
clearInterval(t1);
isNotAutoPaiDan();
//如果倒计时结束,还没有人抢单的话,那么就自动派单
// clearInterval(t2);
// $(".pie2").css("-o-transform", "rotate(" + d + "deg)");
// $(".pie2").css("-moz-transform", "rotate(" + d + "deg)");
//$(".pie2").css("-webkit-transform", "rotate(" + d + "deg)");
} else {
if (totle > 0 && MS > 0) {
MS = MS - 1;
if (MS < 10) {
MS = "0" + MS
}
;
}
;
if (MS == 0 && SS > 0) {
MS = 10;
SS = SS - 1;
if (SS < 10) {
SS = "0" + SS
}
;
}
;
if (SS == 0 && MM > 0) {
SS = 90;
MM = MM - 1;
if (MM < 10) {
MM = "0" + MM
}
;
}
;
}
;
$(".time").html(SS + "s");
};
var start1 = function(){
//i = i + 0.6;
i = i + 360/((gameTime)*10); //旋转的角度 90s 为 0.4 60s为0.6
count = count + 1;
if(count <= (gameTime/2*10)){ // 一半的角度 90s 为 450
$(".pie1").css("-o-transform","rotate(" + i + "deg)");
$(".pie1").css("-moz-transform","rotate(" + i + "deg)");
$(".pie1").css("-webkit-transform","rotate(" + i + "deg)");
}else{
$(".pie2").css("backgroundColor", "#d13c36");
$(".pie2").css("-o-transform","rotate(" + i + "deg)");
$(".pie2").css("-moz-transform","rotate(" + i + "deg)");
$(".pie2").css("-webkit-transform","rotate(" + i + "deg)");
}
};
var start2 = function(){
j = j + 0.6;
count = count + 1;
if (count == 300) {
count = 0;
clearInterval(t2);
t1 = setInterval("start1()", 100);
}
$(".pie2").css("-o-transform","rotate(" + j + "deg)");
$(".pie2").css("-moz-transform","rotate(" + j + "deg)");
$(".pie2").css("-webkit-transform","rotate(" + j + "deg)");
}
var countDown = function() {
//80*80px 时间进度条
i = 0;
j = 0;
count = 0;
MM = 0;
SS = gameTime;
MS = 0;
totle = (MM + 1) * gameTime * 10;
d = 180 * (MM + 1);
MM = "0" + MM;
showTime();
s = setInterval("showTime()", 100);
start1();
//start2();
t1 = setInterval("start1()", 100);
//t2 = setInterval("start2()", 100);
}
function isNotAutoPaiDan(){
var id=$("#orderId").val();
$.ajax({
url : '/qiangdan/timeover.html',
type : 'POST',
async : false,
dataType : 'json',
data : {
id :id
},
success : function(r) {
//自动派单成功,不做任何操作
},error:function(){
alert("操作一次");
}
});
}
|
import React, { useState } from "react";
import a from "./../images/illustration-features-tab-1.svg";
import b from "./../images/illustration-features-tab-2.svg";
import c from "./../images/illustration-features-tab-3.svg";
import "./index.css";
const Feature = () => {
const [list, setlist] = useState(0);
const [aa, setaa] = useState("br");
const [bb, setbb] = useState(0);
const [cc, setcc] = useState(0);
return (
<div className="feature">
<div className="f-1">
<h1>Features</h1>
<p>
Our aim is to make it quick and easy for you to access your favourite
websites. Your bookmarks sync between your devices so you can access
them on the go.
</p>
</div>
<div className="list">
<div className="tp-1">
<ul>
<li
onClick={() => {
setlist(0);
setaa("br");
setbb("");
setcc("");
}}
className={aa}
>
Simple Bookmarking
</li>
<li
onClick={() => {
setlist(1);
setaa("");
setbb("br");
setcc("");
}}
className={bb}
>
Speedy Searching
</li>
<li
onClick={() => {
setlist(2);
setaa("");
setbb("");
setcc("br");
}}
className={cc}
>
Easy Sharing
</li>
</ul>
</div>
<div className="glb">
{list === 0 ? (
<div className="tab">
<div className="imgL">
<img src={a} alt="" />
</div>
<div className="aL">
<h1>Bookmark in one click</h1>
<p>
Organize your bookmarks however you like. Our simple
drag-and-drop interface gives you complete control over how
you manage your favourite sites.
</p>
<button>More Info</button>
</div>
</div>
) : list === 1 ? (
<div className="tab">
<div className="imgL">
<img src={b} alt="" />
</div>
<div className="aL">
<h1>Simple Bookmarking</h1>
<p>
Speedy Searching Easy Sharing Intelligent search Our powerful
search feature will help you find saved sites in no time at
all. No need to trawl through all of your bookmarks.
</p>
<button>More Info</button>
</div>
</div>
) : list === 2 ? (
<div className="tab">
<div className="imgL">
<img src={c} alt="" />
</div>
<div className="aL">
<h1>Simple Bookmarking</h1>
<p>
{" "}
Speedy Searching Easy Sharing Share your bookmarks Easily
share your bookmarks and collections with others. Create a
shareable link that you can send at the click of a button.
</p>
<button>More Info</button>
</div>
</div>
) : (
""
)}
</div>
</div>
<div className="bluebox2"></div>
</div>
);
};
export default Feature;
|
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('Videos', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
key: {
type: Sequelize.STRING(4096)
},
thumbnail_key: {
type: Sequelize.STRING(4096)
},
original_key: {
type: Sequelize.STRING(4096)
},
caption: {
type: Sequelize.STRING
},
status: {
type: Sequelize.ENUM({
values: ['approved', 'denied', 'pending', 'suspended', 'processing', 'manual', 'reserved']
})
},
access_level: {
type: Sequelize.ENUM({
values: ['public', 'followers', 'private', 'friends']
})
},
format: {
type: Sequelize.ENUM({
values: ['mp4', 'avi', 'mov']
})
},
duration: {
type: Sequelize.INTEGER
},
height: {
type: Sequelize.STRING(45)
},
width: {
type: Sequelize.STRING(45)
},
creator_id: {
type: Sequelize.INTEGER
},
copyright: {
type: Sequelize.ENUM({
values: ['user_generated', 'inhouse_produced', 'acquired', 'public', 'licensed']
})
},
badge: {
type: Sequelize.ENUM({
values: ['featured', 'demo', 'ad']
})
},
geo: {
type: Sequelize.STRING
},
comments_count: {
type: Sequelize.INTEGER
},
likes_count: {
type: Sequelize.INTEGER
},
views_count: {
type: Sequelize.INTEGER
},
deleted_at: {
type: Sequelize.DATE(5)
},
inserted_at: {
allowNull: false,
type: Sequelize.DATE(5),
defaultValue: Sequelize.NOW
},
updated_at: {
allowNull: false,
type: Sequelize.DATE(5),
defaultValue: Sequelize.NOW,
onUpdate : Sequelize.NOW
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('Videos');
}
};
|
import React from "react";
import MessageCard from "../components/chat/MessageCard";
import { useSelector, useDispatch } from "react-redux";
import ChatInput from "../components/chat/ChatInput";
import { getChat } from "../components/chat/Actions";
import "../components/chat/Chat.css";
export default function ChatList(props) {
const dispatch = useDispatch();
const chat = useSelector(
state =>
state.chatReducer.chats &&
state.chatReducer.chats.find(c => c._id === props.match.params.id)
);
if (chat === undefined) {
dispatch(() => getChat(props.match.params.id));
return <div>Loading</div>;
}
const listItems = chat.messages.map(listItem => {
return (
<MessageCard
creationDate={listItem.creationDate}
name={listItem.text}
key={listItem._id}
/>
);
});
return (
<div className="chat-list_container">
<ul>{listItems}</ul>
<ChatInput id={props.match.params.id} />
</div>
);
}
|
$(document).ready(function() {
var content = $("div.content");
var contentbox = $("div.contentbox");
var sidebar = $("div.sidebar");
resizeWindow(null);
$(window).bind("resize", resizeWindow);
function resizeWindow( e ) {
var width = contentbox.outerWidth();
var offset = contentbox.offset();
var left = (offset.left+width)+'px';
sidebar.css({
'position' : "absolute",
'left' : left + 20,
'display' : 'inline-block',
'width' : '160px',
'opacity' : 1
});
}
ajaxLoad("about");
function ajaxLoad(input){
content.fadeOut("medium",function() {
$.ajax({url: "ajax_pages/"+input+".html",
type: "GET",
dataType: "html",
success: function(result){
content.html(result);
$('#gallery1').galleryView({
panel_width: 750,
panel_height: 490,
show_filmstrip_nav: false
});
$('#gallery2').galleryView({
panel_width: 275,
panel_height: 489,
show_filmstrip_nav: false
});
$('#gallery3').galleryView({
panel_width: 275,
panel_height: 275,
show_filmstrip_nav: false
});
$('#gallery4').galleryView({
panel_width: 275,
panel_height: 489,
show_filmstrip_nav: false
});
},
complete: function(){
content.fadeIn("medium");
}
})
});
};
$("#about").click(function () {
ajaxLoad("about");
});
$("#projects").click(function() {
ajaxLoad("projects");
});
$("#resume").click(function() {
ajaxLoad("resume");
});
});
|
var timer;
function startimer(speed){
timer = window.setInterval(changeNum,speed);
}
startimer(100);
var images=document.getElementById('images');
console.log(images1);
console.log(images2);
console.log(images2.children[3]);
var currentNo=0;
function changeNum()
{
h2obj.textContent=currentNo;
if(currentNo<8) currentNo++;
else currentNo=0;
h2obj.textContent=currentNo;
}
var btnObj =document.getElementById('btnOjb')
function startChange()
{
startimer(500);
btnObj.textContent="停止";
}
function stopChange(){
window.clearInterval(timer);
btnObj.textContent="启动"
}
btnObj.addEventListener('mouseover',stopChange);
btnObj.addEventListener('mouseout',startChange);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.