text
stringlengths 7
3.69M
|
|---|
const fs = require('fs')
arguments = process.argv.splice(2)
// transform is just a helper function to process the word,
// To make the code more readable, I keep it outside.
const transform = require('./helper').transform
function extract_words(path_to_file) {
let me = this
me['_data'] = fs.readFileSync(path_to_file, 'utf8')
me['_data'] = me['_data'].replace(/[^a-zA-Z]/g," ")
let words = me['_data'].split(" ")
let wordsDcit = []
for (let i = 0; i < words.length; i++) {
let w = transform(words[i])
if (w.length > 1) wordsDcit.push(w)
}
me['_data'] = wordsDcit
}
function words() {
let me = this
return me['_data']
}
function load_stop_words() {
let me = this
let stop_words = fs.readFileSync('../stop_words.txt', 'utf8')
stop_words = stop_words.split(",")
for (let i = 0; i < stop_words.length; i++) {
me['_stop_words_set'].add(stop_words[i])
}
}
function is_stop_word(w) {
let me = this
return me['_stop_words_set'].has(w)
}
function increment_count(w) {
let me = this
if (!me['_word_freqs'].has(w)) me['_word_freqs'].set(w, 1)
else me['_word_freqs'].set(w, me['_word_freqs'].get(w) + 1)
}
function sorted() {
let me = this
let res = []
let i = 0
me['_word_freqs'].forEach((val, key) => {
res[i] = {key, val}
i++
})
res.sort((a, b) => {
return b.val - a.val
})
return res
}
function top25() {
let me = this
let word_freqs = me['sorted'].call(me)
for (let i = 0; i < 25; i++) {
let w = word_freqs[i]
console.log(w.key + " - " + w.val)
}
}
let data_storage_obj = {
'_data' : [],
'init' : extract_words,
'words' : words
}
let stop_words_obj = {
'_stop_words_set' : new Set(),
'init' : load_stop_words,
'is_stop_word' : is_stop_word
}
let word_freqs_obj = {
'_word_freqs' : new Map(),
'increment_count' : increment_count,
'sorted' : sorted,
'top25' : top25
}
data_storage_obj['init'].call(data_storage_obj, arguments[0])
stop_words_obj['init'].call(stop_words_obj)
let ws = data_storage_obj['words'].call(data_storage_obj)
for (let i = 0; i < ws.length; i++) {
if (!stop_words_obj['is_stop_word'].call(stop_words_obj, ws[i])) {
word_freqs_obj['increment_count'].call(word_freqs_obj, ws[i])
}
}
word_freqs_obj['top25'].call(word_freqs_obj)
|
import React from 'react';
import Header from '../sections/header/Header';
import Wrapper from '../sections/wrapper/Wrapper';
import About from '../sections/about/About';
import Skills from '../sections/skills/Skills';
// import Experience from '../sections/experience/Experience';
// import Education from '../sections/education/Education';
// import Projects from '../sections/projects/Projects';
import Contact from '../sections/contact/Contact';
class HomePage extends React.Component {
state = {};
render() {
return (
<div>
<Header>
<Wrapper>
<About />
<Skills />
</Wrapper>
{/* <Wrapper color="#2f4152">
<Projects />
</Wrapper> */}
<Wrapper color="#f2f3f3">
<Contact />
</Wrapper>
</Header>
</div>
);
}
}
export default HomePage;
|
function aestheticise_text(text_in) {
return text_in.split(" ").map(word => word.split("").join(" ")).join(" ")
}
function aestheticise() {
message = $("#aes-input")[0].value || "This is some aesthetic text"
message = aestheticise_text(message)
$("#aes-output")[0].innerHTML = message
}
$("#aes-submit").click(function(e) {
e.preventDefault()
aestheticise()
})
$(document).ready(function() {
aestheticise()
})
|
// pages/habit/group/export.js
var wegrouplib = require('../../common/lib/wegrouplib')
var util = require('../../../utils/util')
var app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
picker_start_day: '',
picker_end_day: '',
start_day: '',
end_day: '',
error: {
msg: "",
show: true
},
disabled: false,
export_status: 0,
tasks: {},
is_creator: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var group_id = options.group_id;
this.setData({
isSetClipboardData: wx.setClipboardData ? true : false,
group_id: group_id
})
util.showLoading('加载中')
var that = this
app.getUserInfo(function (userInfo, setting) {
//更新数据
that.setData({
userInfo: userInfo
})
that.getGroup()
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
bindStartDayChange: function (e) {
this.setData({
start_day: e.detail.value
})
},
bindEndDayChange: function (e) {
this.setData({
end_day: e.detail.value
})
},
bindSetClipboardDataTap: function (e) {
if (wx.setClipboardData) {
wx.setClipboardData({
data: this.data.tasks.fileurl,
success: function (res) {
util.showSuccess('复制成功')
}
})
}
},
bindPreviewFileTap: function (e) {
wx.downloadFile({
url: this.data.tasks.fileurl,
success: function (res) {
var filePath = res.tempFilePath
wx.openDocument({
filePath: filePath,
//fileType:'csv',
success: function (res) {
console.log(filePath, res, '打开文档成功')
}
})
}
})
},
bindExportTap: function (e) {
util.showLoading('导出中')
this.setData({
disabled: true
})
var params = {
group_id: this.data.group_id,
start_day: this.data.start_day,
end_day: this.data.end_day
}
var that = this
wegrouplib.exportGroup(params, function (code, msg, data) {
if (code == 0) {
util.hideLoading()
if (data.tasks.daka_counter > 0) {
that.setData({
export_status: 1,
tasks: data.tasks
})
} else {
wx.showModal({
title: '提示',
content: '当前无打卡数据,请更换时间',
showCancel: false,
success: function (res) {
that.setData({
export_status: 0,
disabled: false
})
}
})
}
} else {
that.showError(msg)
}
})
},
getGroup: function () {
var that = this
var group_id = that.data.group_id
var group = wegrouplib.getLocalGroup(group_id)
var d = new Date()
var end_day = d.getFullYear() + '-' + ((d.getMonth() + 1) < 10 ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1)) + "-" + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate())
var sd = new Date(new Date() - 24 * 3600 * 1000)
var start_day = sd.getFullYear() + '-' + ((sd.getMonth() + 1) < 10 ? "0" + (sd.getMonth() + 1) : (sd.getMonth() + 1)) + "-" + (sd.getDate() < 10 ? "0" + sd.getDate() : sd.getDate())
var cd = new Date(group.create_time * 1000)
var create_day = cd.getFullYear() + '-' + ((cd.getMonth() + 1) < 10 ? "0" + (cd.getMonth() + 1) : (cd.getMonth() + 1)) + "-" + (cd.getDate() < 10 ? "0" + cd.getDate() : cd.getDate())
// from cache
console.log(create_day, start_day, end_day)
if (group) {
this.setData({
group: group,
start_day: start_day,
end_day: end_day,
picker_start_day: create_day,
picker_end_day: end_day,
is_creator: group.creator == that.data.userInfo.id ? true : false,
})
}
util.hideLoading()
},
showError: function (msg) {
util.hideLoading()
var that = this
this.setData({
export_status: 0,
error: {
show: false,
msg: "错误提示:" + msg
},
disabled: false
})
setTimeout(function () {
that.setData({
error: {
show: true,
msg: "错误提示"
}
})
}, 2000)
}
})
|
import React from 'react';
import HeaderTabs from './../components/HeaderTabs';
import HeaderTitle from './../components/HeaderTitle';
export default function HeaderContainer(props) {
return (
<div>
<HeaderTitle />
<HeaderTabs changeView={props.changeView} />
</div>
)
}
|
for (var i = 0; i < 12; i++) {
var s = "Item " + (i + 1);
debugger;
console.log(s);
}
|
var $define = {};
$define.u = {};
$define.u.Mobile = (navigator.userAgent.match(/Android|iPhone|SymbianOS|Windows Phone|iPad|iPod|MQQBrowser/i) && navigator.userAgent.indexOf("Windows NT") == -1) ? true : false;
$define.api = {};
console.log(navigator.userAgent);
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubeIframeAPIReady(){ $define.api.Youtube = true; }
/* PAGE Change */
$(window).resize(function() {
var wh = $(window).height();
$('.page-layout:not(.active):not([data-h])').each(function(){
if($(this).css('top')>0)
$(this).css('transition', 'all 0s ease').css('top', wh);
else
$(this).css('transition', 'all 0s ease').css('top', -wh);
});
});
$("body").on("click", "a[data-target]", function(e){
e.preventDefault();
e.stopPropagation();
return false;
}).on("tap", "a[data-target]:not(.active)", function(e){
var a = $('.page-layout.active'),
t = $($(this).attr("data-target"));
if(a.css('top')!='0px') return false;
a.removeClass('active').css('top', 0-parseInt(t.css('top')));
if(a.attr('data-h')) a.css('top', 0);
t.css('transition', 'all 1s ease').addClass('active').css('top', '0%');
$(".page-scroll.active").removeClass('active');
$(".page-scroll[data-target='"+$(this).attr("data-target")+"']", t).addClass('active');
PageAnimation(t);
});
/* PAGE Animation Function */
var $s = {
st: 'style',
ts: 'transition'
}, $v = {
ae: 'all 1s ease',
una: 'all 0s ease'
}
function initAnimation(panel){
$('[data-animation-type="width"]', panel).css($s.ts, $v.una).css('width', '0%');
$('[data-animation-type="height"]', panel).css($s.ts, $v.una).css('height', '0%');
$('[data-animation-type="half-height"]', panel).css($s.ts, $v.una).css('height', '0%');
$('[data-animation-type="opacity"]', panel).css($s.ts, $v.una).css('opacity', '0');
$('[data-animation-css]', panel).css($s.ts, $s.ae).css('opacity', '0');
setTimeout(function(){
if(!$define.u.Mobile) $('[id^=collapse]', panel).removeAttr($s.st).animateCss("fadeInDown");
$('[data-animation-type="width"]', panel).css($s.ts, $v.ae).css('width', '100%');
$('[data-animation-type="height"]', panel).css($s.ts, $v.ae).css('height', '100%');
$('[data-animation-type="half-height"]', panel).css($s.ts, $v.ae).css('height', '50%');
$('[data-animation-type="opacity"]', panel).css($s.ts, $v.ae).css('opacity', '1');
$('[data-animation-css]', panel).each(function(){
var self = $(this);
if($(this).attr('data-animation-delay'))
setTimeout(function(){ self.removeAttr($s.st).animateCss(self.attr('data-animation-css')); }, parseInt(self.attr('data-animation-delay')));
else
self.removeAttr($s.st).animateCss(self.attr('data-animation-css'));
});
}, 100);
}
function PageAnimation(panel, delaytime=600){
$('[id^=collapse]', panel).addClass("in");
$('[data-animation-type="width"]', panel).css($s.ts, $v.una).css('width', '0%');
$('[data-animation-type="height"]', panel).css($s.ts, $v.una).css('height', '0%');
$('[data-animation-type="half-height"]', panel).css($s.ts, $v.una).css('height', '0%');
$('[data-animation-type="opacity"]', panel).css($s.ts, $v.una).css('opacity', '0');
$('[data-animation-css]', panel).css($s.ts, $v.una).css('opacity', '0');
$('[data-animation-one]', panel).css($s.ts, $v.una).css('opacity', '0');
setTimeout(function(){
if(!$define.u.Mobile) $('[id^=collapse]', panel).removeAttr($s.st).animateCss("fadeInDown");
$('[data-animation-type="width"]', panel).css($s.ts, $v.ae).css('width', '100%');
$('[data-animation-type="height"]', panel).css($s.ts, $v.ae).css('height', '100%');
$('[data-animation-type="half-height"]', panel).css($s.ts, $v.ae).css('height', '50%');
$('[data-animation-type="opacity"]', panel).css($s.ts, $v.ae).css('opacity', '1');
$('[data-animation-css]', panel).each(function(){
var self = $(this);
if($(this).attr('data-animation-delay'))
setTimeout(function(){ self.removeAttr($s.st).animateCss(self.attr('data-animation-css')); }, parseInt(self.attr('data-animation-delay')));
else
self.removeAttr($s.st).animateCss(self.attr('data-animation-css'));
});
setTimeout(function(){ $('[data-animation-one]:nth-child(odd)', panel).removeAttr($s.st).css('opacity', '1'); }, 500);
setTimeout(function(){ $('[data-animation-one]:nth-child(even)', panel).removeAttr($s.st).css('opacity', '1'); }, 1000);
}, delaytime);
}
/* Animate Function */
$.fn.extend({
animateCss: function (animationName, callback) {
var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
var animationEvents = 'fadeOutUp fadeInDown'
this.removeClass('animated ' + animationEvents).addClass('animated ' + animationName).one(animationEnd, function() {
$(this).removeClass('animated ' + animationName);
if (callback) {
callback();
}
});
return this;
}
});
|
import React from "react";
import MoviesList from "../../Movies/MoviesList";
import Filters from "../../Filters/Filters";
class MoviesPage extends React.Component {
constructor() {
super();
this.initialState = {
filters: {
sort_by: "popularity.desc",
primary_release_year: null,
genres: [],
},
page: 1,
total_pages: null,
};
this.state = this.initialState;
}
onChangeFilters = (event) => {
const newFilters = {
...this.state.filters,
[event.target.name]: event.target.value,
};
this.setState({
filters: newFilters,
});
};
onChangePage = (page) => {
this.setState({
page: page,
});
};
getTotalPages = (total_pages) => {
this.setState({
total_pages,
});
};
resetFilters = (event) => {
this.setState(this.initialState);
};
render() {
const { filters, page, total_pages } = this.state;
return (
<div className="container">
<div className="row">
<div className="col-4 mt-4">
<div className="card" style={{ width: "100%" }}>
<div className="card-body">
<h3>Фильтры:</h3>
<Filters
onChangeFilters={this.onChangeFilters}
filters={filters}
page={page}
total_pages={total_pages}
onChangePage={this.onChangePage}
resetFilters={this.resetFilters}
/>
</div>
</div>
</div>
<div className="col-8 mt-4">
<MoviesList
filters={filters}
page={page}
onChangePage={this.onChangePage}
getTotalPages={this.getTotalPages}
/>
</div>
</div>
</div>
);
}
}
export default MoviesPage;
|
const dbpool = require("../config/dbconfig"); //dbpool
// const userModel = require("../dao/userdao");
const filecontroller = {
};
module.exports = filecontroller;
|
/**
* Created by Administrator on 2016/8/17.
*/
// 隔1s检查一次合成进度
function check_progress(ret, base_url) {
var btn_synthesis = $('#synthesis-btn');
var span_warning = $('#warning');
var span_audio = $('#audio');
if (ret.retCode != '000000') {
span_warning.text(ret.retMsg);
span_warning.show();
btn_synthesis.text("合成");
btn_synthesis.removeAttr("disabled");
return;
} else {
var chk_progress = setInterval(function () {
var progress_url = base_url + '/qry_progress';
$.getJSON(progress_url, function (ret_data) {
if ('000000' === ret_data.retCode) {
// 显示进度条
$('#progress-parent').show();
var div_progress = $('#progress');
var percent = ret_data.synthPercent;
div_progress.attr("aria-valuenow", percent);
div_progress.css("width", percent + '%');
div_progress.text(percent + '%');
var ret_url = ret_data.tempWorksUrl;
if (ret_url != null) {
var div_ret_url = $('#ret-url');
div_ret_url.html('<a target="_blank" href="' + ret_url + '">' + ret_url + '</a>');
// 试听
span_audio.html(
'<span class="musicControl" class="media-object">' +
'<a style="cursor: pointer" class="stop" onclick="play_music(this);">' +
'<audio loop="">' +
'<source src="' + ret_url + '" type="audio/mpeg">' +
'</audio></a></span>'
);
// 显示试听
$('#audition').show();
clearInterval(chk_progress);
btn_synthesis.text("合成");
btn_synthesis.removeAttr("disabled");
}
} else {
$('#warning').text(ret_data.retMsg);
clearInterval(chk_progress);
btn_synthesis.text("合成");
btn_synthesis.removeAttr("disabled");
return;
}
});
}, 1000);
}
}
function word_count(maxCount, textarea, span) {
var count = maxCount - $('#' + textarea).val().length;
var count_text = count + '/' + maxCount;
$('#' + span).text(count_text);
}
// 检查输入是否为空
function isBlank(val) {
return val.replace(/(^\s*)|(\s*$)/g, "") == '';
}
//播放按钮
function play_music(i) {
var e = $(i);
if (e.hasClass('on')) {
e.find('audio').get(0).pause();
e.attr('class', 'stop');
} else {
e.find('audio').get(0).play();
e.attr('class', 'on');
}
}
|
import * as types from './constants';
const initialState = {
message: '',
status: false,
loading: false,
showPlanner: false
};
const TalkToAhwanamReducer = (state = initialState, action) => {
switch (action.type) {
case types.POST_FORMDATA:
return {
...state,
message: '',
loading: true,
status:null
};
case types.POST_FORMDATA_SUCCESS:
return {
...state,
status: true,
loading: false
};
case types.POST_FORMDATA_FAILURE:
return {
...state,
status: false,
message: action.error.message,
loading: false
};
case types.CLEAR_TALKTO_ERRORS:
return {
...state,
loading: false,
error: null,
message: '',
status: null
};
case types.SHOW_PLANNER:
return {
...state,
showPlanner: true
};
case types.HIDE_PLANNER:
return {
...state,
showPlanner: false
};
default:
return state;
}
};
export default TalkToAhwanamReducer;
|
import React, { Component } from 'react';
import PartyInvitation from './PartyInvitation';
export default class App extends Component {
render() {
return (
<div>
<PartyInvitation />
</div>
);
}
}
|
app.controller('TestAppController', function (MyService, $scope) {
//tabs start
$scope.tabs = [{
title: 'Pie Chart',
url: 'pie.tpl.html'
}, {
title: 'table',
url: 'table.tpl.html'
}];
$scope.currentTab = 'pie.tpl.html';
$scope.onClickTab = function (tab) {
$scope.currentTab = tab.url;
}
$scope.isActiveTab = function (tabUrl) {
return tabUrl == $scope.currentTab;
}
//tabs end
//pie start
MyService.getPie().then(function (d) {
$scope.labels = [];
$scope.data = [];
angular.forEach(d.data.geo, function (value, key) {
$scope.labels.push(value.country);
$scope.data.push(value.count);
});
});
//pie end
//table start
MyService.getTable().then(function (d) {
$scope.tableData = d.data;
});
//table end
});
|
const SHSCoinCrowdsale = artifacts.require("./SHSCoinCrowdSale.sol")
moudule.exports = function(deployer, network, accounts) {
//const startTime = web3.eth.getBlock(web3.eth.blockNumber).timestamp + 5
//const endTime = startTime + (86400 * 20)
const rate = new web3.BigNumber(1000)
const wallet = accounts[0]
deployer.deploy(SHSCoinCrowdsale, rate, wallet)
};
|
import React from 'react';
import ResetPasswordForm from '../containers/ResetPassword';
const ResetPassword = ({ ...props }) => (
<ResetPasswordForm {...props} />
);
export default ResetPassword;
|
(function() {
// 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释
var imports = [
'rd.controls.Module', 'rd.services.PopupService', 'base/module-controller'
];
var extraModules = [ ];
var controllerDefination = ['$scope', 'PopupService', main];
function main(scope, PopupService) {
var moduleID;
scope.load = function(){
var sampleDiv =
'<div controller="SampleModuleController" caption="弹出框标题" icon="<i class=\'fa fa-windows\'></i>" style="border:1px solid red; margin:6px; padding:6px">\
<p>这是模块的初始化数据:{{myData}}</p>\
<p>这是模块控制预定义的数据:{{someData}}</p>\
<button ng-click="destroyHandler()">确认</button>\
</div>';
var initData = {myData: 'load module manually...'};
moduleID = PopupService.popup(sampleDiv, initData);
}
}
var controllerName = 'DemoController';
//==========================================================================
// 从这里开始的代码、注释请不要随意修改
//==========================================================================
define(/*fix-from*/application.import(imports)/*fix-to*/, start);
function start() {
application.initImports(imports, arguments);
rdk.$injectDependency(application.getComponents(extraModules, imports));
rdk.$ngModule.controller(controllerName, controllerDefination);
}
})();
|
$(document).ready(function(){
$("#barre").click(function(){
$("#sandwich").toggle();
});
});
|
const APIError = require('../lib/errors/api.error');
const errorDictionaries = require('../lib/errors/dictionaries');
module.exports = (App) => {
App.error = {
dictionaries: errorDictionaries,
APIError
};
};
|
var express = require('express');
var router = express.Router();
var models = require('../../models');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
// **********************************
//登录接口
router.post('/login', function (req, res, next) {
var username = req.body.username
var password = req.body.password
if (!username || !password) {
res.json({success: false, message: '用户名或密码错误!'})
return;
}
models.User.findOne({
where: {
username: username,
}
}).then(user => {
if (!user) {
res.json({success: false, message: '用户名不存在!'})
return;
}
if(!bcrypt.compareSync(password, user.password)){
res.json({success: false, message: '密码错误!'})
return;
}
var token = jwt.sign({
user:{
id: user.id,
username: username,
admin: true
}
}, process.env.SECRET, {expiresIn: 60 * 60 * 24 * 7});
res.json({
success: true,
message: '请求成功',
token: token
})
})
});
//注册
router.post('/register', function (req, res, next) {
var username = req.body.username
var password = req.body.password
var check_password = req.body.check_password
if (!username || !password) {
res.json({success: false, message: '用户名或密码必填!'})
return;
}
if(check_password != password){
res.json({success: false, message: '两次密码输入不一致!'})
return;
}
models.User.findOne({
where: {
username: username,
}
}).then(user => {
if (user) {
res.json({success: false, message: '用户名已注册!'})
return;
}
password = bcrypt.hashSync(password, 8);
// res.json({password: password})
models.User.create({
username: username,
password: password,
}).then((user) => {
res.json({
success: true,
message: '请求成功',
user: user,
username:username,
})
});
})
});
module.exports = router
|
import PropTypes from "prop-types";
export const dayMap = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday"
};
export const monthMap = {
0: "January",
1: "February",
2: "March",
3: "April",
4: "May",
5: "June",
6: "July",
7: "August",
8: "September",
9: "October",
10: "November",
11: "December"
};
export const FeedStruct = {
actor: PropTypes.string,
created_at: PropTypes.string,
id: PropTypes.number,
object: PropTypes.string,
updated_at: PropTypes.string,
verb: PropTypes.string
};
export const feedsLabelMap = {
all: "",
shared: "Shared",
posted: "Posted"
};
|
import React from "react";
import { withRouter, Link } from "react-router-dom";
import { connect } from "react-redux";
import { ReactComponent as DashIcon } from "../assets/svg/dashboard.svg";
import { ReactComponent as PersonIcon } from "../assets/svg/people.svg";
import { ReactComponent as ReviewIcon } from "../assets/svg/star.svg";
import { ReactComponent as RequestIcon } from "../assets/svg/bookmark.svg";
import { ReactComponent as SettingsIcon } from "../assets/svg/settings.svg";
import { ReactComponent as AdminIcon } from "../assets/svg/admin.svg";
import { ReactComponent as IssueIcon } from "../assets/svg/issue.svg";
import pjson from "../../package.json";
class Sidebar extends React.Component {
render() {
let current = this.props.location.pathname;
let user = this.props.user.current;
return (
<div className={`menu ${this.props.mobOpen ? "open" : ""}`}>
<div className="menu--logo">
<div className="logo">
Pet<span>io</span>
</div>
<p className="menu--title">Admin Dashboard</p>
</div>
<div className="menu--items">
<Link
to="/user"
className={
"menu--item user-profile " +
(current === "/user" || current.startsWith("/user/")
? "active"
: "")
}
onClick={this.props.toggleMobMenu}
>
<p>{user.title}</p>
<div className="icon">
<div
className="thumb"
style={{
backgroundImage:
process.env.NODE_ENV === "development"
? 'url("http://localhost:7778/user/thumb/' +
user.id +
'")'
: 'url("' +
window.location.pathname
.replace("/admin/", "")
.replace(/\/$/, "") +
"/api/user/thumb/" +
user.id +
'")',
}}
></div>
</div>
</Link>
<Link
to="/"
className={"menu--item " + (current === "/" ? "active" : "")}
onClick={this.props.toggleMobMenu}
>
<p>Dashboard</p>
<div className="icon">
<DashIcon />
</div>
</Link>
<Link
to="/requests"
className={
"menu--item " +
(current === "/requests" || current.startsWith("/requests/")
? "active"
: "")
}
onClick={this.props.toggleMobMenu}
>
<p>Requests</p>
<div className="icon">
<RequestIcon />
</div>
</Link>
<Link
to="/issues"
className={
"menu--item " +
(current === "/issues" || current.startsWith("/issues/")
? "active"
: "")
}
onClick={this.props.toggleMobMenu}
>
<p>Issues</p>
<div className="icon">
<IssueIcon />
</div>
</Link>
<Link
to="/reviews"
className={
"menu--item " +
(current === "/reviews" || current.startsWith("/reviews/")
? "active"
: "")
}
onClick={this.props.toggleMobMenu}
>
<p>Reviews</p>
<div className="icon">
<ReviewIcon />
</div>
</Link>
<Link
to="/users"
className={
"menu--item " +
(current === "/users" || current.startsWith("/users/")
? "active"
: "")
}
onClick={this.props.toggleMobMenu}
>
<p>Users</p>
<div className="icon">
<PersonIcon />
</div>
</Link>
<Link
to="/settings"
className={
"menu--item " +
(current === "/settings" || current.startsWith("/settings/")
? "active"
: "")
}
onClick={this.props.toggleMobMenu}
>
<p>Settings</p>
<div className="icon">
<SettingsIcon />
</div>
</Link>
<a
className="menu--item"
href={`${window.location.protocol}//${
window.location.host
}${window.location.pathname.replace("/admin/", "")}`}
>
<p>Exit Admin</p>
<div className="icon">
<AdminIcon />
</div>
</a>
</div>
<p className="menu--version">version {pjson.version}</p>
</div>
);
}
}
Sidebar = withRouter(Sidebar);
function SidebarContainer(props) {
return (
<Sidebar
user={props.user}
changeLogin={props.changeLogin}
mobOpen={props.mobOpen}
toggleMobMenu={props.toggleMobMenu}
/>
);
}
const mapStateToProps = function (state) {
return {
user: state.user,
};
};
export default connect(mapStateToProps)(SidebarContainer);
|
require.config({
paths: {
jquery: 'vendor/jquery-2.0.3.min',
underscore: 'vendor/underscore-1.5.2.min',
backbone: 'vendor/backbone-1.0.0.min',
prismic: 'vendor/prismic.io-1.0.11.min',
text: 'vendor/text-0.27.0.min',
modernizr: 'vendor/modernizr-2.6.2.min',
catslider: 'vendor/catslider',
numeral: 'vendor/numeral-1.4.5.min',
moment: 'vendor/moment-2.2.1.min'
},
shim: {
catslider: {
deps : ['modernizr']
},
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
prismic: {
exports: 'Prismic'
}
}
});
require(['app', 'blog'], function(App, Blog) {
if(document.location.pathname.indexOf('blog') > 0) {
Blog.run();
} else {
App.run();
}
});
|
window.registerExtension("dependencyversion/report", function(options) {
var isDisplayed = true;
if (!document.querySelector("style#dependency-version-report")) {
var style = document.createElement("style");
style.id = "dependency-version-report";
style.appendChild(document.createTextNode(""));
document.head.appendChild(style);
style.sheet.insertRule(".dependency-version-report-content {flex: 1 1 auto;}", 0);
style.sheet.insertRule(".dependency-version-report-container {display: flex; flex-direction: column;}", 0);
}
window.SonarRequest.getJSON("/api/measures/component", {
componentKey : options.component.key,
metricKeys : "report"
}).then(function(response) {
if (isDisplayed) {
var htmlString = response.component.measures.filter(measure => measure.metric === "report")[0].value;
var currentEl = options.el;
while (currentEl.id !== "container") {
currentEl.classList.add("dependency-version-report-content");
currentEl.classList.add("dependency-version-report-container");
currentEl = currentEl.parentElement;
}
currentEl.classList.add("dependency-version-report-container");
var reportFrame = document.createElement("iframe");
reportFrame.sandbox.value = "allow-scripts allow-same-origin";
reportFrame.style.border = "none";
reportFrame.style.flex= "1 1 auto";
reportFrame.srcdoc = htmlString;
options.el.append(reportFrame);
}
});
return function() {
options.el.textContent = "";
var currentEl = options.el;
while (currentEl.id !== "container") {
currentEl.classList.remove("dependency-version-report-content");
currentEl.classList.remove("dependency-version-report-container");
currentEl = currentEl.parentElement;
}
currentEl.classList.remove("dependency-version-report-container");
};
});
|
async function login(page, callback) {
let res;
const p = new Promise((r) => res = r);
await page.waitForSelector('div[class*="qrCode-"] > img');
page.browser().on('targetchanged', (e) => {
let t = e.url();
if (t === 'https://discord.com/channels/@me') res();
});
const b64 = await page.evaluate(() => {
return document.querySelector('div[class*="qrCode-"] > img').src;
});
callback(b64);
await p;
await page.waitForSelector('div[class*="unreadMentionsIndicatorTop"]');
}
async function getMentions(page) {
return page.evaluate(() => {
let mentions = 0;
let hasUnreads = false;
document.querySelectorAll('div[class*="lowerBadge-"] > div[class*="numberBadge-"]').forEach((i) => {
mentions += parseInt(i.innerText);
});
Array.from(document.querySelectorAll('div[class*="pill"] > span'))
.forEach((e) => { if (e.style.height == '8px') hasUnreads = true })
return {
mentions,
hasUnreads
};
});
}
function setTitle(title, context, sd) {
sd.send({
event: 'setTitle',
context: context,
payload: {
title: title
}
})
}
module.exports = { login, getMentions, setTitle }
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//---------------
var map;
var myTimer;
var today;
var urlPort;
moment().format();
//---------------
var app = {
// Application Constructor
initialize: function()
{
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function()
{
this.receivedEvent('deviceready');
onLoadFunc();//device is ready, so init...
document.getElementById("getCurrPosition").addEventListener("click", getCurrPosition);
// document.getElementById("watchPosition").addEventListener("click", watchPosition);
document.addEventListener("backbutton", this.onBackKeyDown, false);
var div = document.getElementById("map_canvas");
// Initialize the map view
map = plugin.google.maps.Map.getMap(div);
// Wait until the map is ready status.
map.addEventListener(plugin.google.maps.event.MAP_READY, app.onMapReady);
},
// Handle the back button
onBackKeyDown: function()
{
map.clear();
map.off();
if (navigator.app)
{
navigator.app.exitApp();
} else if (navigator.device)
{
navigator.device.exitApp();
} else
{
window.close();
}
},
onMapReady: function ()
{
console.log("onMapReady:");
app.receivedEvent('mapready');
var button1 = document.getElementById("map-button1");
var button2 = document.getElementById("map-button2");
button1.addEventListener("click", app.onButtonClick1);
button2.addEventListener("click", app.onButtonClick2);
map.getMyLocation(function(location)
{
// Move camera to the marker created
map.animateCamera(
{
'target': location.latLng,
'zoom': 15,
'bearing': 140
});
});
},
// Update DOM on a Received Event
receivedEvent: function(id)
{
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
//john
onButtonClick1: function()
{
// Move to the position with animation
map.animateCamera
({
target: {lat: 51.5769603, lng: -0.0617729},
zoom: 11,
tilt: 60,
bearing: 140,
duration: 5000
}, function()
{
// Add a maker
map.addMarker
({
position: {lat: 51.5769603, lng: -0.0617729},
title: "John\n" ,
snippet: "Have a nice day !",
animation: plugin.google.maps.Animation.BOUNCE
}, function(marker)
{
// Show the info window
marker.showInfoWindow();
// Catch the click event
marker.on(plugin.google.maps.event.INFO_CLICK, function()
{
// To do something...
alert("North London");
});//marker.on
});//addMarker
});//animateCamera
},//onButtonClick1
//Gabi 51.52041800413905%2C-0.07519049999996241
onButtonClick2: function()
{
// Move to the position with animation
map.animateCamera
({
target: {lat: 51.52041800413905, lng: -0.07519049999996241},
zoom: 11,
tilt: 60,
bearing: 140,
duration: 5000
}, function()
{
// Add a maker
map.addMarker
({
position: {lat: 51.52041800413905, lng: -0.07519049999996241},
title: "Gabi\n" ,
snippet: "Have a nice day !",
animation: plugin.google.maps.Animation.BOUNCE
}, function(marker)
{
// Show the info window
marker.showInfoWindow();
// Catch the click event
marker.on(plugin.google.maps.event.INFO_CLICK, function()
{
// To do something...
alert("Central London");
});//marker.on
});//addMarker
});//animateCamera
},//onButtonClick2
// getMap: function()
// {
// return map;//app.map
// },
animateCamera: function(target, zoom, tilt, bearing, duration)
{
},
addMarker: function(position, title, snippet, animation)
{
}
//---------------
};//app
//---------------
app.initialize();
//---------------
|
let name = "Vitaliy",
age = 25;
let user = {
name,
age
};
console.log(JSON.stringify(user));
|
jQuery(document).ready(function($) {
//FEED_URL = 'http://stackoverflow.com/feeds/tag?tagnames=wordpress&sort=newest';
//feed url
$.ajax({
url: document.location.protocol + '//blogs.ntu.edu.sg/lib-databases/?feed=json',
//document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
dataType: 'json',
success: function(data) {
if (data.responseData.feed && data.responseData.feed.entries) {
var ul = $('<ul>'),
titles = data.responseData.feed.entries.map(function(item) { return item.title; });
//get the titles in array
$.each(titles.sort( case_insensitive_comp ) /* sort the titles */, function(i, r) { var li = $('<li/>', { 'text': r }) .appendTo(ul); });
$('#element').html(ul);
//output at #element
}
}
})
});
//case insensitive base on @Lekensteyn answer at http://stackoverflow.com/a/5286047/1562904
function case_insensitive_comp( strA, strB ) {
return strA.toLowerCase().localeCompare( strB.toLowerCase() );
}
|
'use strict';
const match = require('../../MultiBracketValidation/multi-bracket-validation');
const trueArr =['{}','{}(){}','()[[Extra Characters]]','(){}[[]]','{}{Code}[Fellows](())'];
const falseArr =['[({}]','(](','{(})'];
describe('it should check for even amount of scoping characters', ()=>{
it('Should check for matching symbols',() =>{
let test = trueArr[0];
expect(match.matchingBrackets(test)).toBe(true);
test = trueArr[1];
expect(match.matchingBrackets(test)).toBe(true);
test = trueArr[2];
expect(match.matchingBrackets(test)).toBe(false);
// test = trueArr[3];
// expect(match.matchingBrackets(test)).toBe(true);
})
})
|
import { StyleSheet } from 'react-native'
import { Color, Layout } from '../../../constants'
const styles = StyleSheet.create({
container: {
flex: 1
},
section: {
width: '100%',
marginTop: Layout.EDGE_PADDING
},
imageWrapper: {
justifyContent: 'center',
alignItems: 'center',
// backgroundColor: Color.BACKGROUND_ACCENT,
// padding: Layout.EDGE_PADDING,
// height: 120,
position: 'relative'
},
image: {
width: 100,
height: 100,
borderRadius: Layout.ICON_GAP,
marginBottom: Layout.EDGE_PADDING,
position: 'absolute',
top: 48,
backgroundColor: Color.WHITE
},
textContainer: {
// position: 'absolute',
width: '100%',
top: 160
},
textWrapper: {
justifyContent: 'space-around',
paddingHorizontal: Layout.EDGE_PADDING
},
textWhite: {
color: Color.WHITE
},
smallText: {
fontSize: Layout.SPAN,
textAlign: 'center'
},
handle: {
color: Color.DEFAULT
},
lightText: {
color: Color.DEFAULT,
textAlign: 'center'
},
bold: {
fontWeight: 'bold',
textAlign: 'center'
},
bottomLinks: {
marginTop: Layout.EDGE_PADDING * 2,
flexDirection: 'row',
justifyContent: 'space-around',
width: '100%'
},
bio: {
marginTop: Layout.EDGE_PADDING,
textAlign: 'center'
},
title: {
fontSize: Layout.HEADER,
color: Color.BLACK,
backgroundColor: Color.WHITE,
padding: Layout.EDGE_PADDING,
textAlign: 'center'
},
itemStyle: {
paddingHorizontal: Layout.EDGE_PADDING
},
icon: {
color: Color.DEFAULT,
paddingRight: Layout.ICON_GAP * 2
}
})
export default styles
|
import { createStore, applyMiddleware, combineReducers } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from 'redux/reducers';
import rootSaga from 'redux/sagas'
// create the saga middleware
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
combineReducers(rootReducer),
applyMiddleware(sagaMiddleware)
);
// then run the saga
sagaMiddleware.run(rootSaga);
export default store;
|
import React, {Component} from 'react';
import './App.css';
import Toolbar from "./component/toolbar";
import logo from './logo.svg';
import TodoList from "./component/todolist/todolist";
class App extends Component {
constructor(props) {
super(props);
this.state = {
todoList: [
{name: 'Test Item'},
{name: 'Test Item 2'}
]
};
}
render() {
return (
<div className="App">
<Toolbar logo={logo}/>
<div className="container">
<TodoList items={this.state.todoList} />
</div>
</div>
);
}
}
export default App;
|
import axios from 'axios'
export default class JobPostingService {
getJobPostings(){
return axios.get("http://localhost:8080/api/jobposting/getall")}
getActiveJobPostings(){
return axios.get("http://localhost:8080/api/jobposting/getAllIsActive")}
getJobPostingsWithDetails(){
return axios.get("http://localhost:8080/api/jobposting/getJobAdvertisementWithDetails")
}
getByPostingDateAsc(){
return axios.get("http://localhost:8080/api/jobposting/getByPostingDateAscending")
}
getByPostingDateDesc(){
return axios.get("http://localhost:8080/api/jobposting/getByPostingDateDescending")
}
getByCompanyName(){
return axios.get("http://localhost:8080/api/jobposting/getByCompanyName")
}
}
|
const freelanceList = [
{
name: 'Software & Tech',
topicID: 'freelance_software',
icon: 'code',
color: 'peach',
children: [
{
name: 'Web Development',
topicID: 'freelance_software_webdevelopment',
color: 'peach',
},
{
name: 'Mobile Apps',
topicID: 'freelance_software_mobileapps',
color: 'peach',
},
{
name: 'Game Development',
topicID: 'freelance_software_gamedevelopment',
color: 'peach',
},
{
name: 'E-commerce Development',
topicID: 'freelance_software_ecommercedevelopment',
color: 'peach',
},
{
name: 'Backend / Database',
topicID: 'freelance_software_backenddatabase',
color: 'peach',
},
{
name: 'IT & Networking',
topicID: 'freelance_software_itnetworking',
color: 'peach',
},
{
name: 'Data Science & Analytics',
topicID: 'freelance_software_datascienceanalytics',
color: 'peach',
},
{
name: 'Other',
topicID: 'freelance_software_other',
color: 'peach',
},
],
},
{
name: 'Engineering',
topicID: 'freelance_engineering',
icon: 'drafting-compass',
color: 'peach',
children: [
{
name: 'Mechanical Engineering',
topicID: 'freelance_engineering_mechanicalengineering',
color: 'peach',
},
{
name: 'Electrical Engineering',
topicID: 'freelance_engineering_electricalengineering',
color: 'peach',
},
{
name: 'Chemical Engineering',
topicID: 'freelance_engineering_chemicalengineering',
color: 'peach',
},
{
name: 'Civil & Structural Engineering',
topicID: 'freelance_engineering_civilstructuralengineering',
color: 'peach',
},
{
name: 'Product Design',
topicID: 'freelance_engineering_productdesign',
color: 'peach',
},
{
name: '3D Modeling & CAD',
topicID: 'freelance_engineering_3dmodelingcad',
color: 'peach',
},
{
name: 'Other',
topicID: 'freelance_engineering_other',
color: 'peach',
},
],
},
{
name: 'Graphics & Design',
topicID: 'freelance_design',
icon: 'paint-brush',
color: 'peach',
// color: colors.peach,
children: [
{
name: 'Logo Design',
topicID: 'freelance_design_logodesign',
color: 'peach',
},
{
name: 'Brand Design',
topicID: 'freelance_design_branddesign',
color: 'peach',
},
{
name: 'Web & Mobile Design',
topicID: 'freelance_design_webmobiledesign',
color: 'peach',
},
{
name: 'Graphic Design',
topicID: 'freelance_design_graphicdesign',
color: 'peach',
},
{
name: 'Game Design',
topicID: 'freelance_design_gamedesign',
color: 'peach',
},
{
name: 'Photoshop',
topicID: 'freelance_design_photoshop',
color: 'peach',
},
{
name: 'Other',
topicID: 'freelance_design_other',
color: 'peach',
},
],
},
{
name: 'Music & Audio',
topicID: 'freelance_musicaudio',
icon: 'music',
color: 'peach',
// color: colors.peach,
children: [
{
name: 'Voice Over',
topicID: 'freelance_musicaudio_voiceover',
color: 'peach',
},
{
name: 'Mixing & Mastering',
topicID: 'freelance_musicaudio_mixingmastering',
color: 'peach',
},
{
name: 'Producing',
topicID: 'freelance_musicaudio_producing',
color: 'peach',
},
{
name: 'Singer-Songwriter',
topicID: 'freelance_musicaudio_singersongwriter',
color: 'peach',
},
{
name: 'Other',
topicID: 'freelance_musicaudio_other',
color: 'peach',
},
],
},
{
name: 'Video & Animation',
topicID: 'freelance_videoanimation',
icon: 'film',
color: 'peach',
// color: colors.peach,
children: [
{
name: 'Explainer Videos',
topicID: 'freelance_videoanimation_explainervideos',
color: 'peach',
},
{
name: 'Video Editing',
topicID: 'freelance_videoanimation_videoediting',
color: 'peach',
},
{
name: 'Video Production',
topicID: 'freelance_videoanimation_videoproduction',
color: 'peach',
},
{
name: 'Intros & Outros',
topicID: 'freelance_videoanimation_introsoutros',
color: 'peach',
},
{
name: 'Animations',
topicID: 'freelance_videoanimation_animations',
color: 'peach',
},
{
name: 'Short Video Ads',
topicID: 'freelance_videoanimation_shortvideoads',
color: 'peach',
},
{
name: 'Other',
topicID: 'freelance_videoanimation_other',
color: 'peach',
},
],
},
{
name: 'Sales & Marketing',
topicID: 'freelance_salesmarketing',
icon: 'comment-dollar',
color: 'peach',
// color: colors.peach,
children: [
{
name: 'Social Media Marketing',
topicID: 'freelance_salesmarketing_socialmediamarketing',
color: 'peach',
},
{
name: 'Digital Marketing',
topicID: 'freelance_salesmarketing_digitalmarketing',
color: 'peach',
},
{
name: 'Marketing Strategy',
topicID: 'freelance_salesmarketing_marketingstrategy',
color: 'peach',
},
{
name: 'E-commerce Sales',
topicID: 'freelance_salesmarketing_ecommercesales',
color: 'peach',
},
{
name: 'Lead Generation & Sales',
topicID: 'freelance_salesmarketing_leadgenerationsales',
color: 'peach',
},
{
name: 'Other',
topicID: 'freelance_salesmarketing_other',
color: 'peach',
},
],
},
{
name: 'Business',
topicID: 'freelance_business',
icon: 'user-tie',
color: 'peach',
// color: colors.peach,
children: [
{
name: 'Virtual Assistant',
topicID: 'freelance_business_virtualassistant',
color: 'peach',
},
{
name: 'Data Entry',
topicID: 'freelance_business_dataentry',
color: 'peach',
},
{
name: 'Accounting',
topicID: 'freelance_business_accounting',
color: 'peach',
},
{
name: 'Legal Consulting',
topicID: 'freelance_business_legalconsulting',
color: 'peach',
},
{
name: 'Financial Consulting',
topicID: 'freelance_business_financialconsulting',
color: 'peach',
},
{
name: 'Business Consulting',
topicID: 'freelance_business_businessconsulting',
color: 'peach',
},
{
name: 'Branding Services',
topicID: 'freelance_business_brandingservices',
color: 'peach',
},
{
name: 'Project Managament',
topicID: 'freelance_business_projectmanagement',
color: 'peach',
},
{
name: 'Marketing Research',
topicID: 'freelance_business_marketingresearch',
color: 'peach',
},
{
name: 'Customer Service',
topicID: 'freelance_business_customerservice',
color: 'peach',
},
{
name: 'Other',
topicID: 'freelance_business_other',
color: 'peach',
},
],
},
{
name: 'Writing',
topicID: 'freelance_writing',
icon: 'feather',
color: 'peach',
children: [
{
name: 'Editing & Proofreading',
topicID: 'freelance_writing_editingproofreading',
color: 'peach',
},
{
name: 'Content Writing',
topicID: 'freelance_writing_contentwriting',
color: 'peach',
},
{
name: 'Ghostwriting',
topicID: 'freelance_writing_ghostwriting',
color: 'peach',
},
{
name: 'Business Writing',
topicID: 'freelance_writing_businesswriting',
color: 'peach',
},
{
name: 'Creative Writing',
topicID: 'freelance_writing_creativewriting',
color: 'peach',
},
{
name: 'Technical Writing',
topicID: 'freelance_writing_technicalwriting',
color: 'peach',
},
{
name: 'Other',
topicID: 'freelance_writing_other',
color: 'peach',
},
],
},
];
module.exports = {
freelanceList
};
|
import React from "react";
import PropTypes from "prop-types";
import Card from "../atoms/card";
function Article(props) {
const { articles } = props;
return (
<React.Fragment>
{articles &&
articles.map((x, index) => {
return <Card key={index} element={x}></Card>;
})}
</React.Fragment>
);
}
Article.propTypes = {
articles: PropTypes.array
};
export default Article;
|
var lib = {};
lib.tmpl = function(){
var cache = {};
function _getTmplStr(rawStr, mixinTmpl) {
if(mixinTmpl) {
for(var p in mixinTmpl) {
var r = new RegExp('<%#' + p + '%>', 'g');
rawStr = rawStr.replace(r, mixinTmpl[p]);
}
}
return rawStr;
};
return function tmpl(str, data, opt) {
opt = opt || {};
var key = opt.key, mixinTmpl = opt.mixinTmpl, strIsKey = !/\W/.test(str);
key = key || (strIsKey ? str : null);
var fn = key ? cache[key] = cache[key] || tmpl(_getTmplStr(strIsKey ? document.getElementById(str).innerHTML : str, mixinTmpl)) :
new Function("obj", "var _p_=[],print=function(){_p_.push.apply(_p_,arguments);};with(obj){_p_.push('" + str
.replace(/[\r\t\n]/g, " ")
.split("\\'").join("\\\\'")
.split("'").join("\\'")
.split("<%").join("\t")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("_p_.push('")
+ "');}return _p_.join('');");
return data ? fn( data ) : fn;
};
}();
lib.insertStyle = function(rules){
var node=document.createElement("style");
node.type='text/css';
document.getElementsByTagName("head")[0].appendChild(node);
if(rules){
if(node.styleSheet){
node.styleSheet.cssText=rules;
}else{
node.appendChild(document.createTextNode(rules));
}
}
return node.sheet||node;
}
lib.parseDate = function(date){
var copy = new Date(+date);
var result = {};
result.year = copy.getFullYear();
result.month = copy.getMonth();
result.date = copy.getDate();
copy.setDate(1);
result.emptys = copy.getDay() ? copy.getDay()-1:6;
result.first = +new Date(result.year,result.month,copy.getDate());
copy.setMonth(copy.getMonth()+1);
copy.setDate(0);
result.count = copy.getDate();
result.last = +new Date(result.year,result.month,copy.getDate());
return result
}
lib.ready = function(fn){
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
if (document.readyState === 'complete'){
setTimeout(trigger);
} else {
this.addEventListener(document,'DOMContentLoaded', trigger);
this.addEventListener(window,'load', trigger);
}
}
lib.format = function(date){
return date.toLocaleDateString().replace(/(\d{4}).(\d{2}).(\d{2})./,"$1/$2/$3");
}
lib.getClientRect =function(elem){
try {
var box = elem.getBoundingClientRect(),rect = {};
//ie8- 没有width和height
if(box.width){
rect = box;
box.width = box.right-box.left;
box.height = box.bottom - box.top;
}
else{
rect = {
top:box.top,
right:box.right,
bottom:box.bottom,
left:box.left,
width:box.right-box.left,
height:box.bottom - box.top
}
}
return rect;
} catch (e) {return {}}
}
;(function(){
var handlers = {};
var clicks = {};
var callback = function(e){
var type = e.type;
if(type == 'touchend'){
type = 'click'
}
var target = e.target || e.srcElement;
if(handlers[type] && handlers[type].length){
var prevent = false;
for(var i=0,hdl;hdl = handlers[type][i];i++){
if(false === hdl.call(target,e)){
prevent = true;
}
}
if(prevent && e.preventDefault){
e.preventDefault();
e.stopPropagation();
}
}
}
lib.addEventListener = function(element,type, callback){
if (element.addEventListener) // W3C
element.addEventListener(type, callback, true);
else if (elem.attachEvent) { // IE
element.attachEvent("on"+ type, callback);
}
}
////////////////////////
lib.on = function(types,hdl){
types = types.split(',');
for(var i=0,type;type = types[i];i++){
//第一次添加该类型则:
//1
if(!handlers[type]){
handlers[type] = [];
}
//2
if(handlers[type].length < 1){
var element = document.documentElement;
if (type === 'click' && 'ontouchstart' in element) {
(function(){
var x1=0,y1=0,x2=0,y2=0,flag = false;
element.addEventListener('touchstart',function(e){
var touch = e.touches[0];
x1 = touch.pageX;
y1 = touch.pageY;
flag = false;
})
element.addEventListener('touchmove',function(e){
var touch = e.touches[0];
x2 = touch.pageX;
y2 = touch.pageY;
flag = true;
})
element.addEventListener('touchend',function(e){
if(flag){
var offset = Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2));
if(offset < 5){
callback(e)
}
}
else{
callback(e)
}
})
})()
}
else{
lib.addEventListener(element,type,callback);
}
}
handlers[type].push(hdl);
}
}
lib.click = function(name,hdl){
lib.on('click',function(e){
var target = this;
while(target && target.nodeType == 1){
var name = target.getAttribute('data-click');
if(name && clicks[name]){
return clicks[name].call(this,target);
break;
}
target = target.parentNode;
}
})
lib.click = function(name,hdl){
clicks[name] = hdl;
}
lib.click(name,hdl);
}
})();
|
import React from 'react' ;
const ViewPost = () => {
return <div> ViewPost </div>;
}
export default ViewPost ;
|
import styled, { css } from "styled-components";
import tokens from "@paprika/tokens";
import stylers from "@paprika/stylers";
import * as types from "../../types";
const blueSelected = tokens.color.blueLighten50;
const activeStyles = css`
${stylers.focusRing()}
`;
const disabledStyles = css`
background: transparent;
border: 0;
color: ${tokens.color.blackLighten60};
outline: none;
&:focus {
${stylers.focusRing.subtle()}
border-bottom-color: transparent;
border-radius: ${tokens.border.radius};
}
`;
const fontSize = {
[types.SMALL]: css`
${stylers.fontSize(-2)}
`,
[types.MEDIUM]: css`
${stylers.fontSize(-1)}
`,
[types.LARGE]: css`
${stylers.fontSize()}
`,
};
const stateStyles = ({ isSelected, hasPreventDefaultOnSelect }) => css`
&:hover {
${hasPreventDefaultOnSelect ? "background: transparent;" : ""};
background: ${isSelected ? blueSelected : tokens.color.blackLighten70};
}
&:focus {
${stylers.focusRing()}
border-bottom-color: transparent;
border-radius: ${tokens.border.radius};
}
`;
export const Option = styled.li(
({ size, isDisabled, hasPreventDefaultOnSelect, isSelected, isActive, listBoxHasFocus }) => css`
border: 2px solid transparent;
border-radius: 3px;
cursor: pointer;
margin-bottom: ${tokens.spaceSm};
padding: ${tokens.spaceSm};
${fontSize[size]}
&:hover {
${isDisabled ? "cursor: not-allowed;" : ""};
}
${isActive && listBoxHasFocus && hasPreventDefaultOnSelect ? `border-color: ${tokens.color.blackLighten60}` : ""};
${isActive && listBoxHasFocus ? activeStyles : ""}
${hasPreventDefaultOnSelect}
${isSelected ? `background: ${blueSelected};` : ""}
${isDisabled ? disabledStyles : stateStyles}
`
);
|
import Headerbounce from "./Headerbounce";
import React, { useState, useEffect } from "react";
import axios from "axios";
import "../../src/App.css";
import Badge from "react-bootstrap/Badge";
import "bootstrap/dist/css/bootstrap.min.css";
import { motion } from "framer-motion";
import Button from "react-bootstrap/Button";
import "antd/dist/antd.css";
import { Switch } from "antd";
import { CloseOutlined, CheckOutlined } from "@ant-design/icons";
import Roll from "react-reveal/Roll";
import Wobble from "react-reveal/Wobble";
function Product() {
const [foodName, setfoodName] = useState("");
const [foodList, setfoodList] = useState([]);
const [newFoodName, setnewFoodName] = useState("");
const [visible, setvisible] = useState(false);
useEffect(() => {
axios
.get("https://shopping-grocery-list.herokuapp.com/read")
.then((response) => {
setfoodList(response.data);
});
}, []);
const addToList = () => {
axios
.post("https://shopping-grocery-list.herokuapp.com/insert", {
foodName: foodName,
})
.then(() => {
window.location.reload(false);
});
};
const updateFood = (id) => {
axios
.put("https://shopping-grocery-list.herokuapp.com/update", {
id: id,
newFoodName: newFoodName,
})
.then(() => {
window.location.reload(false);
});
};
/* hide editing */
const editingHandler = () => {
setvisible((visible) => !visible);
};
const deleteFood = (id) => {
axios
.delete(`https://shopping-grocery-list.herokuapp.com/delete/${id}`, {})
.then(() => {
window.location.reload(false);
});
};
return (
<div>
<div className="App">
<Headerbounce />
<div className="decoration">
{/* first part */}
<label>Food Name:</label>
<input
type="text"
onChange={(event) => {
setfoodName(event.target.value);
}}
/>
<motion.button
className="Add"
onClick={addToList}
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
>
Add!
</motion.button>
{/* first part */}
<h1>Food</h1>
<Roll bottom>
<div>
{foodList.map((val, key) => {
return (
<div key={key} className="product">
<div>
<div className="checkbox">
<h3>
<Badge pill variant="success">
{val.foodName}
</Badge>
</h3>
</div>
<Button
style={{ marginBottom: "10px" }}
onClick={() => deleteFood(val._id)}
variant="success"
>
Delete
</Button>
{visible && (
<div>
<Button onClick={() => updateFood(val._id)}>
Update
</Button>
<input
type="text"
placeholder="New food Name..."
onChange={(event) => {
setnewFoodName(event.target.value);
}}
/>
</div>
)}
</div>
<Switch
checkedChildren={<CheckOutlined />}
unCheckedChildren={<CloseOutlined />}
/>
</div>
);
})}
</div>
</Roll>
<Wobble>
<Button onClick={editingHandler} variant="danger">
Update-Product
</Button>
</Wobble>
</div>
</div>
</div>
);
}
export default Product;
|
import React, { Component } from 'react';
import { Row, Col, Collapse } from 'reactstrap';
import s from './footerMobile.scss';
class FooterMobile extends Component {
constructor(props) {
super(props);
this.state = { collapse: [] };
}
toggle = (index) => {
const { collapse } = this.state;
collapse[index] = !collapse[index];
this.setState({ collapse });
}
render() {
return (
<div className="footerMobileDiv">
<div className="footerMobileHeaderDiv">
<Row className="menuRow">
<Col xs={10} className="d-flex justify-content-middle align-items-left">
<div className="footerTitle">Store</div>
</Col>
<Col xs={2} className="d-flex justify-content-middle align-items-left">
<div className="divImgPlusTeal">
<btn href="#" onClick={() => this.toggle(0)}><img src="/static/images/plusTeal.png" alt="plusTeal" /></btn>
</div>
</Col>
</Row>
<Row>
<Col sm={12} className="d-flex justify-content-middle align-items-left">
<Collapse isOpen={this.state.collapse[0]}>
<ul>
<li>
<a href="/">Cove Protect</a>
</li>
<li>
<a href="/">Cove Touch</a>
</li>
<li>
<a href="/">Cove Smoke Detector</a>
</li>
<li>
<a href="/">Cove Food Detector</a>
</li>
<li>
<a href="/">Cove Carbon Monoxide</a>
</li>
<li>
<a href="/">Cove Camera</a>
</li>
</ul>
</Collapse>
</Col>
</Row>
</div>
<div className="footerMobileHeaderDiv">
<Row className="menuRow">
<Col xs={10} className="d-flex justify-content-middle align-items-left">
<div className="footerTitle">Company</div>
</Col>
<Col xs={2} className="d-flex justify-content-middle align-items-right">
<div className="divImgPlusTeal" >
<btn onClick={() => this.toggle(1)}><img src="/static/images/plusTeal.png" alt="plusTeal" /></btn>
</div>
</Col>
</Row>
<Row>
<Col sm={12} className="d-flex justify-content-middle align-items-left">
<Collapse isOpen={this.state.collapse[1]}>
<ul>
<li>
<a href="/">Support</a>
</li>
<li>
<a href="/">Community</a>
</li>
<li>
<a href="/">About us</a>
</li>
<li>
<a href="/">Blog</a>
</li>
<li>
<a href="/">Responsibility</a>
</li>
<li>
<a href="/">Careers</a>
</li>
<li>
<a href="/">Press</a>
</li>
<li>
<a href="/">Video</a>
</li>
</ul>
</Collapse>
</Col>
</Row>
</div>
<div className="footerMobileHeaderDiv">
<Row className="menuRow">
<Col xs={10} className="d-flex justify-content-middle align-items-left">
<div className="footerTitle">Programs</div>
</Col>
<Col xs={2} className="d-flex justify-content-middle align-items-right">
<div className="divImgPlusTeal" >
<btn onClick={() => this.toggle(2)}><img src="/static/images/plusTeal.png" alt="plusTeal" /></btn>
</div>
</Col>
</Row>
<Row>
<Col sm={12} className="d-flex justify-content-middle align-items-left">
<Collapse isOpen={this.state.collapse[2]}>
<ul>
<li>
<a href="/">Insurance Partners</a>
</li>
<li>
<a href="/">Rebates and Rewards</a>
</li>
<li>
<a href="/">Cove for Business</a>
</li>
</ul>
</Collapse>
</Col>
</Row>
</div>
<Row>
<Col xs={12} sm={12} md={3}>
<input className="email" type="text" name="email" id="emailText" placeholder="Enter Email for Cove news" />
<div className="socialMedia">
<img src="/static/images/facebook.png" alt="facebook" />
<img src="/static/images/twitter.png" alt="twitter" />
<img src="/static/images/instagram.png" alt="instagram" />
<img src="/static/images/youtube.png" alt="youtube" />
<img src="/static/images/whatsapp.png" alt="whatsapp" />
</div>
</Col>
</Row>
<style jsx>{s}</style>
</div>
);
}
}
export default FooterMobile;
|
import * as actionTypes from './types';
export const setInBatchMode = inBatch => ({
type: actionTypes.SET_INBATCHMODE,
payload: inBatch,
})
export const addBatchedAction = action => ({
type: actionTypes.ADD_BATCHED_ACTION,
payload: action,
})
export const clearBatchedActions = () => ({
type: actionTypes.CLEAR_BATCHED_ACTIONS,
})
export const startBatchMode = () => ({
type: actionTypes.SET_INBATCHMODE,
payload: true,
})
export const flushBatchedActions = () => ({
type: actionTypes.FLUSH_BATCH_UPDATES,
})
|
$(document).ready(function(){
// all elements
$('*').css('background-color', 'lightgrey');
// selector tag
$('h1').css('color', 'red');
$('p').css('color', 'blue');
// selector class
$('.judul').css('background-color', 'blue');
$('.paragraf').css('color', 'salmon');
// selector id
$('#judul').css('border', '2px solid blue');
$('#paragraf').css('border', '2px solid green');
// eq(index)
$('h4:eq(2)').css('background-color', 'yellow')
$('h4:first').css('background-color', 'lightgreen')
$('h4:last').css('background-color', 'lightblue')
// input:type
$('input').css('color', 'blue').css('border-radius', '7px').css('font-family', 'calibri'); //multiple properties
$('input:submit').css('background-color', 'lightblue');
$('input:button').css('padding', '10px');
})
|
import React, { useContext, useState } from "react";
import axios from "axios";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import Alert from "@material-ui/lab/Alert";
import { UserContext } from "./../userContext";
import CreateForm from "./../components/createForm";
import CreateImageForm from "./../components/createFormImage";
import ImgOrTxt from "./../components/createImageOrText";
import Layout from "../components/layout";
import { style } from "../styles";
import QuestionImg from "../images/question.png";
import ResponsiveImage from "./../components/responsiveImage";
import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles";
const theme = createMuiTheme({
typography: {
fontFamily: style.dropDown.fontFamily,
fontSize: "3vw",
},
bacgroundColor: style.colors.yellow,
});
function Create() {
const [title, setTitle] = useState("");
const [questions, setQuestions] = useState([]);
const [showQuestions, setShowQuestions] = useState(false);
const [displayInputAlert, setDisplayInputAlert] = useState(false);
const [displayGameChoice, setDisplayGameChoice] = useState(true);
const [textGame, setTextGame] = useState(false);
const [answerImages, setAnswerImages] = useState([]);
const context = useContext(UserContext);
const uploadFiles = () => {
console.log("selected many");
let files = answerImages;
console.log(files);
const formData = new FormData();
//append all files to formData
for (var file of files) {
formData.append("uploadedFiles", file);
}
const config = {
headers: {
"content-type": "multipart/form-data",
},
};
axios
.post("http://localhost:3030/upload-files", formData, config)
.then(() => {
console.log("files Saved");
})
.catch((err) => {
console.log(err);
});
};
const typeOfTest = () => {
return textGame ? "text" : "image";
};
const saveTest = () => {
if (!(questions.length <= 0) && !(title === "")) {
const questionsToBeSaved = {
title: title,
owner: context.user.userID,
numberOfQuestions: questions.length,
typeOfTest: typeOfTest(),
questions: questions,
};
console.log(questionsToBeSaved);
axios
.post("http://localhost:3001/tests/", questionsToBeSaved)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
setQuestions([]);
setShowQuestions(false);
setTitle("");
} else {
console.log("No questions to save!");
}
if (!textGame) {
console.log("upload files to fileServer");
uploadFiles();
}
};
const validateQuestion = (questionObj) => {
if (!questionObj.question || !questionObj.answer) {
return false;
} else if ("" in questionObj.answers) {
return false;
} else {
return true;
}
};
const addQuestion = (question) => {
if (validateQuestion(question)) {
setQuestions(questions.concat(question));
setShowQuestions(true);
setDisplayInputAlert(false);
} else {
//console.log("invalid missing some fields");
setDisplayInputAlert(true);
}
};
const removeItem = (array, index) => {
console.log(array);
console.log(index);
const newArray = [];
array.forEach((value, i) => {
console.log(i);
if (!(index == i)) {
newArray.push(value);
}
});
return newArray;
};
const deleteQuestion = (event) => {
console.log(questions);
const index = event.currentTarget.value;
const newArray = removeItem(questions, index);
console.log(index);
console.log(newArray);
setQuestions(newArray);
if (newArray.length <= 0) {
setShowQuestions(false);
}
};
const displayInvalidinputAlert = () => {
return (
<Alert severity="info" style={{ backgroundColor: style.colors.yellow }}>
Unable to add questions make sure everything is filled out correctly!
</Alert>
);
};
const displayQuestions = () => {
const items = questions.map((value, index) => {
return (
<Grid item key={index}>
<Paper
key={index}
elevation={5}
style={{
backgroundColor: style.colors.yellow,
padding: "20px 20px 20px 20px",
}}
>
<h3>
{" "}
{index + 1}) {value.question}{" "}
</h3>
<p> a) {value.answers[0]} </p>
<p> b) {value.answers[1]} </p>
<p> c) {value.answers[2]} </p>
<p> d) {value.answers[3]} </p>
<p> Correct Answer: {value.answer} </p>
<Button
variant="contained"
onClick={deleteQuestion}
value={index}
style={{ backgroundColor: style.colors.pink }}
>
Delete
</Button>
</Paper>
</Grid>
);
});
return (
<Paper elevation={5} style={{ backgroundColor: style.colors.yellow }}>
<Grid
container
spacing={3}
direction="row"
justify="center"
alignItems="center"
style={{ padding: "20px 20px 20px 20px" }}
>
{items}
</Grid>
</Paper>
);
};
const playImageGame = () => {
setTextGame(false);
setDisplayGameChoice(false);
};
const playTextGame = () => {
setTextGame(true);
setDisplayGameChoice(false);
};
const imageOrText = () => {
return <ImgOrTxt startImage={playImageGame} startText={playTextGame} />;
};
const createChoosenGame = () => {
if (!displayGameChoice) {
if (textGame) {
return <CreateForm addQuestion={addQuestion} saveTest={saveTest} />;
} else {
return (
<CreateImageForm
addQuestion={addQuestion}
saveTest={saveTest}
setAnswerImages={setAnswerImages}
/>
);
}
}
};
const loggedInView = () => {
return (
<Paper elevation={5} style={{ backgroundColor: style.colors.yellow }}>
<Grid
container
direction="column"
justify="center"
alignItems="center"
style={{ padding: "20px 20px 20px 20px" }}
>
<ThemeProvider theme={theme}>
<TextField
variant="outlined"
label="Game Title"
style={{ width: "65vw" }}
onChange={(event) => {
setTitle(event.target.value);
}}
inputProps={{ style: { color: style.colors.pink } }}
/>{" "}
</ThemeProvider>
<br />
{displayGameChoice && imageOrText()}
{createChoosenGame()}
</Grid>
</Paper>
);
};
const loggedOutView = () => {
return (
<Grid item>
<Alert
severity="info"
style={{ backgroundColor: style.colors.yellow, width: "80vw" }}
>
Please Login to create a game!
</Alert>
</Grid>
);
};
const checkLogin = () => {
if (context.loggedIn) {
return loggedInView();
} else {
return loggedOutView();
}
};
return (
<Layout>
<Grid
container
direction="column"
justify="center"
alignItems="center"
style={{ padding: "20px 20px 20px 20px" }}
>
{checkLogin()}
<br />
<p></p>
{!context.loggedIn ? (
<ResponsiveImage src={QuestionImg} width={300} height={200} />
) : null}
{displayInputAlert && displayInvalidinputAlert()}
{showQuestions && displayQuestions()}
<div style={{ height: "60vh" }} />
</Grid>
</Layout>
);
}
export default Create;
|
import {FETCH_DATA_SUCCESS} from '../actionTypes'
export default function dataReducer(state = [], action) {
const {type} = action;
switch (type) {
case FETCH_DATA_SUCCESS: {
const {result} = action;
return result;
}
default: {
return state;
}
}
}
|
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import App from 'app/App'
import * as serviceWorker from 'serviceWorker'
import { persistor, store } from 'app/Store'
import { Provider } from 'react-redux'
import { Switch, BrowserRouter, withRouter } from 'react-router-dom'
import ApplicationRoutes from 'app/Routes'
import AppRoute from 'app/AppRoute'
import { PersistGate } from 'redux-persist/lib/integration/react'
import theme from '@santander/everest-ui/lib/theme'
import { ThemeProvider } from 'styled-components'
import '@santander/everest-ui/src/fonts.css'
import '@santander/everest-ui/src/icons.css'
import 'assets/stylesheets/main.scss'
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
import Spinner from 'app/shared/components/loader/SpinnerContainer'
// Own toast
// import { ToastContainer} from 'react-toastify';
import 'app/config/AxiosConfig'
const { Routes } = ApplicationRoutes
const BodyComponent = ({ location: { pathname } }) => (
<Switch>
{Routes.map((route) => (
<AppRoute key={route.key} {...route} />
))}
</Switch>
)
BodyComponent.propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string
})
}
const Body = withRouter(BodyComponent)
const estiloColor = {
height: '100%',
margin: '0 auto'
}
ReactDOM.render(
<Provider store={store}>
<PersistGate persistor={persistor}>
<BrowserRouter>
<ThemeProvider theme={theme}>
<div style={estiloColor}>
<Spinner />
<App>
<Body key='body' />
</App>
</div>
</ThemeProvider>
</BrowserRouter>
</PersistGate>
</Provider>,
document.getElementById('root')
)
serviceWorker.unregister()
|
/////////////////////////////////////////////////////////////////
// Sýnidæmi í Tölvugrafík
// Vörpunarfylki búið til í JS og sent yfir til
// hnútalitara, sem margfaldar (þ.e. varpar)
//
// Hjálmtýr Hafsteinsson, febrúar 2019
/////////////////////////////////////////////////////////////////
var canvas;
var gl;
var NumVertices = 36;
var NumBody = 6;
var NumTail = 3;
var bur = [];
var fiskur = [];
var colors = [];
var s = [];
var burBuffer;
var fiskBuffer;
var rotTail = 0.0; // Snúningshorn sporðs
var incTail = 0.01;
var rotUggi1 = 0.0;
var incUggi1 = 0.1;
var xAxis = 0;
var yAxis = 1;
var zAxis = 2;
var axis = 0;
var movement = false; // Do we rotate?
var spinX = 0;
var spinY = 0;
var origX;
var origY;
var setAlign = true;
var colorLoc;
var matrixLoc;
var vPosition;
window.onload = function init()
{
canvas = document.getElementById( "gl-canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
colorCube();
fertices();
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 0.9, 0.9, 0.9, 1.0 );
gl.enable(gl.DEPTH_TEST);
//
// Load shaders and initialize attribute buffers
//
var program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
burBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, burBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(bur), gl.STATIC_DRAW );
fiskBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, fiskBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(fiskur), gl.STATIC_DRAW );
vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 4, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
matrixLoc = gl.getUniformLocation( program, "mv" );
colorLoc = gl.getUniformLocation( program, "color" );
pLoc = gl.getUniformLocation( program, "projection" );
var proj = ortho( -1.0, 1.0, -1.0, 1.0, -2.0, 2.0 );
gl.uniformMatrix4fv(pLoc, false, flatten(proj));
//event listeners for mouse
canvas.addEventListener("mousedown", function(e){
movement = true;
origX = e.offsetX;
origY = e.offsetY;
e.preventDefault(); // Disable drag and drop
} );
canvas.addEventListener("mouseup", function(e){
movement = false;
} );
canvas.addEventListener("mousemove", function(e){
if(movement) {
spinY = ( spinY + (e.offsetX - origX) ) % 360;
spinX = ( spinX + (e.offsetY - origY) ) % 360;
origX = e.offsetX;
origY = e.offsetY;
}
} );
render();
}
function colorCube()
{
quad( 1, 0, 3, 2 );
quad( 2, 3, 7, 6 );
quad( 3, 0, 4, 7 );
quad( 6, 5, 1, 2 );
quad( 4, 5, 6, 7 );
quad( 5, 4, 0, 1 );
}
function quad(a, b, c, d)
{
var vertices = [
vec3( -0.5, -0.5, 0.5 ),
vec3( -0.5, 0.5, 0.5 ),
vec3( 0.5, 0.5, 0.5 ),
vec3( 0.5, -0.5, 0.5 ),
vec3( -0.5, -0.5, -0.5 ),
vec3( -0.5, 0.5, -0.5 ),
vec3( 0.5, 0.5, -0.5 ),
vec3( 0.5, -0.5, -0.5 )
];
var indices = [ a, b, c, a, c, d ];
for ( var i = 0; i < indices.length; ++i ) {
bur.push( vertices[indices[i]] );
}
}
// Fish vertices
function fertices(){
var vertices = [
// líkami (spjald)
vec4( -0.5, -0.1, 0.0, 1.0 ),
vec4( 0.5, -0.1, 0.0, 1.0 ),
vec4( -0.5, 0.1, 0.0, 1.0 ),
vec4( -0.5, 0.1, 0.0, 1.0 ),
vec4( 0.5, -0.1, 0.0, 1.0 ),
vec4( 0.5, 0.1, 0.0, 1.0 ),
// sporður (þríhyrningur)
vec4( -0.5, 0.0, 0.0, 1.0 ),
vec4( -1.0, 0.15, 0.0, 1.0 ),
vec4( -1.0, -0.15, 0.0, 1.0 ),
// uggi1
vec4( 0.02, 0.02, 0.0, 1.0 ),
vec4( 0.0, -0.05, 0.0, 1.0 ),
vec4( 0.04, -0.05, 0.0, 1.0 ),
// uggi2
vec4( 0.02, 0.02, 0.0, 1.0 ),
vec4( 0.0, -0.05, 0.0, 1.0 ),
vec4( 0.04, -0.05, 0.0, 1.0 ),
];
for(var i = 0; i<vertices.length ; i++){
fiskur.push(vertices[i]);
}
}
function fiskabur(mv){
gl.bindBuffer( gl.ARRAY_BUFFER, burBuffer );
gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 );
gl.uniform4fv( colorLoc, vec4(0.0, 0.0, 0.0, 1.0) );
var mv1 = mat4();
mv1 = mult( mv, translate(0.0, 1, -1.0));
mv1 = mult( mv1, scalem(2, 0.1, 0.1));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv1));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv2 = mat4();
mv2 = mult( mv, translate(0.0, -1, -1.0));
mv2 = mult( mv2, scalem(2, 0.1, 0.1));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv2));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv3 = mat4();
mv3 = mult( mv, translate(0.0, 1, 1.0));
mv3 = mult( mv3, scalem(2, 0.1, 0.1));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv3));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv4 = mat4();
mv4 = mult( mv, translate(0.0, -1, 1.0));
mv4 = mult( mv4, scalem(2, 0.1, 0.1));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv4));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv5 = mat4();
mv5 = mult( mv, translate(0.95, -1, 0.0));
mv5 = mult( mv5, scalem(0.1, 0.1, 2));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv5));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv6 = mat4();
mv6 = mult( mv, translate(-0.95, -1, 0.0));
mv6 = mult( mv6, scalem(0.1, 0.1, 2));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv6));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv7 = mat4();
mv7 = mult( mv, translate(-0.95, 1, 0.0));
mv7 = mult( mv7, scalem(0.1, 0.1, 2));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv7));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv8 = mat4();
mv8 = mult( mv, translate(0.95, 1, 0.0));
mv8 = mult( mv8, scalem(0.1, 0.1, 2));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv8));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv9 = mat4();
mv9 = mult( mv, translate(0.95, 0.0, 1.0));
mv9 = mult( mv9, scalem(0.1, 2, 0.1));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv9));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv10 = mat4();
mv10 = mult( mv, translate(0.95, 0.0, -1.0));
mv10 = mult( mv10, scalem(0.1, 2, 0.1));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv10));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv11 = mat4();
mv11 = mult( mv, translate(-0.95, 0.0, -1.0));
mv11 = mult( mv11, scalem(0.1, 2, 0.1));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv11));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
var mv12 = mat4();
mv12 = mult( mv, translate(-0.95, 0.0, 1.0));
mv12 = mult( mv12, scalem(0.1, 2, 0.1));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv12));
gl.drawArrays( gl.TRIANGLES, 0, NumVertices);
}
//////////////
//FISH STUFF//
//////////////
function fish(mv, v){
gl.bindBuffer( gl.ARRAY_BUFFER, fiskBuffer );
gl.vertexAttribPointer( vPosition, 4, gl.FLOAT, false, 0, 0 )
rotTail += incTail;
if( rotTail > 3.5 || rotTail < -3.5 )
incTail *= -1
rotUggi1 += incUggi1;
if( rotUggi1 > 25.5 || rotUggi1 < 0 )
incUggi1 *= -1
// Teikna líkama fisks (án snúnings)
gl.uniform4fv( colorLoc, v )
mv1 = mat4();
mv1 = mult(mv, scalem(0.1,0.2,1.0));
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv1));
gl.drawArrays( gl.TRIANGLES, 0, NumBody )
// Teikna sporð og snúa honum
gl.uniform4fv( colorLoc, vec4(1.0, 0.0, 0.0, 1.0) )
var mv2 = mat4();
mv2 = mult( mv1, translate ( -0.5, 0.0, 0.0 ) );
mv2 = mult( mv2, rotateY( rotTail ) );
mv2= mult( mv2, translate ( 0.5, 0.0, 0.0 ) )
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv2));
gl.drawArrays( gl.TRIANGLES, NumBody, NumTail )
//uggi1
var mv3 = mat4();
mv3 = mult( mv, translate ( -0.05, 0.0, 0.0 ) );
mv3 = mult( mv3, rotateX( rotUggi1 ) );
mv3= mult( mv3, translate ( 0.05, 0.0, 0.0 ) );
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv3));
gl.drawArrays( gl.TRIANGLES, NumBody+NumTail, 3 )
//uggi2
var mv3 = mat4();
mv3 = mult( mv, translate ( -0.05, 0.0, 0.0 ) );
mv3 = mult( mv3, rotateX( -rotUggi1 ) );
mv3= mult( mv3, translate ( 0.05, 0.0, 0.0 ) );
gl.uniformMatrix4fv(matrixLoc, false, flatten(mv3));
gl.drawArrays( gl.TRIANGLES, NumBody+NumTail, 3 )
}
// object to remember fish spawnpoints
var fishSpawn = {};
// if fish has spawned or not
var set = false;
var vel = [];
var fishMvMatrix =[];
var maxX;
var maxY;
var maxZ;
function setFish(mv) {
for(var i = 0; i < 20; i++){
var mv1 = mat4();
var x = (Math.random()*(8 - (-8)+1) + (-8))/10;
var y = (Math.random()*(8 - (-8)+1) + (-8))/10;
var z = (Math.random()*(8 - (-8)+1) + (-8))/10;
mv1 = mult(mv, translate(x,y,z));
fishSpawn[i] = {x : x, y:y, z:z};
}
fishMoveInit();
maxSpeedInit();
set = true;
}
function fishMoveInit(){
for(var i = 0; i< 20; i++){
var attX = Math.random();
if(attX > 0.5) attX = -1;
else attX = 1;
var attY = Math.random();
if(attY > 0.5) attY = -1;
else attX = 1;
var attZ = Math.random();
if(attZ > 0.5) attZ = -1;
else attZ = 1;
velX = (Math.random()*(10 - 5 + 1)+5)/10000;
velY = (Math.random()*(10- 5 + 1)+5)/10000;
velZ = (Math.random()*(2- 0.5 + 1)+0.5)/10000;
vel[i] = { x : velX*attX, y : velY * attY, z : velZ*attZ};
}
}
function moveFish(mv) {
for(var i = 0; i<20; i++){
fishMvMatrix[i] = mult(mv, translate(fishSpawn[i].x,fishSpawn[i].y,fishSpawn[i].z));
var s = align(fishSpawn[i]);
if(setAlign === true){
vel[i].x = s.x;
vel[i].y = s.y;
vel[i].z = s.z;
}
if(vel[i].x < 0) fishMvMatrix[i] = mult(fishMvMatrix[i], rotateY(180));
fishSpawn[i].x+=vel[i].x;
fishSpawn[i].y+=vel[i].y;
fishSpawn[i].z+=vel[i].z;
}
fishColllision();
}
function fishColllision(){
for(var i = 0; i < 20; i++){
if(fishSpawn[i].x > 0.9)
fishSpawn[i].x = -0.9;
else if(fishSpawn[i].x < -0.9)
fishSpawn[i].x = 0.9;
if(fishSpawn[i].y > 0.9)
fishSpawn[i].y = -0.9;
else if(fishSpawn[i].y < -0.9)
fishSpawn[i].y = 0.9;
if(fishSpawn[i].z > 0.9)
fishSpawn[i].z = -0.9;
else if(fishSpawn[i].z < -0.9)
fishSpawn[i].z = 0.9;
}
}
function drawFish(mv){
moveFish(mv);
/* fish(fishMvMatrix[0],vec4(0.4,0.5,0.1,1.0));
fish(fishMvMatrix[1],vec4(1.0,0.5,0.1,1.0));
fish(fishMvMatrix[2],vec4(1.0,1.0,0.1,1.0));
fish(fishMvMatrix[3],vec4(0.0,1.0,0.1,1.0));
fish(fishMvMatrix[4],vec4(0.5,1.0,0.1,1.0));
fish(fishMvMatrix[5],vec4(0.5,1.0,0.5,1.0));
fish(fishMvMatrix[6],vec4(0.0,0.2,1.0,1.0));
fish(fishMvMatrix[7],vec4(0.5,0.0,1.0,1.0));
fish(fishMvMatrix[8],vec4(0.5,0.0,1.0,1.0));
fish(fishMvMatrix[9],vec4(0.0,1.0,1.0,1.0)); */
for(var i = 0; i <20; i++){
fish(fishMvMatrix[i],vec4(1.0,0.5,0.1,1.0));
}
}
function maxSpeedInit(){
maxX = 0.003;
maxY = 0.0007;
maxZ = 0.0005;
return;
}
///////////////////
//FISH STUFF ENDS//
///////////////////
function distance(x, y, z, sx, sy,sz){
var a = Math.pow((sx-x),2);
var b = Math.pow((sy-y),2);
var c = Math.pow((sz-z),2);
var dist = Math.sqrt(a+b+c);
return dist;
}
function distance1(x,sz){
var a = Math.pow((sz-x),2);
var dist = Math.sqrt(a);
return dist;
}
//alignment tilraun
var totalGroup = 0;
function align(f) {
var avg ={x:0,y:0,z:0};
var percRad = 0.8;
for(var j = 0; j<10; j++){
var d = distance(f.x, f.y, f.z,
fishSpawn[j].x, fishSpawn[j].y, fishSpawn[j].z);
if(d < percRad ){
avg.x=fishSpawn[j].x;
avg.y=fishSpawn[j].y;
avg.z=fishSpawn[j].z;
totalGroup++;
}
}
if(totalGroup > 0){
avg.x/=totalGroup;
avg.y/=totalGroup;
avg.z/=totalGroup;
avg.x += maxX;
avg.y += maxY;
avg.z += maxZ;
}
return avg;
}
function render()
{
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
var scale = mult(mat4(), scalem(0.5,0.3,0.5));
var mv = mat4();
mv = mult( mv, scale);
mv = mult( mv, rotateX(spinX) );
mv = mult( mv, rotateY(spinY) );
if(set === false)
setFish(mv);
fiskabur(mv);
drawFish(mv);
requestAnimFrame( render );
}
|
requirejs.config({
base:"js",
paths:{
'jquery':'lib/jquery.min'
}
});
require(['jquery','app/gotop','app/fullwater','app/lazy','app/lunbo']),function($,gotop,fullwater,lazy,lunbo){
};
|
import React from 'react';
import L from 'leaflet';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import 'leaflet-draw';
import './leaflet.css';
import './leaflet-draw.css';
const TILES_PROVIDER = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
const MAP_LICENCE = 'https://openstreetmap.org';
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
iconUrl: require('leaflet/dist/images/marker-icon.png'),
shadowUrl: require('leaflet/dist/images/marker-shadow.png')
});
const layersFromDb = [
{
id: 1,
type: 'Feature',
surface: '7910.22 ha',
style: {
color: '#234C5F',
fillColor: '#234C5F',
weight: 0.5,
fillOpacity: 0.8
},
geometry: {
type: 'Polygon',
coordinates: [
[
[25.418785, 45.656027],
[25.418785, 45.716113],
[25.568372, 45.716113],
[25.568372, 45.656027],
[25.418785, 45.656027]
]
]
}
},
{
id: 2,
type: 'Feature',
surface: '16239.11 ha',
style: {
color: '#234C5F',
fillColor: '#234C5F',
weight: 0.5,
fillOpacity: 1
},
geometry: {
type: 'Polygon',
coordinates: [
[
[25.649895, 45.852198],
[25.660109, 45.755599],
[25.81196, 45.76704],
[25.844162, 45.808872],
[25.72703, 45.902702],
[25.649895, 45.852198]
]
]
}
}
];
export default class Map extends React.Component {
state = {
layers: [],
layersFromDb: layersFromDb
};
baseGeoJsonLayer = null;
componentDidMount() {
const { layersFromDb } = this.state;
this.map = L.map('map', {
center: [45.65, 25.6],
zoom: 10,
maxZoom: 20,
minZoom: 2,
zoomAnimation: true,
markerZoomAnimation: true,
fadeAnimation: true,
detectRetina: true,
scrollWheelZoom: true,
touchZoom: true,
doubleClickZoom: true,
dragging: true
});
L.tileLayer(TILES_PROVIDER, {
attribution: `Map data © <a href="${MAP_LICENCE}">OpenStreetMap</a>`,
subdomains: ['a', 'b', 'c']
}).addTo(this.map);
const newMarker = L.marker([45.65, 25.6], { draggable: true })
.addTo(this.map)
.bindPopup('A popup on marker click.<br /> Add another marker!')
.openPopup()
.on('dragend', () => {
const { lat, lng } = this.parseLatLng(newMarker.getLatLng());
alert([lat[1], lng[0]]);
});
const drawnItems = new L.FeatureGroup();
this.map.addLayer(drawnItems);
const dbLayers = this.getBaseGeoJsonLayer(layersFromDb);
dbLayers.map((layer) => drawnItems.addLayer(layer));
const drawControl = new L.Control.Draw({
position: 'topleft',
draw: {
circle: false,
circlemarker: false
},
edit: {
featureGroup: drawnItems,
remove: true
}
});
this.map.addControl(drawControl);
this.map.on(L.Draw.Event.CREATED, (e) => {
const type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer
.on('click', ({ latlng }) =>
layer.bindPopup(`Coordinates:<br /> [${latlng.lat}, ${latlng.lng}]`)
)
.on('dragend', ({ latlng }) => console.log([latlng.lat, latlng.lng]));
}
drawnItems.addLayer(layer);
const json = drawnItems.toGeoJSON();
let shapeArea;
if (type !== 'marker') {
shapeArea = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]);
shapeArea = L.GeometryUtil.readableArea(shapeArea, true, { ha: 2 });
layer.on('click', () => layer.bindPopup(`Area: ${shapeArea}`));
}
this.handleAddLayer(type, shapeArea, json);
});
this.map.on(L.Draw.Event.EDITED, (e) => {
const layers = e.layers;
layers.eachLayer((layer) => {
drawnItems.addLayer(layer);
const json = drawnItems.toGeoJSON();
if (layer.feature) {
this.handleEditLayer(layer.feature.id, json);
}
});
});
this.map.on('click', (event) => {
this.handleAddMarker(event);
});
}
/**
* add overlay layer to map
* @param {Object} featureCollection
*/
getBaseGeoJsonLayer = (featureCollection) => {
this.baseGeoJsonLayer = L.geoJSON(featureCollection, {
style: function(feature) {
return feature.style;
},
onEachFeature: function(feature, layer) {
layer.on('click', () =>
layer.bindPopup(`Area: ${layer.feature.surface}`)
);
if (layer.getLayers) {
layer.getLayers().forEach(function(l) {
featureCollection.addLayer(l);
});
}
}
}).addTo(this.map);
const layers = this.baseGeoJsonLayer.getLayers();
if (layers.length > 0) {
const bounds = this.baseGeoJsonLayer.getBounds();
this.map.fitBounds(bounds, {
animate: false
});
}
return layers;
};
/**
*
* @param {string} latLng
* @return {{lat: string[], lng: string[]}}
*/
parseLatLng = (latLng) => {
const coordinates = String(latLng).split(',');
const lat = coordinates[0].split('(');
const lng = coordinates[1].split(')');
return { lat, lng };
};
render() {
return <Container className="min-vh-100" id="map"></Container>;
}
/**
* Handle add pin
* @param {Object} event
*/
handleAddMarker = (event) => {
const { lat, lng } = this.parseLatLng(event.latlng.toString());
};
/**
* Handle add layer
* @param {String} type
* @param {String} shapeArea
* @param {Object} json
*/
handleAddLayer = (type, shapeArea, json) => {
const { layers } = this.state;
const id = Math.floor(Math.random() * 500 + 1);
const newJson = json.features.map((feature) =>
!feature.id
? {
id,
type: feature.type,
surface: shapeArea,
geometry: feature.geometry
}
: feature
);
const newLayers = [newJson, ...layers];
this.setState({ layers: newLayers, layersFromDb: newJson });
};
/**
* Handle edit layer
* @param {String} id
* @param {Object} json
*/
handleEditLayer = (id, json) => {
const newJson = id
? json.features.map((feature) =>
feature.id === id ? { id, ...feature } : feature
)
: json;
this.setState({ layersFromDb: newJson });
};
}
|
import React from "react";
import ReactDOM from 'react-dom'
import { render, fireEvent, cleanup } from "@testing-library/react";
import Form from "../Form";
afterEach(cleanup)
it("renders without crashing", () => {
const div = document.createElement('div')
ReactDOM.render(<Form />, div)
})
it("checks the placeholder text is there", () => {
const { queryByPlaceholderText, } = render(<Form />);
expect(queryByPlaceholderText('Add a new task')).toBeTruthy()
})
it("checks the button is there", () => {
const { queryAllByTestId, } = render(<Form />);
expect(queryAllByTestId('app__button')).toBeTruthy()
})
|
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { orange } from 'kitsu/constants/colors';
import { StyledText } from 'kitsu/components/StyledText';
import { styles } from './styles';
export const Pill = ({ color, label }) => (
<View style={[styles.pill, { backgroundColor: color }]}>
<StyledText color="light" size="xsmall">{label}</StyledText>
</View>
);
Pill.propTypes = {
color: PropTypes.string,
label: PropTypes.string,
};
Pill.defaultProps = {
color: orange,
label: '',
};
|
import data from "./data";
const listSize = 100;
Page({
data : {
list0: []
, list1: []
, list2: []
}
, onLoad(){
this.listStarts = {};
this.setCurrent("list1");
}
, setCurrent(currentListId){
let changedData = {};
let currentListIndex = parseInt(currentListId.substring(4));
let previousListId = "list" + ((currentListIndex - 1 + 3) % 3);
let nextListId = "list" + ((currentListIndex + 1 + 3) % 3);
let currentStart = this.listStarts[currentListId];
if(!currentStart){
currentStart = 0;
this.listStarts[currentListId] = currentStart;
let currentData = data.next(currentStart, listSize);
changedData[currentListId] = currentData;
}
this.setData(changedData);
}
});
|
var template = require("./outer.handlebars");
import {
minhaFuncaoQueDefineTitle
} from './lib.js'
export function MeuApp() {
var div = document.createElement('div');
div.innerHTML = template({
segundoNivel: "Segundo nível!",
title: minhaFuncaoQueDefineTitle()
});
document.body.appendChild(div);
$("#App").innerHTML = "Meu inner html";
}
|
/*
#pragma strict
var playerWeapon: PlayerWeaponControl;
var meleeScript : PlayerMelee;
var animator : Animator;
var camScript : CamScript;
var alive : boolean;
var inControl : boolean;
var camTrans : Transform;
var grounded : boolean;
var groundContact : boolean;
var reqContactTime : float;
var contactTime : float;
var velocity : float;
var maxSlope : float;
var moveSpeed : float;
var maxVelocityChange : float;
var movementMultiplyer : float;
var velocityDenom : float;
var lookPoint : Vector3;
var lookTime : float;
var jumpHeight : float;
var contextLookPoint : Vector3;
/*
function Start ()
{
// camTrans = GameObject.Find ("CamObj").transform;
// camScript = GameObject.Find ("CamObj").GetComponent (CamScript);
velocityDenom = moveSpeed;
}
function Update ()
{
// RotationFunc ();
if (alive)
{
RotationFunc ();
}
if (alive && inControl)
{
GroundingFunc ();
MovementUpdate ();
AnimationFunc ();
}
// Debug.Log (rigidbody.velocity.magnitude);
}
function OnTriggerEnter (col : Collider)
{
// Debug.Log (col.name);
if (col.gameObject.tag == "ContextSpot")
{
camScript.contextAvailable = true;
meleeScript.canAttack = false;
var contextScript : ContextSpotScript;
contextScript = col.transform.parent.GetComponent (ContextSpotScript);
camScript.newTargPos = contextScript.camPosV3;
camScript.newTargRot = contextScript.camRotV3;
contextLookPoint = contextScript.newLookPoint;
}
}
function OnTriggerExit ()
{
camScript.contextAvailable = false;
meleeScript.canAttack = true;
camScript.newTargPos = Vector3.zero;
camScript.newTargRot = Quaternion (0,0,0,0);;
}
function FixedUpdate ()
{
if (alive && inControl)
{
MovementFixed ();
}
}
function RotationFunc ()
{
var targQuatRelPos = lookPoint - transform.position;
var targQuat = Quaternion.LookRotation (targQuatRelPos);
targQuat = targQuat * Quaternion.Euler (0,0,0);
targQuat.eulerAngles.x = 0;
targQuat.eulerAngles.z = 0;
transform.rotation = Quaternion.Slerp (transform.rotation, targQuat, Time.deltaTime / lookTime);
}
function MovementUpdate ()
{
if (Input.GetButtonDown ("Jump") && grounded)
{
// rigidbody.velocity.y += jumpVel;
rigidbody.velocity.y = Mathf.Sqrt (2 * Mathf.Abs (Physics.gravity.magnitude) * jumpHeight);
}
}
function MovementFixed ()
{
if (grounded)
{
var targetVelocity : Vector3;
targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity = Vector3.ClampMagnitude (targetVelocity, 1);
targetVelocity = camTrans.TransformDirection(targetVelocity);
targetVelocity *= moveSpeed;
targetVelocity *= movementMultiplyer;
var moveVelocity : Vector3;
var moveVelocityChange : Vector3;
moveVelocity = rigidbody.velocity;
moveVelocityChange = (targetVelocity - moveVelocity);
moveVelocityChange.x = Mathf.Clamp(moveVelocityChange.x, -maxVelocityChange, maxVelocityChange);
moveVelocityChange.z = Mathf.Clamp(moveVelocityChange.z, -maxVelocityChange, maxVelocityChange);
moveVelocityChange.y = 0;
rigidbody.AddForce (moveVelocityChange, ForceMode.VelocityChange);
}
}
function GroundingFunc ()
{
if (groundContact)
{
contactTime = reqContactTime;
grounded = true;
// jumpReady = true;
}
else
{
contactTime -= Time.deltaTime;
if (contactTime <= 0)
{
grounded = false;
}
}
// Debug.Log (groundContact);
}
function OnCollisionStay (collision : Collision)
{
for(var contact : ContactPoint in collision.contacts)
{
// Debug.Log (Vector3.Angle(contact.normal, Vector3.up));
if (Vector3.Angle(contact.normal, Vector3.up) < maxSlope)
{
groundContact = true;
}
}
}
function OnCollisionExit ()
{
groundContact = false;
}
function AnimationFunc ()
{
var horVel = rigidbody.velocity;
horVel.y = 0;
// var inputVector = Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical")).normalized;
var lookVelDif = Vector3.Angle (transform.forward, horVel.normalized);
// Debug.DrawRay (transform.position + Vector3.up, horVel.normalized * 5, Color.red);
// Debug.DrawRay (transform.position + Vector3.up, transform.forward * 5, Color.green);
animator.SetBool ("Grounded", grounded);
animator.SetFloat ("VelocityHor", (horVel / velocityDenom).magnitude);
animator.SetFloat ("LookVelDif", lookVelDif);
// Debug.Log (lookVelDif);
}
*/
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const InvitationToken_1 = require("./InvitationToken");
class InvitationCreate {
constructor(model) {
if (!model)
return;
this.firstName = model.firstName;
this.lastName = model.lastName;
this.fullName = model.firstName + ' ' + model.lastName;
this.email = model.email;
this.userId = model.userId;
this.productId = model.productId;
this.token = model.token && new InvitationToken_1.default(model.token);
}
}
Object.seal(InvitationCreate);
exports.default = InvitationCreate;
|
#target Illustrator
if (app.documents.length > 0) {
mySelection = activeDocument.selection;
if (mySelection.length > 0) {
var doc = app.activeDocument; //current document
var sel = doc.selection; //current slection
var sl = sel.length; //number of selected objects
for (var i = 0; i < sl; i++) {
var pgitem = sel[i];
if (pgitem.typename === "CompoundPathItem") {
pgitem = sel[i].pathItems[0];
}
var currentstrokewidth;
var newstrokewidth;
currentstrokewidth = pgitem.strokeWidth;
if (currentstrokewidth <= 0.1) {
newstrokewidth = currentstrokewidth - 0.01;
} else {
newstrokewidth = currentstrokewidth - 0.1;
}
if (newstrokewidth <= 0) {
newstrokewidth = 0.1;
}
pgitem.strokeWidth = newstrokewidth;
}
app.redraw();
} else {
alert("Nothing selected!");
}
}
|
appicenter.controller('AuctionCtrl', ['$scope', '$location', '$timeout', '$route', 'firebaseService', 'loginService', function($scope, $location, $timeout, $route, firebaseService, loginService) {
// make sure user is logged in
$scope.auth = loginService;
$scope.auth.$getCurrentUser().then(function(user) {
console.log(user);
if (!user) {
$location.path('/login');
}
else {
$scope.user = user;
}
});
// get the current auction's id from the scoreboard
var currentAuctionRef = firebaseService('/scoreboard/current_auction');
currentAuctionRef.$bind($scope, 'currentAuction').then(function() {
// reload page if current action id changes
currentAuctionRef.$on('change', function() {
$route.reload();
});
// get the current auction
var auctionsRef = firebaseService('/auctions');
var auctionRef = auctionsRef.$child($scope.currentAuction);
auctionRef.$bind($scope, 'auction').then(function() {
$scope.updateProgress();
});
});
$scope.updateProgress = function() {
var auction = $scope.auction;
var percent = (Date.now() - auction.start_time) / auction.duration * 100;
var time_remaining = (auction.duration - auction.duration * percent / 100) / 1000;
$scope.progress = {
percent: percent.toFixed(2) + '%',
time_remaining: Math.floor(time_remaining)
};
if (auction.start_time == 0) $scope.status = 0;
else if (time_remaining > 0) $scope.status = 1;
else if (time_remaining <= 0) $scope.status = 2;
$timeout(function() {
$scope.updateProgress();
}, 1000);
};
$scope.bid = function(amount) {
$scope.auction.current_price = amount;
$scope.auction.highest_bidder = $scope.user.email;
};
}]);
|
// if (typeof module === "undefined") module = {};
const ERC20ABI = [
{
constant: true,
inputs: [],
name: "name",
outputs: [
{
name: "",
type: "string",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
name: "_spender",
type: "address",
},
{
name: "_value",
type: "uint256",
},
],
name: "approve",
outputs: [
{
name: "",
type: "bool",
},
],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [],
name: "totalSupply",
outputs: [
{
name: "",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
name: "_from",
type: "address",
},
{
name: "_to",
type: "address",
},
{
name: "_value",
type: "uint256",
},
],
name: "transferFrom",
outputs: [
{
name: "",
type: "bool",
},
],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [],
name: "decimals",
outputs: [
{
name: "",
type: "uint8",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [
{
name: "_owner",
type: "address",
},
],
name: "balanceOf",
outputs: [
{
name: "balance",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "symbol",
outputs: [
{
name: "",
type: "string",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
name: "_to",
type: "address",
},
{
name: "_value",
type: "uint256",
},
],
name: "transfer",
outputs: [
{
name: "",
type: "bool",
},
],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [
{
name: "_owner",
type: "address",
},
{
name: "_spender",
type: "address",
},
],
name: "allowance",
outputs: [
{
name: "",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
payable: true,
stateMutability: "payable",
type: "fallback",
},
{
anonymous: false,
inputs: [
{
indexed: true,
name: "owner",
type: "address",
},
{
indexed: true,
name: "spender",
type: "address",
},
{
indexed: false,
name: "value",
type: "uint256",
},
],
name: "Approval",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
name: "from",
type: "address",
},
{
indexed: true,
name: "to",
type: "address",
},
{
indexed: false,
name: "value",
type: "uint256",
},
],
name: "Transfer",
type: "event",
},
];
const DAIABI = [
{
inputs: [
{
internalType: "uint256",
name: "chainId_",
type: "uint256",
},
],
payable: false,
stateMutability: "nonpayable",
type: "constructor",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "address",
name: "src",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "guy",
type: "address",
},
{
indexed: false,
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "Approval",
type: "event",
},
{
anonymous: true,
inputs: [
{
indexed: true,
internalType: "bytes4",
name: "sig",
type: "bytes4",
},
{
indexed: true,
internalType: "address",
name: "usr",
type: "address",
},
{
indexed: true,
internalType: "bytes32",
name: "arg1",
type: "bytes32",
},
{
indexed: true,
internalType: "bytes32",
name: "arg2",
type: "bytes32",
},
{
indexed: false,
internalType: "bytes",
name: "data",
type: "bytes",
},
],
name: "LogNote",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "address",
name: "src",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "dst",
type: "address",
},
{
indexed: false,
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "Transfer",
type: "event",
},
{
constant: true,
inputs: [],
name: "DOMAIN_SEPARATOR",
outputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "PERMIT_TYPEHASH",
outputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [
{
internalType: "address",
name: "",
type: "address",
},
{
internalType: "address",
name: "",
type: "address",
},
],
name: "allowance",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "usr",
type: "address",
},
{
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "approve",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [
{
internalType: "address",
name: "",
type: "address",
},
],
name: "balanceOf",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "usr",
type: "address",
},
{
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "burn",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [],
name: "decimals",
outputs: [
{
internalType: "uint8",
name: "",
type: "uint8",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "guy",
type: "address",
},
],
name: "deny",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "usr",
type: "address",
},
{
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "mint",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "src",
type: "address",
},
{
internalType: "address",
name: "dst",
type: "address",
},
{
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "move",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [],
name: "name",
outputs: [
{
internalType: "string",
name: "",
type: "string",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [
{
internalType: "address",
name: "",
type: "address",
},
],
name: "nonces",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "holder",
type: "address",
},
{
internalType: "address",
name: "spender",
type: "address",
},
{
internalType: "uint256",
name: "nonce",
type: "uint256",
},
{
internalType: "uint256",
name: "expiry",
type: "uint256",
},
{
internalType: "bool",
name: "allowed",
type: "bool",
},
{
internalType: "uint8",
name: "v",
type: "uint8",
},
{
internalType: "bytes32",
name: "r",
type: "bytes32",
},
{
internalType: "bytes32",
name: "s",
type: "bytes32",
},
],
name: "permit",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "usr",
type: "address",
},
{
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "pull",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "usr",
type: "address",
},
{
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "push",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "guy",
type: "address",
},
],
name: "rely",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [],
name: "symbol",
outputs: [
{
internalType: "string",
name: "",
type: "string",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [],
name: "totalSupply",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "dst",
type: "address",
},
{
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "transfer",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: false,
inputs: [
{
internalType: "address",
name: "src",
type: "address",
},
{
internalType: "address",
name: "dst",
type: "address",
},
{
internalType: "uint256",
name: "wad",
type: "uint256",
},
],
name: "transferFrom",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
payable: false,
stateMutability: "nonpayable",
type: "function",
},
{
constant: true,
inputs: [],
name: "version",
outputs: [
{
internalType: "string",
name: "",
type: "string",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
{
constant: true,
inputs: [
{
internalType: "address",
name: "",
type: "address",
},
],
name: "wards",
outputs: [
{
internalType: "uint256",
name: "",
type: "uint256",
},
],
payable: false,
stateMutability: "view",
type: "function",
},
];
const ISuperfluidABI = [
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "bytes32",
name: "agreementType",
type: "bytes32",
},
{
indexed: false,
internalType: "address",
name: "code",
type: "address",
},
],
name: "AgreementClassRegistered",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "bytes32",
name: "agreementType",
type: "bytes32",
},
{
indexed: false,
internalType: "address",
name: "code",
type: "address",
},
],
name: "AgreementClassUpdated",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
],
name: "AppRegistered",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "contract ISuperfluidGovernance",
name: "oldGov",
type: "address",
},
{
indexed: false,
internalType: "contract ISuperfluidGovernance",
name: "newGov",
type: "address",
},
],
name: "GovernanceReplaced",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
{
indexed: false,
internalType: "uint256",
name: "reason",
type: "uint256",
},
],
name: "Jail",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: false,
internalType: "contract ISuperTokenFactory",
name: "newFactory",
type: "address",
},
],
name: "SuperTokenFactoryUpdated",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperToken",
name: "token",
type: "address",
},
{
indexed: false,
internalType: "address",
name: "code",
type: "address",
},
],
name: "SuperTokenLogicUpdated",
type: "event",
},
{
inputs: [],
name: "getGovernance",
outputs: [
{
internalType: "contract ISuperfluidGovernance",
name: "governance",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidGovernance",
name: "newGov",
type: "address",
},
],
name: "replaceGovernance",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperAgreement",
name: "agreementClassLogic",
type: "address",
},
],
name: "registerAgreementClass",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperAgreement",
name: "agreementClassLogic",
type: "address",
},
],
name: "updateAgreementClass",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "bytes32",
name: "agreementType",
type: "bytes32",
},
],
name: "isAgreementTypeListed",
outputs: [
{
internalType: "bool",
name: "yes",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperAgreement",
name: "agreementClass",
type: "address",
},
],
name: "isAgreementClassListed",
outputs: [
{
internalType: "bool",
name: "yes",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "bytes32",
name: "agreementType",
type: "bytes32",
},
],
name: "getAgreementClass",
outputs: [
{
internalType: "contract ISuperAgreement",
name: "agreementClass",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "bitmap",
type: "uint256",
},
],
name: "mapAgreementClasses",
outputs: [
{
internalType: "contract ISuperAgreement[]",
name: "agreementClasses",
type: "address[]",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "bitmap",
type: "uint256",
},
{
internalType: "bytes32",
name: "agreementType",
type: "bytes32",
},
],
name: "addToAgreementClassesBitmap",
outputs: [
{
internalType: "uint256",
name: "newBitmap",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "bitmap",
type: "uint256",
},
{
internalType: "bytes32",
name: "agreementType",
type: "bytes32",
},
],
name: "removeFromAgreementClassesBitmap",
outputs: [
{
internalType: "uint256",
name: "newBitmap",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "getSuperTokenFactory",
outputs: [
{
internalType: "contract ISuperTokenFactory",
name: "factory",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "getSuperTokenFactoryLogic",
outputs: [
{
internalType: "address",
name: "logic",
type: "address",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperTokenFactory",
name: "newFactory",
type: "address",
},
],
name: "updateSuperTokenFactory",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperToken",
name: "token",
type: "address",
},
],
name: "updateSuperTokenLogic",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "configWord",
type: "uint256",
},
],
name: "registerApp",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "uint256",
name: "configWord",
type: "uint256",
},
{
internalType: "string",
name: "registrationKey",
type: "string",
},
],
name: "registerAppWithKey",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
],
name: "isApp",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
],
name: "getAppLevel",
outputs: [
{
internalType: "uint8",
name: "appLevel",
type: "uint8",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
],
name: "getAppManifest",
outputs: [
{
internalType: "bool",
name: "isSuperApp",
type: "bool",
},
{
internalType: "bool",
name: "isJailed",
type: "bool",
},
{
internalType: "uint256",
name: "noopMask",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
],
name: "isAppJailed",
outputs: [
{
internalType: "bool",
name: "isJail",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "targetApp",
type: "address",
},
],
name: "allowCompositeApp",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
{
internalType: "contract ISuperApp",
name: "targetApp",
type: "address",
},
],
name: "isCompositeAppAllowed",
outputs: [
{
internalType: "bool",
name: "isAppAllowed",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
{
internalType: "bytes",
name: "callData",
type: "bytes",
},
{
internalType: "bool",
name: "isTermination",
type: "bool",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "callAppBeforeCallback",
outputs: [
{
internalType: "bytes",
name: "cbdata",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
{
internalType: "bytes",
name: "callData",
type: "bytes",
},
{
internalType: "bool",
name: "isTermination",
type: "bool",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "callAppAfterCallback",
outputs: [
{
internalType: "bytes",
name: "appCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
{
internalType: "uint256",
name: "appAllowanceGranted",
type: "uint256",
},
{
internalType: "int256",
name: "appAllowanceUsed",
type: "int256",
},
{
internalType: "contract ISuperfluidToken",
name: "appAllowanceToken",
type: "address",
},
],
name: "appCallbackPush",
outputs: [
{
internalType: "bytes",
name: "appCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
{
internalType: "int256",
name: "appAllowanceUsedDelta",
type: "int256",
},
],
name: "appCallbackPop",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
{
internalType: "uint256",
name: "appAllowanceWantedMore",
type: "uint256",
},
{
internalType: "int256",
name: "appAllowanceUsedDelta",
type: "int256",
},
],
name: "ctxUseAllowance",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
{
internalType: "uint256",
name: "reason",
type: "uint256",
},
],
name: "jailApp",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperAgreement",
name: "agreementClass",
type: "address",
},
{
internalType: "bytes",
name: "callData",
type: "bytes",
},
{
internalType: "bytes",
name: "userData",
type: "bytes",
},
],
name: "callAgreement",
outputs: [
{
internalType: "bytes",
name: "returnedData",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
{
internalType: "bytes",
name: "callData",
type: "bytes",
},
],
name: "callAppAction",
outputs: [
{
internalType: "bytes",
name: "returnedData",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperAgreement",
name: "agreementClass",
type: "address",
},
{
internalType: "bytes",
name: "callData",
type: "bytes",
},
{
internalType: "bytes",
name: "userData",
type: "bytes",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "callAgreementWithContext",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
{
internalType: "bytes",
name: "returnedData",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperApp",
name: "app",
type: "address",
},
{
internalType: "bytes",
name: "callData",
type: "bytes",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "callAppActionWithContext",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "decodeCtx",
outputs: [
{
components: [
{
internalType: "uint8",
name: "appLevel",
type: "uint8",
},
{
internalType: "uint8",
name: "callType",
type: "uint8",
},
{
internalType: "uint256",
name: "timestamp",
type: "uint256",
},
{
internalType: "address",
name: "msgSender",
type: "address",
},
{
internalType: "bytes4",
name: "agreementSelector",
type: "bytes4",
},
{
internalType: "bytes",
name: "userData",
type: "bytes",
},
{
internalType: "uint256",
name: "appAllowanceGranted",
type: "uint256",
},
{
internalType: "uint256",
name: "appAllowanceWanted",
type: "uint256",
},
{
internalType: "int256",
name: "appAllowanceUsed",
type: "int256",
},
{
internalType: "address",
name: "appAddress",
type: "address",
},
{
internalType: "contract ISuperfluidToken",
name: "appAllowanceToken",
type: "address",
},
],
internalType: "struct ISuperfluid.Context",
name: "context",
type: "tuple",
},
],
stateMutability: "pure",
type: "function",
},
{
inputs: [
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "isCtxValid",
outputs: [
{
internalType: "bool",
name: "",
type: "bool",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
components: [
{
internalType: "uint32",
name: "operationType",
type: "uint32",
},
{
internalType: "address",
name: "target",
type: "address",
},
{
internalType: "bytes",
name: "data",
type: "bytes",
},
],
internalType: "struct ISuperfluid.Operation[]",
name: "operations",
type: "tuple[]",
},
],
name: "batchCall",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
components: [
{
internalType: "uint32",
name: "operationType",
type: "uint32",
},
{
internalType: "address",
name: "target",
type: "address",
},
{
internalType: "bytes",
name: "data",
type: "bytes",
},
],
internalType: "struct ISuperfluid.Operation[]",
name: "operations",
type: "tuple[]",
},
],
name: "forwardBatchCall",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
];
const IInstantDistributionAgreementV1ABI = [
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "publisher",
type: "address",
},
{
indexed: true,
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
indexed: false,
internalType: "bytes",
name: "userData",
type: "bytes",
},
],
name: "IndexCreated",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "publisher",
type: "address",
},
{
indexed: true,
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
indexed: false,
internalType: "address",
name: "subscriber",
type: "address",
},
{
indexed: false,
internalType: "bytes",
name: "userData",
type: "bytes",
},
],
name: "IndexSubscribed",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "publisher",
type: "address",
},
{
indexed: true,
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
indexed: false,
internalType: "address",
name: "subscriber",
type: "address",
},
{
indexed: false,
internalType: "uint128",
name: "units",
type: "uint128",
},
{
indexed: false,
internalType: "bytes",
name: "userData",
type: "bytes",
},
],
name: "IndexUnitsUpdated",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "publisher",
type: "address",
},
{
indexed: true,
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
indexed: false,
internalType: "address",
name: "subscriber",
type: "address",
},
{
indexed: false,
internalType: "bytes",
name: "userData",
type: "bytes",
},
],
name: "IndexUnsubscribed",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "publisher",
type: "address",
},
{
indexed: true,
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
indexed: false,
internalType: "uint128",
name: "oldIndexValue",
type: "uint128",
},
{
indexed: false,
internalType: "uint128",
name: "newIndexValue",
type: "uint128",
},
{
indexed: false,
internalType: "uint128",
name: "totalUnitsPending",
type: "uint128",
},
{
indexed: false,
internalType: "uint128",
name: "totalUnitsApproved",
type: "uint128",
},
{
indexed: false,
internalType: "bytes",
name: "userData",
type: "bytes",
},
],
name: "IndexUpdated",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "subscriber",
type: "address",
},
{
indexed: false,
internalType: "address",
name: "publisher",
type: "address",
},
{
indexed: false,
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
indexed: false,
internalType: "bytes",
name: "userData",
type: "bytes",
},
],
name: "SubscriptionApproved",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "subscriber",
type: "address",
},
{
indexed: false,
internalType: "address",
name: "publisher",
type: "address",
},
{
indexed: false,
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
indexed: false,
internalType: "bytes",
name: "userData",
type: "bytes",
},
],
name: "SubscriptionRevoked",
type: "event",
},
{
anonymous: false,
inputs: [
{
indexed: true,
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
indexed: true,
internalType: "address",
name: "subscriber",
type: "address",
},
{
indexed: false,
internalType: "address",
name: "publisher",
type: "address",
},
{
indexed: false,
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
indexed: false,
internalType: "uint128",
name: "units",
type: "uint128",
},
{
indexed: false,
internalType: "bytes",
name: "userData",
type: "bytes",
},
],
name: "SubscriptionUnitsUpdated",
type: "event",
},
{
inputs: [],
name: "initialize",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "address",
name: "account",
type: "address",
},
{
internalType: "uint256",
name: "time",
type: "uint256",
},
],
name: "realtimeBalanceOf",
outputs: [
{
internalType: "int256",
name: "dynamicBalance",
type: "int256",
},
{
internalType: "uint256",
name: "deposit",
type: "uint256",
},
{
internalType: "uint256",
name: "owedDeposit",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "agreementType",
outputs: [
{
internalType: "bytes32",
name: "",
type: "bytes32",
},
],
stateMutability: "pure",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "createIndex",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "address",
name: "publisher",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
],
name: "getIndex",
outputs: [
{
internalType: "bool",
name: "exist",
type: "bool",
},
{
internalType: "uint128",
name: "indexValue",
type: "uint128",
},
{
internalType: "uint128",
name: "totalUnitsApproved",
type: "uint128",
},
{
internalType: "uint128",
name: "totalUnitsPending",
type: "uint128",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "address",
name: "publisher",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "uint256",
name: "amount",
type: "uint256",
},
],
name: "calculateDistribution",
outputs: [
{
internalType: "uint256",
name: "actualAmount",
type: "uint256",
},
{
internalType: "uint128",
name: "newIndexValue",
type: "uint128",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "uint128",
name: "indexValue",
type: "uint128",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "updateIndex",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "uint256",
name: "amount",
type: "uint256",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "distribute",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "address",
name: "publisher",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "approveSubscription",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "address",
name: "publisher",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "revokeSubscription",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "address",
name: "subscriber",
type: "address",
},
{
internalType: "uint128",
name: "units",
type: "uint128",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "updateSubscription",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "address",
name: "publisher",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "address",
name: "subscriber",
type: "address",
},
],
name: "getSubscription",
outputs: [
{
internalType: "bool",
name: "exist",
type: "bool",
},
{
internalType: "bool",
name: "approved",
type: "bool",
},
{
internalType: "uint128",
name: "units",
type: "uint128",
},
{
internalType: "uint256",
name: "pendingDistribution",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "bytes32",
name: "agreementId",
type: "bytes32",
},
],
name: "getSubscriptionByID",
outputs: [
{
internalType: "address",
name: "publisher",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "bool",
name: "approved",
type: "bool",
},
{
internalType: "uint128",
name: "units",
type: "uint128",
},
{
internalType: "uint256",
name: "pendingDistribution",
type: "uint256",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "address",
name: "subscriber",
type: "address",
},
],
name: "listSubscriptions",
outputs: [
{
internalType: "address[]",
name: "publishers",
type: "address[]",
},
{
internalType: "uint32[]",
name: "indexIds",
type: "uint32[]",
},
{
internalType: "uint128[]",
name: "unitsList",
type: "uint128[]",
},
],
stateMutability: "view",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "address",
name: "publisher",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "address",
name: "subscriber",
type: "address",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "deleteSubscription",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{
internalType: "contract ISuperfluidToken",
name: "token",
type: "address",
},
{
internalType: "address",
name: "publisher",
type: "address",
},
{
internalType: "uint32",
name: "indexId",
type: "uint32",
},
{
internalType: "address",
name: "subscriber",
type: "address",
},
{
internalType: "bytes",
name: "ctx",
type: "bytes",
},
],
name: "claim",
outputs: [
{
internalType: "bytes",
name: "newCtx",
type: "bytes",
},
],
stateMutability: "nonpayable",
type: "function",
},
];
// Mainnet DAI, Optimism and Arbitrium Rollup Contracts with local addresses
module.exports = {
1: {
contracts: {
DAI: {
address: "0x6B175474E89094C44Da98b954EedeAC495271d0F",
abi: DAIABI,
},
UNI: {
address: "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
abi: ERC20ABI,
},
},
},
4: {
contracts: {
ISuperfluid: {
address: "0xeD5B5b32110c3Ded02a07c8b8e97513FAfb883B6",
abi: ISuperfluidABI,
},
IInstantDistributionAgreementV1: {
address: "0x32E0ecb72C1dDD92B007405F8102c1556624264D",
abi: IInstantDistributionAgreementV1ABI,
},
},
},
};
|
'use strict';
const _ = require('lodash');
const participation = require('./_channelParticipation');
module.exports = (channel, thresh, app, options) => new Promise((resolve, reject) => {
if (!app._ircClient.isInChannel(channel) || !app._ircClient.isOpInChannel(channel)) {
reject(new Error(`I am not in, or I am not an op in ${channel}`));
return;
}
options = _.isObject(options) ? options : {};
options.threshold = thresh;
return participation(channel, options)
.then(results => {
let actions = _.filter(results, v => app._ircClient.isInChannel(channel, v.nick) && !app._ircClient.isOpOrVoiceInChannel(channel, v.nick));
_(actions)
.chunk(4)
.each((v, k) => {
let args = ['MODE', channel, '+' + 'v'.repeat(v.length)].concat(_.map(v, 'nick'));
let callBack = () => app._ircClient.send.apply(null, args);
let callBackDelay = (1 + k) * 1000;
setTimeout(callBack, callBackDelay);
})
})
.then(() => {
resolve(`Voicing users with ${thresh} on ${channel}`);
});
});
|
import React, { Component } from "react";
import WeatherPage from "../component/WeatherPage";
import { connect } from "react-redux";
import { cityName, countryName, search } from "../redux/action/action";
class Weather extends Component {
handleCity = e => {
const city = e.target.value;
this.props.actionForSetCityName(city);
};
handleCountry = e => {
const country = e.target.value;
this.props.actionForSetCountryName(country);
};
handlerSearch = e => {
const value = {
city: this.props.cityName,
country: this.props.countryName
};
this.props.actionForSearch(value);
};
render() {
console.log("Data", this.props.error);
return (
<div>
<WeatherPage
handleCity={this.handleCity}
handleCountry={this.handleCountry}
handlerSearch={this.handlerSearch}
cityName={this.props.cityName}
weatherData={this.props.weatherData}
countryName={this.props.countryName}
isLoading={this.props.isLoading}
loaded={this.props.loaded}
error={this.props.error}
/>
</div>
);
}
}
const mapStateToProps = state => {
return {
cityName: state.reducer.cityName,
countryName: state.reducer.countryName,
detail: state.reducer.detail,
weatherData: state.reducer.weatherData,
isLoading: state.reducer.isLoading,
loaded: state.reducer.loaded,
error: state.reducer.error
};
};
const mapDispatchToProps = dispatch => {
return {
actionForSetCityName: value => dispatch(cityName(value)),
actionForSetCountryName: value => dispatch(countryName(value)),
actionForSearch: value => dispatch(search(value))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Weather);
|
import WhatWeDo from './WhatWeDo'
import MeetAmico from './MeetAmico'
import AmicoConnect from './AmicoConnect'
import DownloadApp from './DownloadApp'
export {
WhatWeDo,
MeetAmico,
AmicoConnect,
DownloadApp
}
|
import jwtFunctions from '../auth/jwt.js';
const authenticateJWT = async (req, res, next) => {
try {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1];
const user = jwtFunctions.decodeUser(token);
req.user = user;
next();
}
} catch (error) {
res.sendStatus(401);
}
};
export default authenticateJWT;
|
import React from 'react';
import {
createBottomTabNavigator,
createStackNavigator,
createSwitchNavigator
} from 'react-navigation'
import AddContactScreen from "./screens/AddContactScreen"
import ContactListScreen from "./screens/ContactListScreen"
import ContactDetailsScreen from "./screens/ContactDetailsScreen"
import LoginScreen from "./screens/LoginScreen"
import SettingsScreen from "./screens/SettingsScreen"
import {Ionicons} from 'react-native-vector-icons'
import {fetchUsers} from "./api"
import {Provider} from 'react-redux'
import store from "./redux/store"
/**
* In Stack Navigator, we keep all these routes and previous screens mounted in memory.
* Because we need to show the screen immediately when we swipe back.
*/
const ContactsTab = createStackNavigator({
AddContact: AddContactScreen,
ContactList: ContactListScreen,
ContactDetails: ContactDetailsScreen,
}, {
initialRouteName: 'ContactList',
})
ContactsTab.navigationOptions = {
tabBarIcon: ({focused, tintColor}) => (
<Ionicons
name={`ios-contacts${focused ? "" : "-outline"}`}
size={25}
color={tintColor}
/>
)
};
const MainNavigator = createBottomTabNavigator({
Contacts: ContactsTab,
Settings: SettingsScreen,
})
/**
* Composing Navigator
*/
const AppNavigator = createSwitchNavigator({
Main: MainNavigator,
Login: LoginScreen,
}, {
initialRouteName: 'Login',
})
export default class App extends React.Component {
state = {
contacts: null,
}
componentDidMount() {
this.getUsers()
}
getUsers = async () => {
const results = await fetchUsers()
this.setState({contacts: results})
}
render() {
return (
// Provider: let the app knows about the store
<Provider store={store}>
<AppNavigator/>
</Provider>
)
}
}
|
class StringUtils{
static equalIgnoreCase(a, b){
return typeof a === 'string' && typeof b === 'string'
? a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0
: a === b;
}
}
module.exports=StringUtils;
|
module.exports = {
itemFields: data => {
const itemFields = {
user: data.user,
item: data.item,
text: data.text,
price: data.price,
title: data.title,
itemImage: data.itemImage
};
return itemFields;
}
};
|
/**
* DomoGeeek v0.1
* https://github.com/ltoinel/domogeeek
*
* Copyright 2014 DomoGeeek
* Released under the Apache License 2.0 (Apache-2.0)
*
* @desc: SMTP Connector
* @author: ltoinel@free.fr
*/
var email = require("emailjs/email");
/**
* Send a text email using an SMTP server.
*
* @param phone The phone number.
* @param message The message to send.
*/
exports.send = function(config, from, to, cc , subject, text) {
console.info("Sending an Email to %s",to);
// Initialize the server instance
var server = email.server.connect({
user: config.username,
password: config.password,
host: config.host,
tls: config.tls ,
ssl : config.ssl
});
// Initialize the message to send
var message = {
text: text,
from: from,
to: to,
cc: cc,
subject: subject,
};
// Send the message and get a callback with an error or details of the message that was sent
server.send(message, function(err, message) {
if (err != null) {
console.error(err);
} else {
console.log("Email correctly sended");
}
});
return true;
}
|
var assert = require('assert');
var testDoc = 'file:///'+ __dirname +'/../../helpers/html/test.html';
describe('grunt-webdriverjs test', function () {
it('checks if title contains the search query', function(done) {
browser
.url(testDoc)
.getTitle(function(err,title) {
assert.strictEqual(title, 'Test Document');
})
.call(done);
});
it('checks if a div with class name "test" is assigned via javascript on load', function(done) {
browser
.url(testDoc)
.getAttribute('div','class')
.then(function(attr) {
assert.strictEqual(attr, 'test');
})
.call(done);
});
});
|
import React from 'react';
import PropTypes from 'prop-types';
import {Redirect} from 'react-router-dom';
import classes from './index.module.css';
// import imgTopViewLeft from './assets/img-topview-left.png';
//import imgTopViewRight from './assets/img-topview-right.png';
import {UserCardSquareAuth} from './component/card/user-card-square-auth';
import {FriendSideBar} from './component/friends';
import {InvitationSideBar} from './component/invitation';
import {TagesSideBar} from './component/tag';
import {languageHelper} from '../../tool/language-helper';
import {removeUrlSlashSuffix} from '../../tool/remove-url-slash-suffix';
import {getAsync, isLogin} from '../../tool/api-helper';
class ConnectionReact extends React.Component {
constructor(props) {
super(props);
// state
this.state = {
render: 0
};
// i18n
this.text = ConnectionReact.i18n[languageHelper()];
}
async componentDidMount() {
if (!isLogin()) {
this.setState({
render: 2
});
}
this.setState({
render: 1,
userFulltext: await getAsync('/discovery/users?limit=10&page=1'),
});
}
render() {
const pathname = removeUrlSlashSuffix(this.props.location.pathname);
if (pathname) {
return (<Redirect to={pathname} />);
}
switch (this.state.render) {
case 1:
return (
<div>
{/*<div className="d-flex align-items-center justify-items-center" style={{background: '#ffffff'}}>*/}
{/*<div>*/}
{/*<img className={classes.topViewImg} src={imgTopViewRight} alt="img" />*/}
{/*</div>*/}
{/*<div style={{width: '60vw'}}>*/}
{/*<p className={classes.topViewTitle1}>拓宽你的人脉</p>*/}
{/*<p className={classes.topViewTitle2}>接触来自不同领域的大牛们能很大程度上帮助你做决策</p>*/}
{/*</div>*/}
{/*<div>*/}
{/*<img className={classes.topViewImg} src={imgTopViewLeft} alt="img" />*/}
{/*</div>*/}
{/*</div>*/}
<div
className="cell-wall"
style={{backgroundColor: '#F3F5F7'}}
>
<div
className="cell-membrane"
>
<div className="d-flex justify-content-center">
<div className="d-flex flex-wrap justify-content-between" style={{marginTop: '2.34vw', width: '70vw'}}>
{this.state.userFulltext.content.data.map((item, index) => {
return (
<div style={{marginBottom: '1vw', marginRight: '2vw',height:'10.5vw'}} key={index}>
<UserCardSquareAuth
id={item.content.id}
avatar={item.content.avatar_url}
name={item.content.first_name+item.content.last_name}
role={item.content.role[0]}
sex={item.content.gender}
nation={item.content.nation}
/>
</div>
);
})}
</div>
<div className={classes.sideBar}>
<FriendSideBar number={[21, 8]} />
<InvitationSideBar content={'目前没有未回复的邀请'} />
<TagesSideBar tags={['求职经历', '面试经历']} />
</div>
</div>
</div>
</div>
</div>
);
case 2:
return (<Redirect to={`/login?to=${this.props.location.pathname}`} />);
default:
return null;
}
}
}
ConnectionReact.i18n = [
{},
{}
];
ConnectionReact.propTypes = {
// self
// React Router
match: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
location: PropTypes.object.isRequired
};
export const Connection = ConnectionReact;
|
var mysql = require('mysql');
var propObj=require('../config_con.js').ruleEngineDbProps;
//start mysql connection
var connection = mysql.createConnection(propObj);
connection.connect(function (err) {
if (err) {
console.log('Error in Mysql connection With rule_engine database :-', err);
} else {
console.log('You are now connected with mysql rule_engine database...');
}
})
module.exports=connection;
|
import React from "react";
import "./questionBox.css";
import { db } from "../../services/firebase";
import { NavLink } from "react-router-dom";
class QuestionBox extends React.Component {
constructor(props) {
super(props);
this.state = {
bool: 0,
id: Date.now().toString(),
flag: 0,
answer1: "",
answer2: "",
answer3: ""
};
}
state = {
questions: null,
users: null
};
componentDidMount() {
db.collection("questions")
.get()
.then(snapshot => {
const questions = [];
snapshot.forEach(doc => {
const data = doc.data();
questions.push(data);
});
this.setState({ questions: questions });
})
.catch(error => console.log(error));
db.collection("users")
.get()
.then(snapshot => {
const users = [];
snapshot.forEach(doc => {
const userData = doc.data();
users.push(userData);
});
this.setState({ users: users });
})
.catch(error => console.log(error));
}
saveAnswer = () => {
this.setState({ flag: this.state.flag + 1 });
};
saveId = () => {
db.collection("users")
.doc("go8qA5lcRD0n5mXDkvjg")
.update({
id: Date.now().toString()
});
};
setFirstOptAnswer1 = () => {
db.collection("users")
.doc("go8qA5lcRD0n5mXDkvjg")
.update({
answer1: "Да"
});
this.setState({ bool: 1, id: Date.now().toString() });
};
setSecondOptAnswer1 = () => {
db.collection("users")
.doc("go8qA5lcRD0n5mXDkvjg")
.update({
answer1: "Нет"
});
this.setState({ bool: 1, id: Date.now().toString() });
};
setFirstOptAnswer2 = () => {
db.collection("users")
.doc("go8qA5lcRD0n5mXDkvjg")
.update({
answer2: "Да"
});
this.setState({ bool: 1 });
};
setSecondOptAnswer2 = () => {
db.collection("users")
.doc("go8qA5lcRD0n5mXDkvjg")
.update({
answer2: "Нет"
});
this.setState({ bool: 1 });
};
setThirdOptAnswer2 = () => {
db.collection("users")
.doc("go8qA5lcRD0n5mXDkvjg")
.update({
answer2: "Затрудняюсь ответить, чувствую слабость"
});
this.setState({ bool: 1 });
};
setThirdAnswer = () => {
db.collection("users")
.doc("go8qA5lcRD0n5mXDkvjg")
.update({
answer3: this.refs.textArea.value
});
this.setState({ bool: 2 });
};
render() {
return (
<div className="card text-center shadow">
{this.state.flag === 0 ? (
<div className="progress" style={{ borderRadius: 1 }}>
<div className="progress-bar" style={{ width: "33%" }}>
1 из 3
</div>
</div>
) : null}
{this.state.flag === 1 ? (
<div className="progress" style={{ borderRadius: 1 }}>
<div className="progress-bar" style={{ width: "66%" }}>
2 из 3
</div>
</div>
) : null}
{this.state.flag === 2 ? (
<div className="progress" style={{ borderRadius: 1 }}>
<div className="progress-bar" style={{ width: "100%" }}>
3 из 3
</div>
</div>
) : null}
<div className="card-body text-dark">
{this.state.flag === 0
? this.state.questions &&
this.state.questions.map(questions => {
return (
<h5 className="card-title text-center">
{String(questions.first_question)}
</h5>
);
})
: null}
{this.state.flag === 1
? this.state.questions &&
this.state.questions.map(questions => {
return (
<h5 className="card-title text-center">
{String(questions.second_question)}
</h5>
);
})
: null}
{this.state.flag === 2
? this.state.questions &&
this.state.questions.map(questions => {
return (
<h5 className="card-title text-center">
{String(questions.third_question)}
</h5>
);
})
: null}
{this.state.flag === 0
? this.state.questions &&
this.state.questions.map(questions => {
return (
<div className="card-text">
<div className="custom-control custom-radio custom-control-inline is-invalid">
<input
input
type="radio"
name="group1"
id="r1"
value="1"
className="custom-control-input"
onChange={this.setFirstOptAnswer1}
/>
<label className="custom-control-label" for="r1">
{String(questions.options[0])}
</label>
</div>
<div className="custom-control custom-radio custom-control-inline">
<input
input
type="radio"
name="group1"
id="r2"
value="2"
className="custom-control-input"
onChange={this.setSecondOptAnswer1}
/>
<label className="custom-control-label" for="r2">
{String(questions.options[1])}
</label>
</div>
</div>
);
})
: null}
{this.state.flag === 1
? this.state.questions &&
this.state.questions.map(questions => {
return (
<div className="card-text">
<div className="custom-control custom-radio custom-control-inline is-invalid">
<input
input
type="radio"
name="group1"
id="r1"
value="1"
className="custom-control-input"
onChange={this.setFirstOptAnswer2}
/>
<label className="custom-control-label" for="r1">
{String(questions.options[0])}
</label>
</div>
<div className="custom-control custom-radio custom-control-inline">
<input
input
type="radio"
name="group1"
id="r2"
value="2"
className="custom-control-input"
onChange={this.setSecondOptAnswer2}
/>
<label className="custom-control-label" for="r2">
{String(questions.options[1])}
</label>
</div>
<div className="custom-control custom-radio custom-control-inline">
<input
input
type="radio"
name="group1"
id="r3"
value="3"
className="custom-control-input"
onChange={this.setThirdOptAnswer2}
/>
<label className="custom-control-label" for="r3">
{String(questions.options[2])}
</label>
</div>
</div>
);
})
: null}
{this.state.flag === 2
? this.state.questions &&
this.state.questions.map(questions => {
return (
<div className="card-text">
<div className="row-fluid">
<div className="col-12">
<textarea
className="form-control"
id="exampleFormControlTextarea1"
rows="3"
onChange={this.setThirdAnswer}
ref="textArea"
/>
</div>
</div>
</div>
);
})
: null}
{this.state.flag === 0 || this.state.flag === 1 ? (
this.state.bool === 1 ? (
<button
className="btn btn-primary"
onClickCapture={this.saveAnswer}
>
Следующий вопрос
</button>
) : (
<button className="btn btn-outline-primary" disabled>
Выберите ответ на вопрос
</button>
)
) : null}
{this.state.flag === 2 ? (
this.state.bool === 2 ? (
<button className="btn btn-primary" onClickCapture={this.saveId}>
<NavLink to="/finish" style={{ color: "white" }}>
Завершить опрос
</NavLink>
</button>
) : (
<button className="btn btn-outline-primary" disabled>
Напишите ответ
</button>
)
) : null}
</div>
</div>
);
}
}
export default QuestionBox;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Dialog, {
DialogActions,
DialogContent,
DialogTitle
} from 'material-ui/Dialog';
import Button from 'material-ui/Button';
import { getSegments, closeSelectRefsDialog, addRef } from '../actions';
import { SegmentsFilter, SegmentsList } from '../components';
import { RefChipList } from './';
import { parseAgentAndProcess } from '../utils/queryString';
export class SelectRefsDialog extends Component {
constructor(props) {
super(props);
this.submitFilters = this.submitFilters.bind(this);
this.addSegmentAsRef = this.addSegmentAsRef.bind(this);
}
componentWillReceiveProps(nextProps) {
// Get all the segments if we are opening the dialog
if (this.props.show === false && nextProps.show === true) {
this.submitFilters({ process: nextProps.process });
}
}
submitFilters(filters) {
const { agent, fetchSegments } = this.props;
// Fetch all available segments
const process =
filters.process != null ? filters.process : this.props.process;
fetchSegments(agent, process, filters);
}
addSegmentAsRef(segment) {
this.props.appendRef({
process: segment.link.meta.process,
linkHash: segment.meta.linkHash,
mapId: segment.link.meta.mapId,
segment: { link: segment.link, meta: segment.meta }
});
}
render() {
const {
segments: { status, details, error },
agent,
process,
processes,
closeDialog,
show
} = this.props;
if (!show) {
return null;
}
const segmentListProps = {
agent,
process,
status,
error,
segments: details,
handleClick: this.addSegmentAsRef
};
return (
<Dialog maxWidth="md" open={show} onClose={() => closeDialog()}>
<DialogTitle>Select refs</DialogTitle>
<DialogContent>
<RefChipList withOpenButton={false} />
<SegmentsFilter
submitHandler={this.submitFilters}
withProcesses
processes={processes}
currentProcess={process}
/>
<SegmentsList {...segmentListProps} />
</DialogContent>
<DialogActions>
<Button color="default" onClick={() => closeDialog()}>
Done
</Button>
</DialogActions>
</Dialog>
);
}
}
SelectRefsDialog.propTypes = {
agent: PropTypes.string,
process: PropTypes.string,
processes: PropTypes.arrayOf(PropTypes.string).isRequired,
fetchSegments: PropTypes.func.isRequired,
closeDialog: PropTypes.func.isRequired,
appendRef: PropTypes.func.isRequired,
show: PropTypes.bool.isRequired,
segments: PropTypes.shape({
status: PropTypes.string,
error: PropTypes.string,
details: PropTypes.arrayOf(
PropTypes.shape({
meta: PropTypes.shape({
linkHash: PropTypes.string.isRequired
})
})
)
}).isRequired
};
SelectRefsDialog.defaultProps = {
agent: '',
process: ''
};
function mapStateToProps(state, ownProps) {
const { location: { pathname } } = ownProps;
const { process, agent } = parseAgentAndProcess(pathname);
const { segments, selectRefs: { show, refs }, agents } = state;
const processes = agents[agent]
? Object.keys(agents[agent].processes || {})
: [];
if (segments.details && refs) {
segments.details = segments.details.filter(
s => !refs.find(r => r.linkHash === s.meta.linkHash)
);
}
return { agent, process, segments, show, processes };
}
export default connect(mapStateToProps, {
fetchSegments: getSegments,
closeDialog: closeSelectRefsDialog,
appendRef: addRef
})(SelectRefsDialog);
|
import React from "react";
import { withTranslation } from "react-i18next";
import { withRouter } from "react-router-dom";
import history from "../history";
import { supportedLanguages } from "../i18n";
function LanguageSwitcherComp(props) {
const { i18n } = props;
const changeLanguage = nextLang => {
i18n.changeLanguage(nextLang, () => {
const newUrl = `/${nextLang}${window.location.pathname.substr(
window.location.pathname.lastIndexOf("/")
)}`;
history.push(newUrl);
});
};
const handleClickSelectLanguage = (event, index) => {
changeLanguage(supportedLanguages[index]);
};
return (
<>
<div className="ui compact menu">
<div className="ui simple dropdown item">
<i
className={`${
i18n.language === "en" ? "gb uk" : i18n.language
} flag`}
></i>
<div className="menu">
{supportedLanguages.map((option, index) => (
<div
className="item"
key={option}
onClick={event => handleClickSelectLanguage(event, index)}
>
<i className={`${option === "en" ? "gb uk" : option} flag`}></i>
</div>
))}
</div>
</div>
</div>
</>
);
}
export default withRouter(withTranslation("routes")(LanguageSwitcherComp));
|
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database('./data/olympic_history.db');
const all = function (query) {
return () => {
return new Promise((resolve, reject) => {
db.all(query, [], (err, rows) => {
if (err) {
err.message = (`Query:\n'${query}'\n caused: ${err.message}`);
reject(err);
}
resolve(rows);
});
});
};
};
const run = function (query, message) {
return () => {
return new Promise((resolve, reject) => {
db.run(query, [], function (err) {
if (err) {
err.message = (`Query:\n'${query}'\n caused: ${err.message}`);
reject(err);
}
if (message) console.log(message);
resolve();
});
});
};
};
const close = (err, onclose) => {
if (onclose) onclose();
if (err) console.log(err.message);
db.close();
};
exports.run = run;
exports.all = all;
exports.close = close;
|
import React from "react";
import Container from "../components/Container";
import Row from "../components/Row";
import Col from "../components/Col";
import Project from "../components/Project";
function Projects() {
return (
<Container style={{ marginTop: 30 }}>
<Row>
<h1>My Portfolio</h1>
</Row>
<Row>
<Col size="md-3"></Col>
<Col size="md-3">
<Project img="WTF-App.png" alt="profile" href="https://athomik79.github.io/WTF-app/" pname="First Project: WTF-App"></Project>
</Col>
<Col size="md-3">
<Project img="burger_header.png" alt="profile" href="https://afternoon-caverns-43648.herokuapp.com/" pname="Eat-Da-Burger App"></Project>
</Col>
</Row>
<Row>
<Col size="md-3"></Col>
<Col size="md-3">
<Project img="trace-me.PNG" alt="profile" href="https://trace-me-app.herokuapp.com/main.html" pname="Trace Me"></Project>
</Col>
<Col size="md-3">
<Project img="emp-direct.PNG" alt="profile" href="https://quiet-journey-55809.herokuapp.com/" pname="Employee Directory"></Project>
</Col>
</Row>
</Container>
)
}
export default Projects;
|
const Movie = require("../models/movie");
const BadRequestError = require("../errors/BadRequestError");
const NotFoundError = require("../errors/NotFoundError");
const ForbiddenError = require("../errors/ForbiddenError");
module.exports.getMovies = (req, res, next) => {
//console.log(req.user);
const owner = req.user._id;
Movie.find({ owner })
.then((cards) => {
if (!cards) {
const error = new NotFoundError("Не найден пользователь с таким ID");
next(error);
} else {
res.send({ cards });
}
})
.catch((err) => {
if (err.name === "ValidationError") {
const error = new BadRequestError("Недопустимые символы");
next(error);
} else if (err.name === "CastError") {
const error = new BadRequestError("Неверный формат ID");
next(error);
}
next(err);
});
};
module.exports.createMovie = (req, res, next) => {
//console.log(req.user);
const owner = req.user._id;
Movie.create({ owner: owner, ...req.body })
.then((movie) => {
if (!movie) {
const error = new NotFoundError("Не найден пользователь с таким ID");
next(error);
} else {
res.send({ movie });
}
})
.catch((err) => {
if (err.name === "ValidationError") {
const error = new BadRequestError("Недопустимые символы");
next(error);
} else if (err.name === "CastError") {
const error = new BadRequestError("Неверный формат ID");
next(error);
}
next(err);
});
};
module.exports.deleteMovie = (req, res, next) => {
Movie.findByIdAndRemove(req.params._id)
.then((movie) => {
if (!movie) {
const r = new NotFoundError("Нет фильма с таким идентификатором");
next(r);
} else if (movie.owner.toString() !== req.user._id) {
//Есть проверка на то что удалять чужие фильмы нельзя
const r = new ForbiddenError("Нельзя удалять чужие фильмы");
next(r);
} else {
res.send({ data: movie });
}
})
.catch((err) => {
if (err.name === "CastError") {
const r = new BadRequestError("Неверный формат ID");
next(r);
}
next(err);
});
};
|
import React from 'react';
import { mount } from 'enzyme';
import { injectIntl } from '../../lib/index.es.js';
const intlConfig = {
locale: 'en',
messages: {
greeting: 'Hello {name}!',
},
};
describe('format HTML message', () => {
it('formats HTML message properly', () => {
const Strong = ({ children }) => <b>{children}</b>;
const Component = ({ intl }) => (
<span>
{intl.formatHTMLMessage(
{ id: 'greeting' },
{ name: <Strong>world</Strong> },
)}
</span>
);
const EnhancedComponent = injectIntl(Component);
const wrapper = mount(<EnhancedComponent intl={intlConfig} />);
expect(wrapper.text()).toEqual('Hello world!');
expect(wrapper.html()).toEqual('<span>Hello <b>world</b>!</span>');
});
it('fallbacks to formatMessage', () => {
const Component = ({ intl }) => (
<span>
{intl.formatHTMLMessage({ id: 'greeting' }, { name: 'world' })}
</span>
);
const EnhancedComponent = injectIntl(Component);
const wrapper = mount(<EnhancedComponent intl={intlConfig} />);
expect(wrapper.text()).toEqual('Hello world!');
expect(wrapper.html()).toEqual('<span>Hello world!</span>');
});
});
|
'use Strict'
function curlHandler(note) {
let noteKey = ''
let noteValue = ''
for (var key in note) {
noteKey = key
noteValue = note[key]
}
let noteData = noteValue == '' && noteKey != 'note_content' ? { note_content: noteKey } : note
return noteData
}
module.exports = {
curlHandler
}
|
/// <reference path="lib/jquery-1.7.1.js" />
/// <reference path="_eGravity.js" />
World = {
settings: {
width: 0,
height: 0,
gravity: 0,
hasColision: true
},
title: '',
context: null,
Elements: [],
load: function (context) {
if (context) World.context = context[0].getContext('2d');
World.settings.width = context.width();
World.settings.height = context.height();
World.settings.gravity = eGravity.TERRA;
},
update: function () {
$(World.Elements).each(function (i, item) {
$(World.Elements).each(function (j, item2) {
if (World.collision(item, item2)) {
item.update(true, true);
item2.update(true);
Sound.play('sound-of-ball');
}
item.update();
});
});
},
collision: function (Obj1, Obj2) {
if (Obj1.UID != Obj2.UID) {
var cateto1 = Obj2.x - Obj1.x;
var cateto2 = Obj2.y - Obj1.y;
var distancia = Math.sqrt(cateto1 * cateto1 + cateto2 * cateto2); //hipotenusa
if (distancia < 0) distancia = -(distancia);
if (distancia < (Obj1.settings.width + Obj2.settings.width)) {
//console.log('COLISION! ----> ' + Obj1.name + ' colisao com ' + Obj2.name);
return World.settings.hasColision; //colisão
}
}
return false;
},
draw: function () {
World.clear();
$(World.Elements).each(function () {
if (this.draw) {
this.draw(World.context);
}
});
},
clear: function () {
World.context.clearRect(0, 0, World.settings.width, World.settings.height);
},
addElement: function (element) {
World.Elements.push(element);
}
}
Model = function () {
this.UID = 0;
this.name = 'unknown';
this.image = null;
this.x = 0;
this.y = 0;
this.dx = 0;
this.dy = 0;
this.draw = null; //functions
this.update = null; //functions
this.settings = {
movable: false,
width: 0,
height: 0,
weight: 0
};
}
|
(function(){var g=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},f=function(a){var b=[],c;for(c in a)b.push(c+"="+encodeURIComponent(a[c]));return b.join("&")},e=function(a,b){this.base=a||{};var c={id:"f2e"},d;for(d in c)"undefined"==typeof this.base[d]&&(this.base[d]=c[d]);this.cfg=b||{};c={baseUrl:"http://project.f2e.netease.com:88/e.gif",wait:1E3};for(d in c)"undefined"==typeof this.cfg[d]&&(this.cfg[d]=c[d]);this.info=[]};e.prototype.domload=function(a){window.addEventListener?
document.addEventListener("DOMContentLoaded",a,!1):document.attachEvent&&document.attachEvent("onreadystatechange",a)};e.prototype.load=function(a){window.addEventListener?window.addEventListener("load",a,!1):window.attachEvent&&window.attachEvent("onload",a)};e.prototype.performance=function(){var a=this;a.domload(function(){a.timer("domload")});a.load(function(){setTimeout(function(){a.timer("load");if(window.performance&&window.performance.timing){var b={},c=window.performance.timing.navigationStart,
d,e;for(e in window.performance.timing)d=window.performance.timing[e]-c,0<d&&(b[e]=d);a.collect(b)}a.send()},a.cfg.wait)})};e.prototype.timer=function(a){if(window._ntes_const&&window._ntes_const.stime){var b={};b[a]=(new Date).getTime()-window._ntes_const.stime.getTime();this.collect(b)}};e.prototype.collect=function(a){g(a)||(a=[a]);this.info=this.info.concat(a)};e.prototype.send=function(){for(var a=this.cfg.baseUrl,a=a+("?"+f(this.base)),b=0,c=this.info.length;b<c;b++)a+="&"+f(this.info[b]);(new Image).src=
a;this.info=[]};window.NTES||(window.NTES={});window.NTES.Monitor=e})();
var _f2e_tools ={
setCookie : function(name, value, expires, domain, path, secure){//过期时间:天
var cookieStr = [escape(name) + "=" + escape(value)];
if (expires) {
var date;
if (!isNaN(expires)) {
date = new Date();
date.setTime(date.getTime() + expires * 60 * 1000);
} else {
date = expires;
}
cookieStr.push("expires=" + date.toUTCString());
}
if (path != null && path !== "") {
cookieStr.push("path=" + path);
}
if (domain) {
cookieStr.push("domain=" + domain);
}
if (secure) {
cookieStr.push("secure");
}
document.cookie = cookieStr.join(";");
},
getCookie:function(name){
name = escape(name) + "=";
var cookie = document.cookie, beginPos = cookie.indexOf(name);
if (-1 === beginPos) {
return "";
}
beginPos += name.length;
var endPos = cookie.indexOf(";", beginPos);
if (endPos === -1) {
endPos = cookie.length;
}
return unescape(cookie.substring(beginPos, endPos));
},
addEvent:function(obj,_event,func){
if (obj.attachEvent){
obj.attachEvent('on' + _event,func);
}else{
obj.addEventListener(_event,func,false);
}
},
stopDefault:function(e){//阻止浏览器默认动作
if (e && e.preventDefault){
e.preventDefault();
}else{
window.event.returnValue = false;
}
return false;
},
ieupdate:function(){
var _t= this;
var html = '<div style="width:960px;margin:1px auto;height:26px;overflow:hidden;border-bottom:2px solid #6699cc;background:#bad6eb;text-align:left;overflow:hidden;">'+
'<p style="font-size:12px;height:22px;padding:4px 15px 0 15px;color:#33588d;margin:0;line-height:20px;">'+
'<a id="update_popwin_close" onmouseover="this.style.color=\'#BA2636\';" onmouseout="this.style.color=\'#4F85B1\';" style="float:right;color:#4F85B1;text-decoration:underline; font-size:12px;" href="javascript:void(0);" target="_self" >下次不再显示</a>'+
'<span style="float:left;">亲爱的网易用户,您是否还在用老旧的ie6浏览器?加入网易“<a onmouseover="this.style.color=\'#BA2636\';this.style.textDecoration=\'underline\';" onmouseout="this.style.color=\'#4F85B1\';" style="color:#4F85B1;font-size:12px;text-decoration:underline;" href="http://developer.163.com/notice/ie_update.html">全网公敌IE6</a>”活动,一起给你的</span>'+
'<a style="float:left;zoom:1;padding: 0 3px;margin:0 5px;background:#fff;border:1px solid #a6adb7;color:#33588d;text-decoration:none; font-size:12px;height: 16px;line-height: 16px;line-height:18px\\9;overflow:hidden; _display: inline;" onmouseover="this.style.borderColor=\'#69c\'; this.style.color=\'#fff\';this.style.backgroundColor=\'#356AA0\';" onmouseout="this.style.borderColor=\'#a6adb7\'; this.style.color=\'#33588d\';this.style.backgroundColor=\'#fff\';" href="http://developer.163.com/notice/ie_update.html">浏览器升级</a>'+
'<span style="float:left;">吧!您也可以: </span>'+
'<a onmouseover="this.style.color=\'#BA2636\';" onmouseout="this.style.color=\'#4F85B1\';" style="float:left;color:#4F85B1;text-decoration:underline; font-size:12px;" href="http://developer.163.com/notice/ie_update.html">下载360安全浏览器</a>'+
'<img src="http://img1.cache.netease.com/2012/ieupdate/360.gif" alt="360安全浏览器" style="float:left;margin-left:5px;_display:inline;"/>'+
'</p></div>';
var close = _t.getCookie("_ieupdate_close");
if(close === ""){
var node = document.createElement("div");
node.id = 'update_popwin';
node.style.overflow = 'hidden';
node.style.position = 'relative';
node.style.zIndex = 9999;
node.innerHTML = html.replace(/ie_update.html/g,'ie_update.html?ref='+location.hostname);
var parent = document.getElementsByTagName("body")[0];
var timmer = null;
var time_close = 20000;
function showwin(n,height,time){
n.style.height = '0px';
var h = 0,t=0;
function Sine(t,b,c,d){ return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }
var _timmer = setInterval(function(){
h = Sine(t,0,height,time);
if(t>time){
n.style.height = height+"px";
clearInterval(_timmer);
_timmer = null;
return;
}
n.style.height = h+"px";
t+=13;
},13);
}
function hiddenwin(n,height,time){
var h = height,t=0;
function Sine(t,b,c,d){ return c * Math.sin(t/d * (Math.PI/2)) + b; }
var _timmer = setInterval(function(){
h = Sine(t,height,-1*height,time);
if(t>time){
n.style.height = height+"px";
n.style.display = "none";
clearInterval(_timmer);
_timmer = null;
return;
}
n.style.height = h+"px";
t+=13;
},13);
}
parent.insertBefore(node,parent.firstChild);
var height = node.offsetHeight;
showwin(node,height,300);
_t.addEvent(document.getElementById("update_popwin_close"),"click",function(e){
e = e || window.event;
_t.stopDefault(e);
hiddenwin(node,height,300);
_t.setCookie("_ieupdate_close","close",365);
if(timmer!==null){
clearTimeout(timmer);
timmer = null;
}
});
_t.addEvent(node,"mouseover",function(e){
if(timmer!=null){
clearTimeout(timmer);
timmer = null;
}
});
_t.addEvent(node,"mouseout",function(e){
timmer = setTimeout(function(){
hiddenwin(node,height,300);
},time_close);
});
timmer = setTimeout(function(){
hiddenwin(node,height,300);
},time_close);
}
}
};
function __ieUpdate(){
setTimeout(function(){
_f2e_tools.ieupdate();
},17000);
}
function __f2e_monitor(cid,r){
if(typeof _ntes_const === "undefined"){
return;
}
var ratio = r || 0.0001;
if(Math.random()<ratio){
(new NTES.Monitor({id:cid})).performance();
}
}
|
exports.sourceNodes = async ({ actions, createNodeId, createContentDigest }) => {
const icons = [
{ type: 'fab', name: 'linkedin', url: 'https://www.linkedin.com/in/emil-petersson-5a042b114/' },
{ type: 'fab', name: 'facebook', url: 'https://www.facebook.com/emilpee' },
{ type: 'fab', name: 'github', url: 'https://github.com/emilpee/' },
]
const links = [
{
name: 'Home',
link: '/',
},
{
name: 'About',
link: '/about',
},
]
icons.forEach(icon => {
const node = {
id: createNodeId(`FontAwesome-${icon.name}`),
type: icon.type,
name: icon.name,
url: icon.url,
internal: {
type: 'fontAwesomeIcon',
contentDigest: createContentDigest(icon),
},
}
actions.createNode(node)
})
links.forEach((link, index) => {
const node = {
id: createNodeId(index),
name: link.name,
url: link.link,
internal: {
type: 'internalLink',
contentDigest: createContentDigest(link),
},
}
actions.createNode(node)
})
}
|
import React from 'react'
import {Link } from "react-router-dom"
// import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
function CardItem(props) {
const {item,addToCart} = props
const addItem = async () => {
console.log(await addToCart(item._id))
}
return (
<div><i class="fas fa-thumbs-down"></i>
<div className=" my-10 rounded-xl shadow-md ">
<img className="w-full" src="https://images.unsplash.com/photo-1484527273420-c598cb0601f8?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyNDU1MTN8MHwxfHNlYXJjaHw1MXx8bWVuLWZhc2hpb258ZW58MHx8fHwxNjM1MTAzMDIy&ixlib=rb-1.2.1&q=80&w=200" alt="" />
<div className="p-4 space-y-2 text-center">
<p>{item.title}</p>
<p>Price : $ {item.price}</p>
{/* <span><FontAwesomeIcon icon={["fas","fa-thumbs-down"]}/></span> */}
<div className="flex space-x-2">
<Link to={`/detail/${item._id}`} className="w-1/2 py-2 rounded-full bg-purple-600 text-white hover:bg-purple-700"><button >More Info</button></Link>
<button className="w-1/2 py-2 rounded-full bg-purple-50 text-purple-600 hover:text-purple-700" onClick={addItem}>Add To Cart</button>
</div>
</div>
</div>
</div>
)
}
export default CardItem
|
'use strict'
//전역으로 사용하는것, 함수마다 사용하는것 자제.
|
import request from '@/utils/request'
/**
* 版本
* @constant
* @type {string}
* @default
* */
/**
* 获取服务器地址
* * @param {*} params 请求地址
*/
export function getAddress(params) {
return request({
url: `/sys/configs`,
method: 'get',
params
})
}
/**
* 根据名称获取服务器地址
* * @param {*} params 请求地址
*/
export function getAddressByName(name) {
return request({
url: `/sys/configs/${name}`,
method: 'get'
})
}
/**
* 修改服务器地址
* * @data {*} 提交数据
*/
export function modifyAddress(data) {
return request({
url: `/sys/configs`,
method: 'post',
data
})
}
|
import logo from './logo.svg';
import './App.css';
import { useEffect, useState } from 'react';
function App() {
// var person= {
// name:"Dr. Mahfuz",
// job:"Singer"
// }
// var person2= {
// name:"Eva Rahman",
// job:"Kokil Konthi"
// }
// var style ={
// color:'red',
// backgroundColor:'yellow'
// }
const nayoks = ['Anwar', 'Alamgir', 'Salman', 'Sakib', 'Shuvo']
const products = [
{name: 'Photoshop',price:'$90.99'},
{name: 'Illustrator',price:'$60.99'},
{name: 'PDF Reader',price:'$6.99'},
{name: 'Premiere El',price:'$249.99'}
]
const nayokNames = nayoks.map(nayok => nayok);
console.log(nayokNames);
return (
<div className="App">
<header className="App-header">
<p>I am a React Person</p>
<Counter></Counter>
<Users></Users>
<ul>
{
nayoks.map(nayok => <li>{nayok}</li>)
}
{
products.map(product=><li>{product.name}</li>)
}
</ul>
{
products.map(pd =><Product product={pd}></Product>)
}
<Product name={products[0].name} price={products[0].price}></Product>
<Product name={products[1].name} price={products[1].price}></Product>
<Person name={nayoks[1]} food="Pizza" nayika="Moushumi"></Person>
<Person name="Jasim" nayika="Shabana"></Person>
<Person name="BappaRaz" nayika="Cheka"></Person>
<Person name="Elias K" nayika="Bobita"></Person>
</header>
</div>
);
}
function Counter(){
const[count, setCount] = useState(10);
const handleIncrease = () => setCount(count +1);
return(
<div>
<h1>Count: {count}</h1>
<button onClick={()=> setCount(count-1)}>Decrease</button>
<button onClick={handleIncrease}>Increase</button>
</div>
)
}
function Users(){
const [users, setUsers] = useState([]);
useEffect(()=>{
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => setUsers(data));
}, [])
return(
<div>
<h3>Dynamic Users: {users.length}</h3>
<ul>
{
users.map(user => <li>{user.name}</li>)
}
</ul>
</div>
)
}
function Product(props){
const productStyle={
border:'1px solid gray',
borderRadius:'5px',
backgroundColor:'lightgray',
height:'200px',
width:'200px',
float:'left'
}
return(
<div style={productStyle}>
<h3>{props.name}</h3>
<h5>{props.price}</h5>
<button>Buy now</button>
</div>
)
}
function Person(props){
const personStyle={
border:'2px solid red',
margin:'10px',
padding:'2px 20px'
}
return (
<div style={personStyle}>
<h1>Name: {props.name}</h1>
<h3>Hero of {props.nayika}</h3>
</div>
)
}
export default App;
|
import $ from '../core';
$.prototype.addClass = function(...classNames) { //Добавляет 1 и более классов, переданных в ...classNames через запятую
for (let i = 0; i < this.length; i++) {
if (!this[i].classList) {
continue;
}
this[i].classList.add(...classNames);
}
return this;
};
$.prototype.removeClass = function(...classNames) { //Удаляет 1 и более классов, переданных в ...classNames через запятую
for (let i = 0; i < this.length; i++) {
if (!this[i].classList) {
continue;
}
this[i].classList.remove(...classNames);
}
return this;
};
$.prototype.toggleClass = function(className) { //Тогглит класс className
for (let i = 0; i < this.length; i++) {
if (!this[i].classList) {
continue;
}
this[i].classList.toggle(className);
}
return this;
};
|
$(function() {
window.$Qmatic.components.card.transferUserPoolCard = new window.$Qmatic.components.card.TransferCardComponent('#transferUserPoolCard')
})
|
var pageSize = 25;
var subscribe = document.getElementById('subscribe').value;
Ext.define('gigade.EdmContentNew', {
extend: 'Ext.data.Model',
fields: [
{ name: "content_id", type: "int" },
{ name: "group_id", type: "int" },
{ name: "subject", type: "string" },
{ name: "template_id", type: "int" },
{ name: "template_data", type: "string" },
{ name: "template_data_send", type: "string" },
{ name: "importance", type: "int" },
{ name: "sender_id", type: "int" },
{ name: "content_createdate", type: "string" },
{ name: "content_updatedate", type: "string" },
{ name: "content_create_userid", type: "int" },
{ name: "content_update_userid", type: "int" },
{ name: "schedule_date", type: "string" },
{ name: "count", type: "int" },
{ name: "date", type: "string" },
{ name: "sender_email", type: "string" },
{ name: "sender_name", type: "string" },
{ name: "edit_url", type: "string" },
{ name: "content_url", type: "string" },
{ name: "pm", type: "int" },
{ name: "edm_pm", type: "string" },
{ name: "static_template", type: "int" },
{ name: "user_username_create", type: "string" },
{ name: "user_username_update", type: "string" },
]
});
EdmContentNewStore = Ext.create('Ext.data.Store', {
autoDestroy: true,
pageSize: pageSize,
model: 'gigade.EdmContentNew',
proxy: {
type: 'ajax',
url: '/EdmNew/GetECNList',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
});
Ext.define('gigade.edm_group_new2', {
extend: 'Ext.data.Model',
fields: [
{ name: 'group_id', type: 'int' },
{ name: 'group_name', type: 'string' }
]
});
var EdmGroupNewStore2 = Ext.create("Ext.data.Store", {
autoLoad: true,
model: 'gigade.edm_group_new2',
proxy: {
type: 'ajax',
url: '/EdmNew/GetEdmGroupNewStore',
reader: {
type: 'json',
root: 'data'
}
}
});
EdmContentNewStore.on('beforeload', function () {
Ext.apply(EdmContentNewStore.proxy.extraParams,
{
group_id: Ext.getCmp('search_group_name').getValue(),
});
});
var sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections) {
Ext.getCmp("EdmContentNew").down('#edit').setDisabled(selections.length == 0);
//Ext.getCmp("EdmContentNew").down('#report').setDisabled(selections.length == 0);
Ext.getCmp("EdmContentNew").down('#goSend').setDisabled(selections.length == 0);
}
}
});
Ext.onReady(function () {
var EdmContentNew = Ext.create('Ext.grid.Panel', {
id: 'EdmContentNew',
store: EdmContentNewStore,
flex: '8.9',
width: document.documentElement.clientWidth,
columnLines: true,
frame: true,
columns: [
{ header: "編號", dataIndex: 'content_id', width: 60, align: 'center' },
{ header: "需求申請者", dataIndex: 'edm_pm', width: 85, align: 'center' },
{ header: "正式發送", dataIndex: 'count', width: 150, align: 'center' },
{ header: "郵件主旨", dataIndex: 'subject', width: 200, align: 'center' },
{
header: "報表", width: 100, align: 'center', hidden: false, id: 'reportEdmContentNew',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
return "<a href='javascript:void(0)' onclick='ContentNewReportList(" + record.data.content_id + ")'><img src='../../../Content/img/icon_report.gif' /></a>"
}
},
{
header: "發送時間", dataIndex: 'date', width: 150, align: 'center'
, renderer: function (value) {
if (value == "0001-01-01 00:00:00") {
return "";
}
else {
return value;
}
}
},
{
header: "預覽電子報", width: 100, align: 'center', hidden: false, id: 'reviewEdm',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
return "<a href='javascript:void(0)' onclick='ReviewEdm()'><img src='../../../Content/img/icon_report.gif' /></a>"
}
},
{ header: "建立人", dataIndex: 'user_username_create', width: 85, align: 'center' },
{ header: "更新人", dataIndex: 'user_username_update', width: 85, align: 'center' },
],
tbar: [
{ xtype: 'button', text: '新增', id: 'add', hidden: false, iconCls: 'icon-user-add', handler: onAddClick },
{ xtype: 'button', text: '編輯', id: 'edit', hidden: false, iconCls: 'icon-user-edit', disabled: true, handler: onEditClick },
{ xtype: 'button', text: "前往發送", id: 'goSend', hidden: false, disabled: true, handler: onGoSendClick },
'->',
{
xtype: 'combobox', fieldLabel: '電子報類型', id: 'search_group_name', store: EdmGroupNewStore2, displayField: 'group_name',
valueField: 'group_id', editable: false, value: 0, lastQuery: '', emptyText: '全部',
},
{
xtype: 'button', text: '查詢', handler: Search
},
{
xtype: 'button', text: '重置', handler: function () {
Ext.getCmp('search_group_name').setValue();
}
},
],
bbar: Ext.create('Ext.PagingToolbar', {
store: EdmContentNewStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: "當前顯示記錄" + ': {0} - {1}' + "共計" + ': {2}',
emptyMsg: "沒有記錄可以顯示"
}),
listeners: {
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
},
selModel: sm
});
Ext.create('Ext.container.Viewport', {
layout: 'vbox',
items: [EdmContentNew],
renderTo: Ext.getBody(),
listeners: {
resize: function () {
EdmContentNew.width = document.documentElement.clientWidth;
this.doLayout();
}
}
});
ToolAuthority();
});
/*************************************************************************************新增*************************************************************************************************/
onAddClick = function () {
editFunction(null, EdmContentNewStore);
}
/*************************************************************************************編輯*************************************************************************************************/
onEditClick = function () {
var row = Ext.getCmp("EdmContentNew").getSelectionModel().getSelection();
if (row.length == 0) {
Ext.Msg.alert("提示信息", "沒有選擇一行");
} else if (row.length > 1) {
Ext.Msg.alert("提示信息", "只能選擇一行");
} else if (row.length == 1) {
editFunction(row[0], EdmContentNewStore);
}
}
onGoSendClick = function () {
var row = Ext.getCmp("EdmContentNew").getSelectionModel().getSelection();
if (row.length == 0) {
Ext.Msg.alert("提示信息", "沒有選擇一行");
} else if (row.length > 1) {
Ext.Msg.alert("提示信息", "只能選擇一行");
} else if (row.length == 1) {
row[0].data.template_data_send = row[0].data.template_data;
sendFunction(row[0], EdmContentNewStore);
}
}
onStatusClick = function () {
var row = Ext.getCmp("EdmContentNew").getSelectionModel().getSelection();
statusFunction(row[0], EdmContentNewStore);
}
function Search() {
EdmContentNewStore.removeAll();
var group_id = Ext.getCmp('search_group_name').getValue();
if (group_id != 0 && group_id != null) {
Ext.getCmp("EdmContentNew").store.loadPage(1, {
params: {
group_id: group_id,
}
});
} else {
Ext.Msg.alert("提示信息","請選擇查詢條件");
return;
}
}
function ContentNewReportList(content_id) {
var urlTran = '/EdmNew/EdmContentNewReport?content_id=' + content_id;
var panel = window.parent.parent.Ext.getCmp('ContentPanel');
var copy = panel.down('#EdmContentNew');
if (copy) {
copy.close();
}
copy = panel.add({
id: 'EdmContentNew',
title: '電子報統計報表',
html: window.top.rtnFrame(urlTran),
closable: true
});
panel.setActiveTab(copy);
panel.doLayout();
}
function ReviewEdm() {
var checked;
var template_data;
var row = Ext.getCmp("EdmContentNew").getSelectionModel().getSelection();
var static_template=row[0].data.static_template;
if (row[0].data.template_data.indexOf(subscribe) > 0) {
checked = true;
template_data = row[0].data.template_data.replace(subscribe, "");
}
else {
checked = false;
template_data = row[0].data.template_data;
}
var myMask = new Ext.LoadMask(Ext.getBody(), { msg: "生成預覽中..." });
myMask.show();
Ext.Ajax.request({
url: '/EdmNew/GetPreviewHtml',
params: {
content_id: row[0].data.content_id,
template_data: template_data,
checked: checked,
static_template: static_template,
},
success: function (data) {
myMask.hide();
var result = data.responseText;
var A = 1000;
var B = 700;
var C = (document.body.clientWidth - A) / 2;
var D = window.open('', null, 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=' + A + ',height=' + B + ',left=' + C);
var E = "<html><head><title>預覽</title></head><style>body{line-height:200%;padding:50px;}</style><body><div >" + result + "</div></body></html>";
D.document.write(E);
D.document.close();
}
});
}
|
/* SERVICES */
var userService = require('./service/userService');
var messageService = require('./service/messageService');
var systemService = require('./service/systemService');
var searchService = require('./service/searchService');
var monitorService = require('./service/monitorService');
module.exports = function(app) {
/* SYSTEM LEVEL APIs */
app.get('/', systemService.isUnderTesting, systemService.handleRootContext);
app.get('/home', systemService.isUnderTesting, systemService.handleHomeContext);
app.get('/uploadPicture', systemService.isUnderTesting, systemService.handlePictureUpload);
app.get('/views/:pageid', systemService.isUnderTesting, systemService.handleViewContext);
/* USER LEVEL APIs */
app.post('/user/signup/:username', userService.signup);
app.post('/user/login/:username', userService.login);
app.post('/user/logout', userService.logout);
app.get('/users', systemService.isUserLoggedIn, userService.getUsers);
app.get('/user/:username', systemService.isUserLoggedIn, userService.getUser);
app.put('/user/:username', systemService.isUserLoggedIn, userService.updateUser);
// Just for system testing, not an public API
app.delete('/user/:username', userService.deleteUser);
app.post('/user/picture/:username', systemService.isUserLoggedIn, userService.postProfilePicture);
app.get('/user/picture/:username', userService.getProfilePicture);
app.post('/status/:username', systemService.isUserLoggedIn, userService.shareStatus);
app.get('/status/all/:username', systemService.isUserLoggedIn, userService.getStatusHistory);
/* MESSAGING APIs */
app.get('/announcements', systemService.isUserLoggedIn, messageService.getAnnouncements);
app.get('/messages/wall', systemService.isUserLoggedIn, messageService.getWallMessages);
app.post('/messages/wall', systemService.isUserLoggedIn, messageService.putMessageOnWall);
app.get('/messages/:username', systemService.isUserLoggedIn, messageService.getPrivateMessagesWithUser);
/* SEARCH INFORMATION APIs */
app.get('/search/users', systemService.isUserLoggedIn, searchService.searchUsers);
app.get('/search/announcements', systemService.isUserLoggedIn, searchService.searchAnnouncements);
app.get('/search/publicMessages', systemService.isUserLoggedIn, searchService.searchPublicMessages);
app.get('/search/privateMessages', systemService.isUserLoggedIn, searchService.searchPrivateMessages);
/* PERFORMANCE MONITORING APIs */
app.post('/admin/test/start', systemService.isUserLoggedIn, monitorService.startPerformanceTest);
app.post('/admin/test/stop', systemService.isUserLoggedIn, monitorService.stopPerformanceTest);
};
|
MyApp.controller('HelloController', hello);
function hello($scope)
{
$scope.name = "Genevieve";
}
|
/*
* ================================================
* Kavimo.com
* Designer : WonderCo Team
* Programing : WonderCo Team
* URL : http://WonderCo.ir
* ================================================
** Blog Module - JS
* ================================================
*/
$(function(){
Kavimo.modules.blog = {
vars : {
list_comments : $('.list-comments'),
},
init : function()
{
Kavimo.modules.public.responsiveHeaderPages();
Kavimo.modules.public.newsletterForm(this);
this.sendCommnetForm();
this.replyComment();
this.fixMailerLite();
},
fixMailerLite : function()
{
var form = $('.ml-block-form .subscribe-form');
form.find('h4,p,input,button[type="submit"]').each(function(){
$(this).css('cssText','font-family: "iransans" !important; direction:rtl !important;text-align:center !important');
});
},
replyComment : function()
{
var _instance = this,
textarea = $('textarea[name=message]');
_instance.vars.list_comments.on('click','ul li a.actions[data-reply]',function(e){
var _this = $(this);
textarea.val(_this.data('reply') + ' ').focus();
$('html,body').animate({
scrollTop : $('.blog-comments').offset().top - 100
},200);
e.preventDefault();
});
},
sendCommnetForm : function()
{
var _instance = this;
var _form = $('form#send-comment'),
messageField = _form.find('textarea[name=message]'),
submitButton = _form.find('button[type=submit]');
_form.on('submit',function(e){
if(messageField.val())
{
Kavimo.core.ajax.post({
to : 'blog/send-comment',
data : {'text': messageField.val(),'blog_id': _instance.vars.blog_id },
before : function()
{
submitButton.attr('disabled','disabled');
},
done : function(response)
{
if(response.success)
{
submitButton.removeAttr('disabled');
messageField.val('');
var new_comment = '<li class="fadeInDown">'+
'<div class="avatar"><img src="'+Kavimo.user_identity.avatar+'"></div>'+
'<div class="message">'+
'<div class="head-message">'+
'<div class="row">'+
'<div class="col-xl-2 col-xs-2">'+
'<a href="#reply" class="actions" data-reply="'+response.data.mention+'"><i class="md-reply"></i></a>'+
'</div>'+
'<div class="col-xl-10 col-xs-10">'+
'<a href="#cm-'+response.data.anchor_id+'" name="cm-'+response.data.anchor_id+'" class="name">'+Kavimo.user_identity.full_name+'</a>'+
'<span class="date">'+_instance.i18n['accept-after-active']+'</span>'+
'</div>'+
'</div>'+
'</div>'+ response.data.message +
'</div>'+
'</li>';
_instance.vars.list_comments.find('ul').prepend(new_comment);
}
}
});
}
else
{
messageField.focus();
}
e.preventDefault();
})
},
}
//
$(function(){
Kavimo.modules.public = {
// varibale
vars : {
header : $('header'),
responsive : {
button_menu : $('header .button-menu'),
overlay : $('header .overlay-responsive'),
},
plansCost : {
percent_six_monthly_off : 10, // 10 Percent
percent_yearly_off : 15, // 10 Percent
OneTB_bandwidth : 700000,
OneTB_storage : 600000,
}
},
responsiveHeaderPages : function()
{
var _instance = this;
_instance.vars.responsive.button_menu.bind('click',function(){
$('body').addClass('active_responsive_layout');
});
_instance.vars.responsive.overlay.bind('click',function(){
$('body').removeClass('active_responsive_layout');
});
},
calcPricing : function(options)
{
var _instance = this;
var total = 0;
var total_extra = 0;
var price_off = 0;
var percent_off = 0;
var default_price_by_values = 41000;
var totalPriceBandwidth = (_instance.vars.plansCost.OneTB_bandwidth * options.bandwidth) / 1000;
var totalPriceStorage = (_instance.vars.plansCost.OneTB_storage * (options.video_numbers * options.max_size_upload)) / 1000;
options.only_plan_cost = parseInt(options.only_plan_cost);
total_extra = parseInt(totalPriceBandwidth + totalPriceStorage) - default_price_by_values;
total = total_extra + options.only_plan_cost;
if(options.payment_time == "six-monthly")
{
total = (total * 6);
price_off = parseInt(total * _instance.vars.plansCost.percent_six_monthly_off / 100);
total = total - price_off;
percent_off = _instance.vars.plansCost.percent_six_monthly_off;
}
else if(options.payment_time == "yearly")
{
total = (total * 12);
price_off = parseInt(total * _instance.vars.plansCost.percent_yearly_off / 100);
total = total - price_off;
percent_off = _instance.vars.plansCost.percent_yearly_off;
}
return {
total : total,
total_plan_only : options.only_plan_cost,
total_extra : total_extra,
off : {
price : price_off,
percent : percent_off,
},
totalWitoutOff : total + price_off
};
},
newsletterForm : function(module)
{
var _instance = module;
var _form = $('form#newsletter-form'),
emailField = _form.find('input[name=email]'),
nameField = _form.find('input[name=name]'),
submitButton = _form.find('button[type=submit]'),
patternEmail = /^[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/;
$(nameField).add(emailField).on('focus',function(){
$(this).removeClass('error');
})
_form.on('submit',function(e){
if(nameField.val() && emailField.val() && patternEmail.test(emailField.val()))
{
Kavimo.core.ajax.post({
to : 'site/newsletter',
data : {'email': emailField.val(),'name' : nameField.val()},
before : function()
{
submitButton.attr('disabled','disabled');
},
done : function(response)
{
if(response.success)
{
_form.parent('div').html('<div class="newsletter-success">'+__t('newsletter-landing-success-message')+'</div>');
}
}
});
}
else
{
(
(!nameField.val() && nameField.addClass('error')),
(!emailField.val() && emailField.addClass('error')),
(!patternEmail.test(emailField.val()) && emailField.addClass('error'))
)
}
e.preventDefault();
})
},
init : function()
{
// run all pages
},
}
Kavimo.modules.public.init();
Kavimo.modules.blog.init();
});
});
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema
//ObjectId = Schema.ObjectId;
const teacherSchema = new Schema({
id: Number,
name: String,
lastname: String,
username: {
type: String,
// ห้ามซ้ำ
unique: true
},
password: String
}, { versionKey: false });
// userSchema.id instanceof mongoose.Types.ObjectId;
const TeacherModel = mongoose.model('Teacher', teacherSchema);
module.exports = TeacherModel;
|
import { useState } from "react";
export default function MessageForm({ message, handleClose }) {
const [visible, setVisible] = useState(true);
handleClose = () => {
setVisible(!visible);
};
return (
<>
{visible ? (
<>
<div className="message show">
<p>{message}</p>
<button className="btn" onClick={handleClose}>
oke
</button>
</div>
</>
) : (
<>
<div className="message hide">
<p>{message}</p>
<button className="btn" onClick={handleClose}>
oke
</button>
</div>
</>
)}
</>
);
}
|
export const API_URL = 'http://localhost:8080/api';
export const TOKEN_AUTH_USERNAME = 'autoCenterClient';
export const TOKEN_AUTH_PASSWORD = '8ae1c884f76b6371acb51ec7faec4de8c9a4f2b568af2f992a6ca33cd094f1a6';
export const CARS_PAGE_SIZE = 4;
export const FUEL_ECONOMY_PAGE_SIZE = 10;
export const REPAIRS_PAGE_SIZE = 10;
|
class BackgroundManager{
constructor(){
this.content = document.querySelector('.mainContent');
}
setBackground(url){
this.content.style.backgroundImage = `url(${url})`;
this.content.style.backgroundSize = 'cover';
}
clearBackground(){
this.content.style.backgroundImage = '';
}
}
const instance = new BackgroundManager();
export default instance;
|
import React, { useState } from 'react'
import "./MobileMode.css"
import logo from '../../Assets/Mobile – Graphic.png'
import eyelogo from '../../Assets/see_password_icon.png'
function MobileMode() {
const [passwordShown, setPasswordShown] = useState(false);
const togglePasswordVisiblity = () => {
setPasswordShown(passwordShown ? false : true);
};
return (
<div className="mobile-only">
<div className="logo"><img src={logo} alt="logo"></img></div>
<div className="form">
<form style={{ "width": "100%" }}>
<h1 style={{ "textAlign": "center" }}>Create an account</h1>
<div className="row2">
<div className="card">
<label className="card_through_text">Personal Details</label>
<input className="inputBox" placeholder="First Name"></input>
<input className="inputBox" placeholder="Last Name"></input>
<input className="inputBox" placeholder="Age(18-20)"></input>
</div>
<div className="card">
<input className="inputBox" placeholder="Mobile No"></input>
<input className="inputBox" placeholder="email"></input>
</div>
<div className="card">
<label className="card_through_text">Password</label>
<div className="visible_eye">
<input className="inputBox" placeholder="Password" type={passwordShown ? "text" : "password"}></input>
<span className="visible_eye_logo2"><img onClick={togglePasswordVisiblity} src={eyelogo} alt="logo"></img></span>
</div>
<div className="visible_eye">
<input className="inputBox" placeholder="Confirm Password" type={passwordShown ? "text" : "password"}></input>
<span className="visible_eye_logo2"><img onClick={togglePasswordVisiblity} src={eyelogo} alt="logo"></img></span>
</div>
</div>
<div className="description2">
<label>Description</label>
<textarea rows="4" />
</div >
<div>
<div style={{"flex":"1"}}></div>
</div>
</div>
<div className="row2 button_row">
<button className="button button1">RESET</button>
<button className="button">SUBMIT</button>
</div>
</form>
</div>
</div>
)
}
export default MobileMode
|
"use strict";
var modules = ['common','module1','module2'];
var FileConfig = function(){
};
module.exports=new FileConfig();
FileConfig.prototype.modules=function(){
return modules;
}
|
define(['rd.modules.i18n'],
function(i18n) {
//默认语言环境,在获取语言服务失败时使用
var defaultLocale = 'en_US';
return i18n.init({
"en_US": {
},
"zh_CN": {
}
}, defaultLocale);
});
|
export default class Article{
constructor(data){
this.id = data.id
this.title = data.title;
this.sectionName = data.sectionName;
this.dateOfPublication = data.dateOfPublication;
this.fullArticleLink = data.fullArticleLink;
}
createTemplate(){
return `
<li>
<article props='${this.id}' class="news">
<header>
<h3>${this.title}</h3>
</header>
<section class="newsDetails">
<ul>
<li><strong>Section Name:</strong>${this.sectionName}</li>
<li><strong>Publication Date:</strong>${this.dateOfPublication}</li>
</ul>
</section>
<section class="newsActions">
<a href='${this.fullArticleLink}' class="button">Full article</a>
<button class="button button-outline">Read Later</button>
</section>
</article>
</li>
`
}
}
|
import Vue from "vue"
import axios from "axios"
import qs from "qs"
import { errorAlert } from "./alert"
import store from "../store/index"
import router from "../router"
let baseUrl = "/api"
Vue.prototype.$img = "http://localhost:3000"
// 响应拦截
axios.interceptors.response.use(res => {
console.log(res.config.url)
console.log(res)
if (res.data.code !== 200) {
errorAlert(res.data.msg)
}
// if(res.config.url==baseUrl+"/api/menulist"){
// res.data.msg="登录已过期或访问权限受限"
// }
if (res.data.msg === "登录已过期或访问权限受限") {//掉线了
//清除登录信息
store.dispatch("changeUser", {})
//跳转到登录页
router.push("/login")
}
return res;
})
axios.interceptors.request.use(req => {//请求拦截
if (req.url !== baseUrl + "/login") {
req.headers.authorization = store.state.userInfo.token;
}
return req;
})
// 菜单管理列表请求
export const reqMenuList = () => {
return axios({
method: "get",
url: baseUrl + "/api/menulist",
})
}
//菜单管理列表添加请求
export const reqMenuAdd = (form) => {
return axios({
method: "post",
url: baseUrl + "/api/menuadd",
data: qs.stringify(form)
})
}
//菜单管理列表删除请求
export const reqMenuDel = (id) => {
return axios({
method: "post",
url: baseUrl + "/api/menudelete",
data: qs.stringify({
id
})
})
}
//菜单管理列表修改请求
export const reqMenuDetail = (id) => {
return axios({
url: baseUrl + "/api/menuinfo",
method: "get",
params: {
id: id
}
})
}
//菜单管理交互请求
export const reqMenuListAll = () => {
return axios({
url: baseUrl + "/api/menulist",
method: "get",
params: {
istree: true
}
})
}
// 修改
export const reqMenuUpdate = (form) => {
return axios({
url: baseUrl + "/api/menuedit",
method: "post",
data: qs.stringify(form)
})
}
// ===========================角色添加开始=============================
export const resRolAdd = (user) => {//角色添加
return axios({
method: "post",
url: baseUrl + "/api/roleadd",
data: qs.stringify(user)
})
}
export const resRolList = () => {//角色列表
return axios({
method: "get",
url: baseUrl + "/api/rolelist"
})
}
export const resRolDel = (id) => {//角色删除
console.log(id)
return axios({
method: "post",
url: baseUrl + "/api/roledelete",
data: qs.stringify({ id })
})
}
export const reqRolDetail = (id) => {//角色详情
return axios({
method: "get",
url: baseUrl + "/api/roleinfo",
params: {
id
}
})
}
export const reqRolEdit = (user) => {//角色详情
return axios({
method: "post",
url: baseUrl + "/api/roleedit",
data: qs.stringify(user)
})
}
// ===========================角色添加结束====================================
// ===========================管理员列表开始====================================
// 参数格式{size,page}
export const resUserList = (p) => {//管理员列表
console.log(p)
return axios({
method: "get",
url: baseUrl + "/api/userlist",
params: p
})
}
export const resUserDetail = (uid) => {//管理圆详情
return axios({
method: "get",
url: baseUrl + "/api/userinfo",
params: {
uid
}
})
}
export const resUserUpdate = (user) => {//管理圆修改
return axios({
method: "post",
url: baseUrl + "/api/useredit",
data: qs.stringify(user)
})
}
export const reqUserDel = (uid) => {//管理圆删除
return axios({
method: "post",
url: baseUrl + "/api/userdelete",
data: qs.stringify({ uid })
})
}
export const reqUserAdd = (user) => {//管理圆添加
return axios({
method: "post",
url: baseUrl + "/api/useradd",
data: qs.stringify(user)
})
}
export const reqUserCount = (user) => {//管理圆总数
return axios({
method: "get",
url: baseUrl + "/api/usercount"
})
}
// ===========================管理员列表结束====================================
// ===========================管理员登陆开始====================================
export const reqUserLogin = (user) => {//管理圆总数
return axios({
method: "post",
url: baseUrl + "/api/userlogin",
data: user
})
}
// ===========================管理员登陆结束====================================
// ===========================商品分类开始====================================
// 参数格式{size,page}
export const resCateList = (list) => {//商品分类列表
return axios({
method: "get",
url: baseUrl + "/api/catelist",
params: list
})
}
export const resCateDetail = (id) => {//商品分类获取(一条)
return axios({
method: "get",
url: baseUrl + "/api/cateinfo",
params: {
id
}
})
}
export const resCateUpdate = (cate) => {//商品分类修改
let d = new FormData();
for (let key in cate) {
d.append(key, cate[key])
}
return axios({
method: "post",
url: baseUrl + "/api/cateedit",
data: d
})
}
export const reqCateDel = (id) => {//商品分类删除
return axios({
method: "post",
url: baseUrl + "/api/catedelete",
data: qs.stringify({ id })
})
}
export const reqCateAdd = (cate) => {//商品分类添加
let d = new FormData();
for (let key in cate) {
d.append(key, cate[key])
}
return axios({
method: "post",
url: baseUrl + "/api/cateadd",
data: d
})
}
// ===========================商品分类结束====================================
// ===========================商品规格列表开始====================================
// 参数格式{size,page}
export const resSpecsList = (list) => {//商品规格列表(分页)
console.log(list)
return axios({
method: "get",
url: baseUrl + "/api/specslist",
params: list
})
}
export const resSpecsDetail = (id) => {//商品规格获取(一条)
return axios({
method: "get",
url: baseUrl + "/api/specsinfo",
params: {
id
}
})
}
export const resSpecsUpdate = (specs) => {//商品规格修改
console.log(specs)
return axios({
method: "post",
url: baseUrl + "/api/specsedit",
data: qs.stringify(specs)
})
}
export const reqSpecsDel = (id) => {//商品规格删除
return axios({
method: "post",
url: baseUrl + "/api/specsdelete",
data: qs.stringify({ id })
})
}
export const reqSpecsAdd = (specs) => {//商品规格添加
return axios({
method: "post",
url: baseUrl + "/api/specsadd",
data: qs.stringify(specs)
})
}
export const reqSpecsCount = (specs) => {//商品规格总数
return axios({
method: "get",
url: baseUrl + "/api/specscount"
})
}
// ===========================商品规格列表结束====================================
// ===========================会员开始====================================
export const reqMemberList = () => {//会员列表
return axios({
method: "get",
url: baseUrl + "/api/memberlist"
})
}
export const reqMemberDetail = (uid) => {//会员获取(一条)
return axios({
method: "get",
url: baseUrl + "/api/memberinfo",
params: {
uid
}
})
}
export const reqMemberUpdate = (vip) => {//会员修改
console.log(vip)
return axios({
method: "post",
url: baseUrl + "/api/memberedit",
data: qs.stringify(vip)
})
}
// ===========================会员结束====================================
// ===========================轮播图开始====================================
export const reqBannerList = () => {//轮播图列表
return axios({
method: "get",
url: baseUrl + "/api/bannerlist"
})
}
export const reqBannerDetail = (id) => {//轮播图获取(一条)
return axios({
method: "get",
url: baseUrl + "/api/bannerinfo",
params: {
id
}
})
}
export const reqBannerUpdate = (banner) => {//轮播图修改
let d = new FormData();
for (let key in banner) {
d.append(key,banner[key])
}
return axios({
method: "post",
url: baseUrl + "/api/banneredit",
data: d
})
}
export const reqBannerDel = (id) => {//轮播图删除
return axios({
method: "post",
url: baseUrl + "/api/bannerdelete",
data: qs.stringify({id})
})
}
export const reqBannerAdd = (banner) => {//轮播图添加
console.log(banner);
let d = new FormData();
for (let key in banner) {
d.append(key,banner[key])
}
console.log(d);
return axios({
method: "post",
url: baseUrl + "/api/banneradd",
data: d
})
}
// ===========================轮播图结束====================================
// ===========================商品管理开始====================================
export const reqGoodsList = (p) => {//商品列表(分页)
console.log(p)
return axios({
method: "get",
url: baseUrl + "/api/goodslist",
params:p,
})
}
export const reqGoodsDetail = (id) => {//商品获取(一条)
return axios({
method: "get",
url: baseUrl + "/api/goodsinfo",
params: {
id
}
})
}
export const reqGoodsCount = () => {//商品获取(总数)
return axios({
method: "get",
url: baseUrl + "/api/goodscount",
})
}
export const reqGoodsUpdate = (goods) => {//商品修改
let d = new FormData();
for (let key in goods) {
d.append(key,goods[key])
}
return axios({
method: "post",
url: baseUrl + "/api/goodsedit",
data: d
})
}
export const reqGoodsDel = (id) => {//商品删除
return axios({
method: "post",
url: baseUrl + "/api/goodsdelete",
data: qs.stringify({id})
})
}
export const reqGoodsAdd = (goods) => {//商品添加
console.log(goods);
let d = new FormData();
for (let key in goods) {
d.append(key,goods[key])
}
console.log(d);
return axios({
method: "post",
url: baseUrl + "/api/goodsadd",
data: d
})
}
// ===========================商品管理结束====================================
// ===========================商品管理开始====================================
export const reqSecksList = (p) => {//限时秒杀列表
return axios({
method: "get",
url: baseUrl + "/api/secklist",
params:p,
})
}
export const reqSecksDetail = (id) => {//限时秒杀获取(一条)
return axios({
method: "get",
url: baseUrl + "/api/seckinfo",
params:{id}
})
}
export const reqSecksDel = (id) => {//限时秒杀删除
return axios({
method: "post",
url: baseUrl + "/api/seckdelete",
data: qs.stringify({id})
})
}
export const reqSecksAdd = (secks) => {//限时秒杀添加
console.log(secks);
return axios({
method: "post",
url: baseUrl + "/api/seckadd",
data: qs.stringify(secks)
})
}
export const reqSecksUpdate = (secks) => {//限时秒杀修改
console.log(secks);
return axios({
method: "post",
url: baseUrl + "/api/seckedit",
data: qs.stringify(secks)
})
}
// ===========================商品管理结束====================================
|
const express = require('express');
const router = express.Router();
const db = require('../config/db_functions');
const bodyParser = require('body-parser')
const bcrypt = require('bcryptjs');
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())
const { ensureAuthenticated } = require('../config/auth');
const passport = require('passport');
router.post( '/login', (req, res, next) => {
passport.authenticate('local', {
session: true,
successRedirect: '/home',
failureRedirect: '/login',
failureFlash: true
})(req, res, next);
},
);
router.get('/logout', (req, res) => {
req.logout();
// req.session = null;
// req.flash('success_msg', 'You are logged out');
// req.user = null;
req.session.destroy();
res.redirect('/home')
});
router.get( '/', function( req, res ) {
res.redirect('/home');
});
router.get( '/login', function( req, res ) {
res.render( './page/db/login', { title: "Login" } );
});
router.get( '/home', function( req, res ) {
// res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
const get_qtd_cursos = "SELECT COUNT(cod_curso) FROM curso;"
db.getRecords( get_qtd_cursos, (result) => {
res.render( './page/ws/home', { title: "PPC Choice - Home", qtd_cursos: result.rows[0].count, user: req.user });
})
});
router.get( '/comparison', ensureAuthenticated, function( req, res ) {
const get_cursos = "SELECT C.cod_curso, C.nome, C.cod_ppc, C.ch_total_curso, P.status FROM curso as C, projeto_pedagogico_curso as P WHERE C.cod_ppc = P.cod_ppc;"
db.getRecords( get_cursos, (result) => {
res.render('./page/ws/comparison', { title: 'PPC Choice - Comparison', cursos : result.rows, user: req.user } )
})
});
router.get( '/getGrade/:idCurso', function( req, res ) {
const get_dp = "SELECT * FROM dependencia WHERE cod_comp_curricular IN (\
SELECT cod_comp_curricular FROM componente_curricular WHERE cod_ppc = " + req.params.idCurso + " );"
const get_grade = "SELECT D.nome, D.carga_horaria, CC.cod_comp_curricular, CC.periodo from disciplina as D, componente_curricular as CC \
WHERE CC.cod_ppc = " + req.params.idCurso + " AND CC.cod_disciplina = D.cod_disciplina AND CC.cod_departamento = D.cod_departamento ORDER BY CC.cod_comp_curricular;"
var returnVals, ret, data;
db.getRecords( get_grade, (result) => {
ret = result.rows
db.getRecords( get_dp, (result) => {
ret_dp = result.rows
data = { grade : ret, depend: ret_dp }
res.send( data );
});
})
})
router.get( '/getReaprov/:idCurso', function( req, res ) {
const get_reaprov = "SELECT * FROM reaproveitamento WHERE cod_ppc_destino = " + req.params.idCurso + ";"
db.getRecords( get_reaprov, (result) => {
res.send( result.rows );
});
})
router.get('/compare/:idCursoAtual/:idCursoAlvo', function( req, res ){
const get_ppc = "SELECT cod_ppc FROM curso WHERE cod_curso = " + req.params.idCursoAtual;
const get_dp = "SELECT * FROM corresponde WHERE cod_comp_curricular IN (\
SELECT cod_comp_curricular FROM componente_curricular WHERE cod_ppc IN (" + get_ppc + ") );"
var returnVals, ret, data;
db.getRecords( get_dp, (result) => {
res.send({ equiv: result.rows })
})
});
router.get( '/settings/password', ensureAuthenticated, function( req, res ) {
res.render('./page/db/password_change', { title: 'Settings - Password'} )
});
router.post( '/update/password', ensureAuthenticated, (req, res, next) => {
const user_form = { current_password : req.body.current_password,
new_password : req.body.new_password,
confirm_new_password: req.body.confirm_new_password }
const get_users = "SELECT * FROM usuario WHERE email = '" + user.email + "';"
db.getRecords( get_users, (result) => {
if ( result.rows.length > 0 )
{
user = result.rows[0];
bcrypt.compare(user_form.current_password, user.senha, (err, isMatch) =>
{
if (err) throw err;
if (isMatch)
{
bcrypt.genSalt(10, (err, salt) =>
{
bcrypt.hash( user_form.new_password, salt, (err, hash) =>
{
if (err) throw err;
const update = "UPDATE usuario SET senha = '" + hash + "' WHERE email = '" + user.email + "' ;"
db.getRecords( update, (result) =>
{
console.log(result.rows)
res.send( "Senha alterada com sucesso!");
})
});
});
} else
res.send("senha atual nao confere!")
});
} else
res.send("usuario nao existe mais!")
});
});
module.exports = router;
|
$(function() {
var key = getCookie('key');
if (!key) {
window.location.href = WapSiteUrl + '/tmpl/member_system/login.html';
return;
}
$.ajax({
type: 'post',
url: ApiUrl + "/index.php?act=member_property&op=memberEquity",
data: { key: key },
dataType: 'json',
success: function(result) {
checkLogin(result.login);
$('#equity').html(result.datas.amount);
var html = '';
var list = result.datas.list;
if (list.length > 0) {
for (var i = 0; i < list.length; i++) {
html += '<li>';
html += '<dl>';
html += '<dt>' + list[i].title + '</dt>';
html += '<dd>' + list[i].time + '</dd>';
html += '</dl>';
if (list[i].amount >= 0) {
html += '<div class="money add">' + list[i].amount + '</div>';
} else {
html += '<div class="money reduce">' + list[i].amount + '</div>';
}
html += '<time class="date"></time>';
html += '</li>';
}
} else {
html += '<div class="nctouch-norecord equity">';
html += '<div class="norecord-ico"><i></i></div>';
html += '<dl>';
html += '<dt>你还没可看的明细</dt>';
html += '<dd>赶紧去购买更多喜欢的</dd>';
html += '</dl>';
html += '</div>';
}
$('#equity-list').append(html);
}
});
$('#equity-num').click(function() {
$.ajax({
type: 'post',
url: ApiUrl + '/index.php?act=member_property&op=memberEquityNum',
data: { key: key },
dataType: 'json',
success: function(result) {
alert('金券数量:' + result.datas.amount);
}
});
});
});
|
$(document).ready(function() {
//遍历购物车内的素有商品
$.getJSON('shop.json', function(result) {
var storeCont;
var goodsCont;
var storeArray = new Array();
var i = 0;
$.each(result, function(i, store) {
var storeText = store.store;
//获取购物车内所有商品的店铺,如果店铺名相同不再追加栏目
if(storeArray.indexOf(storeText) == -1) {
storeArray.push(storeText);
storeCont = '<div class="dianpudiv">' +
'<div class="dianpunamediv"><div class="dianpuname_cion"><img src="img/shop/icon_shop.png"/></div><span class="dianpuname_font">' + store.store + '</span></div>' +
'<div class="goodsdiv"></div>' +
'<div class="huizongdiv"><span class="zongji">共<span class="xiaoji-number">x</span>件商品</span></span><span class="xiaoji_jine">¥98.00</span><span class="xiaoji">小计:</span></div>' +
'</div>';
$('.content').append(storeCont);
}
});
//获取购物车商品的店铺数量(不包括重复店铺)
var all = $('.dianpuname_font').size();
for(i; i < all; i++) {
var storeName = $('.dianpuname_font').eq(i).text();
var parameter = $('.dianpuname_font').eq(i);
//遍历商品,将商品归类到相应的店铺下
$.each(result, function(j, storee) {
if(storeName == storee.store) {
goodsCont = '<div class="shangpindiv">' +
'<div class="shangpin_cion">' +
'<img src="img/address/normal.png" class="normal" data-id="' + storee.id + '"/>' +
'</div>' +
'<div class="shangpin_img"><img src="' + storee.img + '"/></div>' +
'<div class="shangpin_content">' +
'<div class="shangpin_name">' + storee.tittle + '</div>' +
'<div class="shangpin_kouwei">口味:原味</div>' +
'<div class="shangpin_shuliang">' +
'<div class="shuliang_left">-</div>' +
'<div class="shuliang_middle">' + storee.number + '</div>' +
'<div class="shuliang_right">+</div>' +
'</div>' +
'</div>' +
'<div class="shangpin_money">' +
'<span>¥</span><span class="xianjia">' + storee.price + '.00</span>' +
'<div class="yuanjia">¥' + storee.oldprice + '.00</div>' +
'<div class="delete"><img src="img/address/btn_deleted.png"/></div>' +
'</div>' +
'</div>';
$('.goodsdiv').eq(i).append(goodsCont);
}
});
//计算下每个店铺的小计金额
xiaoji(parameter);
}
//全选选中与取消
$(".gouxuan").on("click", function() {
var status = $(this).find("img").attr("src");
//取消全选,并计算合计金额
if(status.indexOf("normal.png") == -1) {
$(".shangpin_cion img").attr("src", "img/address/normal.png");
$(".gouxuan img").attr("src", "img/address/normal.png");
$(".jiesuan-number").html("");
heji();
}
//全选,并计算合计金额
else {
$(".shangpin_cion img").attr("src", "img/address/selected.png");
$(".gouxuan img").attr("src", "img/address/selected.png");
number();
heji();
}
//定义函数,获取勾选的数量。将数量显示在共X件商品中
function number() {
var chknum = $(".shangpin_cion").size();
$(".jiesuan-number").html("(" + chknum + ")")
}
})
//商品选中和取消选中
$(".shangpin_cion").on("click", function() {
var status = $(this).find("img").attr("src");
if(status.indexOf("normal.png") == -1) {
$(this).find("img").attr("src", "img/address/normal.png");
allchk();
heji();
} else {
$(this).find("img").attr("src", "img/address/selected.png");
allchk();
heji();
}
//定义个函数,如果商品一个个选,全部选中后和全选按钮做关联
function allchk() {
var chknum = $(".shangpin_cion").size();
var chk = 0;
$(".shangpin_cion").each(function() {
var zhuangtai = $(this).find("img").attr("src");
if(zhuangtai.indexOf("normal.png") == -1) {
chk++;
$(".jiesuan-number").html("(" + chk + ")")
}
})
//如果商品都被逐个选中,全选按钮也要被选中
if(chknum == chk) {
$(".gouxuan img").attr("src", "img/address/selected.png");
} else if(chk == 0) {
$(".jiesuan-number").html("");
}
//如果商品都逐个被选中,取消选中一个商品,去选按钮也要被取消掉
else {
$(".gouxuan img").attr("src", "img/address/normal.png");
}
}
})
//每次数量增加,小计合计数量栏目实时变化
$(".shuliang_right").on("click", function() {
var a = $(this).siblings(".shuliang_middle");
a.html(parseInt(a.html()) + 1);
xiaoji(a);
heji();
})
//每次数量减少,小计合计数量栏目实时变化
$(".shuliang_left").on("click", function() {
var a = $(this).siblings(".shuliang_middle");
//当数量小于或等于1后,点击按钮无反应
if(a.html() <= 1) {
a.html(1);
} else {
a.html(parseInt(a.html()) - 1);
xiaoji(a);
heji();
}
})
//核对小计金额
function xiaoji(canshu) {
var xiaoji = 0;
var dianpushuliang = 0;
//每个店铺对应一个小计,遍历所有店铺下的小计
canshu.parents(".dianpudiv").find(".shangpindiv").each(function() {
//店铺下所有商品价格和数量和
xiaoji += parseInt($(this).find(".shuliang_middle").html()) * parseFloat($(this).find(".xianjia").html());
dianpushuliang += parseInt($(this).find(".shuliang_middle").html());
})
canshu.parents(".dianpudiv").find(".xiaoji_jine").html("¥" + xiaoji.toFixed(2));
canshu.parents(".dianpudiv").find(".xiaoji-number").html(dianpushuliang);
}
//核对合计金额
function heji() {
var heji = 0;
var allshuliang = 0;
//遍历所有被勾选商品的总金额
$(".shangpindiv").each(function() {
var status = $(this).find(".shangpin_cion img").attr("src");
if(status.indexOf("normal.png") == -1) {
heji += parseInt($(this).find(".shuliang_middle").html()) * parseFloat($(this).find(".xianjia").html());
allshuliang += parseInt($(this).find(".shuliang_middle").html());
}
})
$(".shuju_jine").html(heji.toFixed(2));
$(".heji-number").html(allshuliang);
}
heji();
//删除购物车中的商品
$(".delete").on("click", function() {
$(".tanchuang").css("display", "block");
$(".quxiao").on("click", function() {
$(".tanchuang").css("display", "none");
})
$(".queren").on("click", function() {
var divnumber = a.parents(".shangpindiv").siblings(".shangpindiv").size();
$(".tanchuang").css("display", "none");
if(divnumber == 0)
a.parents(".dianpudiv").remove();
else {
a.parents(".shangpindiv").remove();
divnumber--;
}
})
})
//跳转到确认订单页
$(".button_jiesuan").on("click", function() {
var money = $('.shuju_jine').text();
var all = $('.normal').size();
var j = 0,
s = 0;
var canshuArray = [];
for(j; j < all; j++) {
var status = $('.normal').eq(j).attr('src');
if(status.indexOf("normal.png") == -1) {
var goid = $('.normal').eq(j).attr("data-id");
canshuArray.push(goid);
}
}
window.location = "confirmOrder.html?money=" + money + "&goid=" + canshuArray.toString();
})
});
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.