text
stringlengths 7
3.69M
|
|---|
var fs = require("fs");
var inquirer = require("inquirer");
function ClozeCard (cloze, partial, ) {
this.cloze = cloze;
this.partial = partial;
}
inquirer.prompt([
{
name: "cloze",
message: "Enter Cloze Portion"
}, {
name: "partial",
message: "Enter Partial Portion"
}
]).then(function(createQ) {
var newQuestion = new ClozeCard(ClozeCard.cloze, ClozeCard.partial);
var logCloze = "\nFront " + ClozeCard.cloze + " Back: " + ClozeCard.partial;
fs.appendFile("ClozeCards.txt", logCloze);
});
module.exports = ClozeCard;
|
/*
* Property of SunGard© Data Systems Inc. or its affiliates, all rights reserved.
* SunGard Confidential.
*
* Copyright (c) 1993-2014 Sungard Wealth Management All Rights Reserved.
*
* This software is the confidential and proprietary information of Sungard
* Expert Solutions ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the terms
* of the license agreement you entered into with Sungard Expert Solutions.
*
* SUNGARD WEALTH MANAGEMENT MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
* SUITABILITY OF THE SOFTWARE OR ASSOCIATED DOCUMENTATION, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. SUNGARD WEALTH MANAGEMENT SHALL NOT BE LIABLE FOR ANY
* DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext*/
Ext.define('MyRetirement.view.whatif.PanelParticipant', {
extend: 'MyRetirement.view.AppPanel'
,xtype: 'whatif-panel-participant'
,requires: [
'MyRetirement.view.whatif.ChartParticipant'
,'MyRetirement.view.whatif.TableParticipant'
,'MyRetirement.view.whatif.FooterParticipant'
]
,nextButton: false
,backButton: true
,componentCls: 'whatif-panel-participant'
,items: [{
xtype: 'whatif-chart-participant'
},{
xtype: 'whatiffooterparticipant',
cls:'whatIfChartLegend'
},{
cls: 'additional-investing'
,id: 'additionalInvestingTable'
,title: 'Additional Investing'
,items: [{
xtype: 'component'
,autoEl: 'header'
,name: 'taxTypeCode'
,cls: 'panel-body-header'
,html: [
'<div class="tools">'
,'<span id="whatif-panel-title" class="left save-more-title"><h1>What If – Saving More</h1></span>'
,'<span class="left"><select id="tax-type-selector" name="taxTypeCode" '
,'class="table-header-dropDown" '
,'onmouseover="MyRetirement.helpFieldMouseOver(Ext.get(\'tax-type-selector\'))" '
,'onfocusgained="MyRetirement.helpFieldGainFocus(Ext.get(\'tax-type-selector\'))">'
,'<option value="0">Taxable</option> <option value="1">Tax-free</option> <option selected value="2">Tax-deferred</option></select> </span>'
,'</div>'
]
},{
xtype: 'whatif-table-participant'
},{
xtype: 'component'
,itemId: 'summary'
,autoEl: 'footer'
,cls: 'panel-body-footer'
,style: 'height: 35px !important;'
,tpl: [
'<p>The {monthlyContribution:currency("$",0)} amount is after tax '
,'({clientFinancialProfileAverageTaxRate:number("0.00") * 100}% tax rate), '
,'increases annually with inflation ({clientFinancialProfileAnnualInflationRate:number("0.00") * 100}% inflation rate), '
,'will continue until retirement ({additionalContributionsMonths} months of contributions), '
,'and assumes a {preRetirementRiskToleranceLabel} risk tolerance portfolio.</p>'
]
}]
}]
});
|
import React from 'react';
import './App.css'
export default function (props) {
const { onCloseSearch, onOpenSearch, onChangeShelf, onSearch,
showSearchPage, books } = props
return (
<div className="app">
{showSearchPage ? (
<div className="search-books">
<div className="search-books-bar">
<a className="close-search" onClick={onCloseSearch}>Close</a>
<div className="search-books-input-wrapper">
<input type="text" placeholder="Search by title or author" onChange={(e) => onSearch(e)}/>
<div className="bookshelf-books">
<ol className="books-grid">
{ books && books.length > 0 ? (
(books || []).map((b, i) => (
<li key={i}>
<div className="book">
<div className="book-top">
<div className="book-cover" style={{ width: 128, height: 193, backgroundImage: `url(${b.imageLinks.smallThumbnail})` }}></div>
<div className="book-shelf-changer">
<select onChange={(e) => onChangeShelf(e, b)}>
<option value="move" disabled>Move to...</option>
<option value="currentlyReading">Currently Reading</option>
<option value="wantToRead">Want to Read</option>
<option value="read">Read</option>
</select>
</div>
</div>
<div className="book-title">{b.title}</div>
{(b.authors).map((a, i) => (
<div className="book-authors" key={i}>
{a}
</div>
))}
</div>
</li>
)
)) : (
<h2 className="bookshelf-title">The books not found</h2>
)}
</ol>
</div>
</div>
</div>
<div className="search-books-results">
<ol className="books-grid"></ol>
</div>
</div>
) : (
<div className="list-books">
<div className="list-books-title">
<h1>MyReads</h1>
</div>
<div className="list-books-content">
<div>
<div className="bookshelf">
<h2 className="bookshelf-title">Currently Reading</h2>
<div className="bookshelf-books">
<ol className="books-grid">
{(books || []).filter(b => { return b.shelf === 'currentlyReading'}).map((b, i) => (
<li key={i}>
<div className="book">
<div className="book-top">
<div className="book-cover" style={{ width: 128, height: 193, backgroundImage: `url(${b.imageLinks.smallThumbnail})` }}></div>
<div className="book-shelf-changer">
<select onChange={(e) => onChangeShelf(e, b)}>
<option value="move" disabled>Move to...</option>
<option value="currentlyReading">Currently Reading</option>
<option value="wantToRead">Want to Read</option>
<option value="read">Read</option>
</select>
</div>
</div>
<div className="book-title">{b.title}</div>
{(b.authors).map((a, i) => (
<div className="book-authors" key={i}>
{a}
</div>
))}
</div>
</li>
)
)}
</ol>
</div>
</div>
<div className="bookshelf">
<h2 className="bookshelf-title">Want to Read</h2>
<div className="bookshelf-books">
<ol className="books-grid">
{(books || []).filter(b => { return b.shelf === 'wantToRead'}).map((b, i) => (
<li key={i}>
<div className="book">
<div className="book-top">
<div className="book-cover" style={{ width: 128, height: 193, backgroundImage: `url(${b.imageLinks.smallThumbnail})` }}></div>
<div className="book-shelf-changer">
<select onChange={(e) => onChangeShelf(e, b)}>
<option value="move" disabled>Move to...</option>
<option value="currentlyReading">Currently Reading</option>
<option value="wantToRead">Want to Read</option>
<option value="read">Read</option>
<option value="none">None</option>
</select>
</div>
</div>
<div className="book-title">{b.title}</div>
{(b.authors).map((a, i) => (
<div className="book-authors" key={i}>
{a}
</div>
))}
</div>
</li>
)
)}
</ol>
</div>
</div>
<div className="bookshelf">
<h2 className="bookshelf-title">Read</h2>
<div className="bookshelf-books">
<ol className="books-grid">
{(books || []).filter(b => { return b.shelf === 'read'}).map((b, i) => (
<li key={i}>
<div className="book">
<div className="book-top">
<div className="book-cover" style={{ width: 128, height: 193, backgroundImage: `url(${b.imageLinks.smallThumbnail})` }}></div>
<div className="book-shelf-changer">
<select onChange={(e) => onChangeShelf(e, b)}>
<option value="move" disabled>Move to...</option>
<option value="currentlyReading">Currently Reading</option>
<option value="wantToRead">Want to Read</option>
<option value="read">Read</option>
<option value="none">None</option>
</select>
</div>
</div>
<div className="book-title">{b.title}</div>
{(b.authors).map((a, i) => (
<div className="book-authors" key={i}>
{a}
</div>
))}
</div>
</li>
)
)}
</ol>
</div>
</div>
</div>
</div>
<div className="open-search">
<a onClick={onOpenSearch}>Add a book</a>
</div>
</div>
)}
</div>
)
}
|
import React from "react";
import GameController from "./components/GameController"
const App = () => (
<GameController/>
)
export default App;
|
var BaseTask = require('./base'),
gulp = require('gulp'),
plumber = require('gulp-plumber'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
notify = require('gulp-notify'),
sourcemaps = require('gulp-sourcemaps'),
gulpif = require('gulp-if'),
lib = require('./../lib');
var SolidConcat = function (key, options, config) {
this._prefix = 'concat.'
this._message = 'Javascript combined'
this._key = this._prefix + key
this._config = config
this._options = options
this._as = null
this._to = null
this._uglifyOptions = {}
this._useSourcemaps = false;
}
SolidConcat.prototype = new BaseTask;
SolidConcat.prototype.constructor = SolidConcat
SolidConcat.prototype.beautify = function () {
this._uglifyOptions = {
mangle: false,
compress: false,
output: {
beautify: true
}
}
return this
}
SolidConcat.prototype.sourcemaps = function () {
this._useSourcemaps = true
return this
}
SolidConcat.prototype.to = function(to) {
var self = this
this._to = to
var isLocal = this._config.isLocal
return gulp.task(self._key, function () {
return gulp.src(lib.pathKey(self._key, self._config))
.pipe(plumber({errorHandler: lib.onError}))
.pipe(gulpif(self._useSourcemaps, sourcemaps.init()))
.pipe(concat(self._as))
.pipe(uglify(self._uglifyOptions))
.pipe(gulpif(self._useSourcemaps, sourcemaps.write()))
.pipe(gulp.dest( self._config.asset_path + self._to ))
.pipe(gulpif(isLocal, notify({ message: self._message })))
});
}
module.exports = exports = SolidConcat;
|
const types = {
TOGGLE_LOADING: 'TOGGLE_LOADING',
TOGGLE_SIDEBAR: 'TOGGLE_SIDEBAR',
TOGGLE_SIDEBAR_SHOW: 'TOGGLE_SIDEBAR_SHOW',
TOGGLE_DEVICE: "TOGGLE_DEVICE",
EXPAND_MENU: 'EXPAND_MENU',
SWITCH_EFFECT: 'SWITCH_EFFECT',
LOAD_MENU: 'LOAD_MENU',
LOAD_CURRENT_MENU: 'LOAD_CURRENT_MENU',
SET_USER_INFO: 'SET_USER_INFO',
SET_COLLAPSE: 'SET_COLLAPSE',
SET_INDEX: 'SET_INDEX',
SET_LOG: 'SET_LOG',
SET_SENDERID: 'SET_SENDERID',
SET_WEBSOCKET: 'SET_WEBSOCKET',
SET_CHANGE: 'SET_CHANGE',
SET_USER: 'SET_USER',
SET_MSG_LIST: 'SET_MSG_LIST',
SET_SYS_LIST: 'SET_SYS_LIST',
}
export default types
|
let base = require('../base'), //引入base
bodyParser = require('body-parser'), //解析params
urlencodedParser = bodyParser.urlencoded({ extended: false }); //
function returnResult(message){
if(message)
return {success: false, message: message};
else
return {success: true}
}
function removeNullKey(obj){
for(var i in obj){
if(obj[i] === null)
delete obj[i];
}
}
exports.handler = function(connection, app){
//获取登录者信息
app.get('/userInfo', function(req, res){
var userName = req.session.user;
if(!userName) throw 'session expired';
connection.query(base.getUserInfo(userName), function(err, userInfo){
removeNullKey(userInfo[0]);
var obj = {
success:true
};
if(userInfo.length)
obj['userInfo'] = userInfo[0];
if(err) throw err;
res.status(200);
res.json(obj);
});
});
//编辑资料
app.post('/editInfo', urlencodedParser, function(req, res){
if(!req.session.user){
res.redirect('/');
return false;
}else{
var userName = req.session.user;
// console.log(req.body, userName);
connection.query(base.editInfo(req.body, userName),function(err, result){
if(err) throw err;
console.log(result);
res.status(200);
res.json({
success: true,
message: '修改资料成功'
});
});
}
});
//收到提交的建议
app.post('/feedback', urlencodedParser, function(req, res){
connection.query("insert into feedBack(name, content) values (?, ?)",[req.body.name, req.body.content],function(err){
if(err) throw err;
res.status(200);
res.json({success: true, message: "反馈成功"});
})
});
}
|
var request = require('request');
var defaultConfig = {
server: {host:'throwandtell.com', port:80},
autoHookUncaught: true,
accessKey: null,
verbose: true
};
var ThrowAndTell = function(config) {
// Validate Config
this.config = defaultConfig;
for(var i in config) this.config[i] = config[i];
if(!this.config.accessKey) throw new Error("An accessKey must be provided when creating a ThrowAndTell Instance");
// HookUncaught Abiding by Config
if(this.config.autoHookUncaught)
this.hookUncaught();
return this;
};
ThrowAndTell.prototype.hookUncaught = function() {
var self = this;
process.on('uncaughtException', function(err) {
if(self.config.verbose) console.log('Caught \'' + err.message + '\'');
self.report(err, function(fail) {
if(fail) return console.warn('ThrowAndTell: Unable to Report Error due to:', ok);
if(self.config.verbose) console.log('\'' + err.message + '\' has been reported to ThrowAndTell');
});
});
};
ThrowAndTell.prototype.report = function(err, dataOrCb, cb) {
if(typeof dataOrCb == "function") cb = dataOrCb;
if(!err.stack) return cb(new Error("Given err does not give a stack"));
request({
uri: 'http://' + this.config.server.host + ':' + this.config.server.port + '/api/v1/report?access_key=' + this.config.accessKey,
method: 'POST',
json: {trace:err.stack},
timeout: 10000
}, function(err, res, body) {
if(err) return cb(err);
if(body.error) return cb(new Error(body.error));
cb(null, true);
});
};
module.exports = ThrowAndTell;
|
import React, { useCallback, useMemo, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import {
FlatList,
SafeAreaView,
StyleSheet,
TextInput,
TouchableOpacity,
TouchableWithoutFeedback,
View
} from 'react-native';
import Modal from 'react-native-modal';
import Icon from 'react-native-vector-icons/Ionicons';
import Fuse from 'fuse.js';
import Device from '../../../../util/Device';
import { strings } from '../../../../../locales/i18n';
import Text from '../../../Base/Text';
import ListItem from '../../../Base/ListItem';
import ModalDragger from '../../../Base/ModalDragger';
import { colors, fontStyles } from '../../../../styles/common';
const styles = StyleSheet.create({
modal: {
margin: 0,
justifyContent: 'flex-end'
},
modalView: {
backgroundColor: colors.white,
borderTopLeftRadius: 10,
borderTopRightRadius: 10
},
inputWrapper: {
flexDirection: 'row',
alignItems: 'center',
marginHorizontal: 30,
marginVertical: 10,
paddingVertical: Device.isAndroid() ? 0 : 10,
paddingHorizontal: 5,
borderRadius: 5,
borderWidth: 1,
borderColor: colors.grey100
},
searchIcon: {
marginHorizontal: 8
},
input: {
...fontStyles.normal,
flex: 1
},
modalTitle: {
marginTop: Device.isIphone5() ? 10 : 15,
marginBottom: Device.isIphone5() ? 5 : 5,
marginHorizontal: 36
},
resultsView: {
height: Device.isSmallDevice() ? 130 : 250,
marginTop: 10
},
resultRow: {
borderTopWidth: StyleSheet.hairlineWidth,
borderColor: colors.grey100,
paddingHorizontal: 20
},
flag: {
fontSize: 24
},
emptyList: {
marginVertical: 10,
marginHorizontal: 30
}
});
function CountrySelectorModal({ isVisible, dismiss, countries, onItemPress }) {
const searchInput = useRef(null);
const list = useRef();
const [searchString, setSearchString] = useState('');
const countriesFuse = useMemo(
() =>
new Fuse(countries, {
shouldSort: true,
threshold: 0.45,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: ['name', 'currency', 'code', 'label']
}),
[countries]
);
const countriesSearchResults = useMemo(
() => (searchString.length > 0 ? countriesFuse.search(searchString) : countries),
[searchString, countriesFuse, countries]
);
const handleSearchPress = () => searchInput?.current?.focus();
const handleSearchTextChange = useCallback(text => {
setSearchString(text);
if (list.current) list.current.scrollToOffset({ animated: false, y: 0 });
}, []);
const renderItem = useCallback(
({ item }) => (
<TouchableOpacity style={styles.resultRow} onPress={() => onItemPress(item.code)}>
<ListItem>
<ListItem.Content>
<ListItem.Icon>
<Text style={styles.flag}>{item.label}</Text>
</ListItem.Icon>
<ListItem.Body>
<ListItem.Title>{item.name}</ListItem.Title>
</ListItem.Body>
</ListItem.Content>
</ListItem>
</TouchableOpacity>
),
[onItemPress]
);
const renderEmptyList = useMemo(
() => (
<View style={styles.emptyList}>
<Text>{strings('fiat_on_ramp.no_countries_result', { searchString })}</Text>
</View>
),
[searchString]
);
return (
<Modal
isVisible={isVisible}
onBackdropPress={dismiss}
onBackButtonPress={dismiss}
onSwipeComplete={dismiss}
swipeDirection="down"
propagateSwipe
avoidKeyboard
onModalHide={() => setSearchString('')}
style={styles.modal}
>
<SafeAreaView style={styles.modalView}>
<ModalDragger />
<View style={styles.modalTitle}>
<Text bold centered primary>
{strings('fiat_on_ramp.supported_countries')}
</Text>
<Text centered small>
{strings('fiat_on_ramp.select_card_country')}
</Text>
</View>
<TouchableWithoutFeedback onPress={handleSearchPress}>
<View style={styles.inputWrapper}>
<Icon name="ios-search" size={20} style={styles.searchIcon} />
<TextInput
ref={searchInput}
style={styles.input}
placeholder={strings('fiat_on_ramp.search_country')}
placeholderTextColor={colors.grey500}
value={searchString}
onChangeText={handleSearchTextChange}
/>
</View>
</TouchableWithoutFeedback>
<FlatList
ref={list}
style={styles.resultsView}
keyboardDismissMode="none"
keyboardShouldPersistTaps="always"
data={countriesSearchResults}
renderItem={renderItem}
keyExtractor={item => item.code}
ListEmptyComponent={renderEmptyList}
/>
</SafeAreaView>
</Modal>
);
}
CountrySelectorModal.propTypes = {
isVisible: PropTypes.bool,
dismiss: PropTypes.func,
countries: PropTypes.array,
onItemPress: PropTypes.func
};
export default CountrySelectorModal;
|
const mongoose = require('mongoose');
const movieDetailsSchema = new mongoose.Schema({
name: {
type: String,
required: false
},
status: {
type: String,
required: false
},
rating: {
type: String,
required: false
},
description: {
type: String,
required: false
},
showTimings: {
type: Array,
required: false
},
releaseDate: {
type: String,
required: false
},
showEndDate: {
type: String,
required: false
},
trailerUrl: {
type: String,
required: false
},
posterUrl: {
type: String,
required: false
},
cast: [{
name: {
type: String,
required: false
},
photourl: {
type: String,
required: false
},
role: {
type: String,
required: false
}
}],
budget: {
type: String,
required: false
},
genre: {
type: String,
required: false
},
censorCertificate: {
type: String,
required: false
}
});
module.exports = mongoose.model("Movie", movieDetailsSchema, 'movie');
|
/**
* 分页组件
* @param data 分页数据 Array
* @param node 单页列表所在的元素
* @param father 页码所在的元素
* @constructor
*/
function Paging(data, node, father, config) {
return new Paging.prototype.init(data, node, father, config)
}
Paging.prototype = {
constructor: Paging,
pageSize: 5,
paginationSize: 10,
init: function(data, node, father, config) {
this.dom = father
this.node = node
this.pageNum = 1
if(config){
config.pageSize && (this.pageSize = config.pageSize)
config.paginationSize && (this.paginationSize = config.paginationSize)
}
var eventList = node && node.pagingEventList
if (eventList) {
eventList.forEach(function (v) {
node.removeEventListener(v.event, v.fn)
})
}
node.pagingEventList = []
var oldUl = father.querySelector('.paging-pagination')
oldUl && father.removeChild(oldUl)
if (data && data.length > 0) {
this.data = data
this.maxPage = Math.ceil(data.length / this.pageSize)
this.initPagination()
} else {
this.isEmpty = true
}
return this
},
getData: function (num) {
var self = this
if (num > 0 && num <= self.maxPage) {
var arr = []
self.pageNum = num
for (var i = self.pageSize * (num - 1); i < self.pageSize * num; i++) {
if (self.data[i]) {
arr.push(self.data[i])
} else {
break
}
}
self.ul.innerHTML = self.setPagination()
Array.prototype.forEach.call(self.ul.getElementsByTagName('li'), function (v) {
if (v.innerHTML === self.pageNum + '') {
v.className += ' current'
}
})
return arr
} else if (num === 0) {
alert('已经是第一页了')
} else {
alert('已经是最后一页了')
}
},
update: function(data) {
this.pageNum = 1
var oldUl = this.dom.querySelector('.paging-pagination')
oldUl && this.dom.removeChild(oldUl)
if (data && data.length > 0) {
this.data = data
this.maxPage = Math.ceil(data.length / this.pageSize)
this.isEmpty = false
this.initPagination()
this.template && this.showPage(1)
} else {
this.isEmpty = true
}
return this
},
initPagination: function () {
this.ul = document.createElement('ul')
this.ul.className = 'paging-pagination'
this.dom.appendChild(this.ul)
var self = this
this.ul.onclick = function (e) {
var i = Array.prototype.indexOf.call(this.getElementsByTagName('li'), e.target)
if (i === -1) return
self.showPage(e.target.innerHTML, i)
}
},
showPage: function (page, i) {
var self = this
var pageNum = self.pageNum * 1
var strArr = []
var length = this.dom.querySelectorAll('.paging-pagination li').length
strArr.push(self.header || '')
if (i === undefined) {
strArr.push(self.template(self.getData(page)))
} else {
switch (i) {
case 0:
strArr.push(self.template(self.getData(1)))
break
case 1:
strArr.push(self.template(self.getData(pageNum - 1)))
break
case length - 2:
strArr.push(self.template(self.getData(pageNum + 1)))
break
case length - 1:
strArr.push(self.template(self.getData(self.maxPage)))
break
default:
strArr.push(self.template(self.getData(page)))
}
}
if (strArr.length <= 1 || !strArr[1]) {
return false
}
self.node.innerHTML = strArr.join('')
return self
},
setPagination: function () {
var list = [],
pageNum = this.pageNum * 1
list.push('<li class="paging-pagenum paging-arrow"></li>')
list.push('<li class="paging-pagenum paging-arrow"></li>')
if (this.maxPage <= this.paginationSize) {
for (var i = 0; i < this.maxPage; i++) {
list.push('<li class="paging-pagenum">' + (i + 1) + '</li>')
}
} else if (pageNum + this.paginationSize > this.maxPage) {
for (var i = this.maxPage - this.paginationSize; i < this.maxPage; i++) {
list.push('<li class="paging-pagenum">' + (i + 1) + '</li>')
}
} else {
var start = pageNum - this.paginationSize / 2 <= 0 ? 1 : pageNum - this.paginationSize / 2
for (var i = start; i < start + this.paginationSize; i++) {
list.push('<li class="paging-pagenum">' + i + '</li>')
}
}
list.push('<li class="paging-pagenum paging-arrow"></li>')
list.push('<li class="paging-pagenum paging-arrow"></li>')
return list.join('')
},
setTemplate: function (cb) {
this.template = function (data) {
var arr = []
data && data.forEach(function (v) {
arr.push(cb(v))
})
return arr.join('')
}
this.isEmpty || this.showPage(1)
return this
},
setHeader: function (cb) {
var type = typeof cb
if (type === 'string') {
this.header = cb
} else if (type === 'function') {
var str = cb()
typeof str === 'string' && (this.header = str)
}
return this
},
setEvent: function (event, el, cb) {
var node = this.node
var eventFn = this.bindEvent(el, cb)
this.node.pagingEventList.push({
event: event,
fn: eventFn
})
node.addEventListener(event, eventFn)
return this
},
bindEvent: function (el, cb) {
var self = this
return function (e) {
var indexOf = Array.prototype.indexOf
var doms = this.querySelectorAll(el)
var index = -1
for (var i = 0; i < e.path.length; i++) {
index = indexOf.call(doms, e.path[i])
if (index > -1) break
}
if (index === -1) return
cb(doms[index], index + (self.pageNum - 1) * self.pageSize, doms)
}
},
empty: function (cb) {
if (this.isEmpty) {
var header = this.header || ''
var type = typeof cb
if (type === 'string') {
this.node.innerHTML = header + cb
} else if (type === 'function') {
var str = cb()
typeof str === 'string' && (this.node.innerHTML = header + str)
}
}
return this
}
}
Paging.prototype.init.prototype = Paging.prototype
|
import mg from 'mongoose'
import 'mongoose-type-email'
import bcrypt from 'bcrypt'
const schema = new mg.Schema({
email: {
type: mg.Types.Email,
required: true,
index: {unique: true},
},
password: {
type: String,
required: true,
}
})
const User = mg.model('users', schema)
export async function addUser(email, plainPassword) {
const password = await bcrypt.hash(plainPassword, 10)
const {_doc: {_id}} = await User.create({email, password})
return _id
}
export async function authenticate(email, plainPassword) {
const {_doc} = await User.findOne({email})
console.log(_doc)
if (!await bcrypt.compare(plainPassword, _doc.password)) {
return null
}
return _doc._id
}
|
var group___device_addrs =
[
[ "ConfigRegisterA", "group___device_addrs.html#ga7c1a102601a1aedb5213d9ec2bdd44d9", null ],
[ "ConfigRegisterB", "group___device_addrs.html#ga2c4505b7f511c1459a77fb9ef4793cd9", null ],
[ "DataRegister", "group___device_addrs.html#gae3e06eef67a36f80ad1fbdbac2049809", null ],
[ "HMC5883L_ADDR", "group___device_addrs.html#gaf476bf33d389e5fc597d87cac399088d", null ],
[ "ModeRegister", "group___device_addrs.html#ga588e30fd18c31816cde04b8e3b3adf15", null ],
[ "StatusRegister", "group___device_addrs.html#gacda516aca361386a87975a62eba267d7", null ]
];
|
const {Command, flags} = require('@oclif/command')
const axios = require('axios')
function connect(taskId) {
const ws = require("websocket");
const wsc = new ws.client();
wsc.on('connect', function (c) {
c.on('error', e => {
console.error(e);
process.exit(1);
});
c.on('close', _ => process.exit(0));
c.on('message', m => {
// console.log(m);
const msg = JSON.parse(m.utf8Data);
switch (msg.EType) {
case 'progress': {
console.log(`taskId:${taskId}\ttime:${msg.Args.totalTime} s\ttotal:${msg.Args.total}\tspeed:${msg.Args.rps} rps`)
break
}
default: {
// console.log(m.utf8Data)
}
}
if (msg.EType === "finish" || msg.EType === "error") {
console.log(m.utf8Data)
process.exit(0)
}
})
});
wsc.connect(`${process.env['TASK_API']}/task/${taskId}/events`)
}
class RunCommand extends Command {
async run() {
const {flags} = this.parse(RunCommand)
axios({method: 'POST', url: process.env['TASK_API'] + '/task/' + flags.taskid + '/run'})
.then(res => {
if (res.status === 204) {
console.log("started");
if (!flags.background) {
connect(flags.taskid)
}
} else {
console.error(res.data.error)
}
}, err => {
console.error(err.response.data);
})
}
}
RunCommand.description = `run task
...
Extra documentation goes here
`
RunCommand.flags = {
taskid: flags.integer({char: 't', description: 'task id to run'}),
background: flags.boolean({char: "d", description: 'run in background'})
}
module.exports = RunCommand
|
/**
* Created by cl-macmini-149 on 31/01/17.
*/
'use strict'
var mongoose = require('mongoose');
//mongoose schema
var codeSchema = mongoose.Schema({
place:{type:String,default:null},
code:{type:String,default:null},
placeType:{type:String,default:null},
country:{type:String,default:null}
},
{
collection : 'codes'
}
);
module.exports.CodeSchema = mongoose.model('CodeSchema', codeSchema,'codes');
|
import rootReducer from 'reducers'
import { createStore, applyMiddleware } from 'redux'
import api from 'middleware/api'
export default function configureStore () {
return createStore(
rootReducer,
applyMiddleware(
api
)
)
}
|
'use strict';
angular
.module('myApp.controllers', ['myApp.data'])
.controller('main', function ($scope, data) {
$scope.title = "Sissy life web";
$scope.started = false;
$scope.points = 0;
$scope.total = 0;
$scope.objects = [];
$scope.data = data;
$scope.selected = [];
$scope.langs = [];
$scope.currentLanguage = 'en';
angular.forEach($scope.data, function (tab) {
angular.forEach(tab.content, function (line) {
line.selected = false;
});
});
angular.forEach(getLang(), function (value, key) {
$scope.langs.push(key)
});
$scope.loadText = function (lang) {
var languages = getLang();
if (!languages[lang]) {
lang = 'en';
}
angular.forEach($scope.data, function (tab) {
if (languages[lang][tab.id] && languages[lang][tab.id].label) {
tab.name = languages[lang][tab.id].label;
}
angular.forEach(tab.content, function (line) {
if (languages[lang][line.id] && languages[lang][line.id].label && languages[lang][line.id].description) {
line.label = languages[lang][line.id].label;
line.description = languages[lang][line.id].description;
}
});
});
}
$scope.$watch('currentLanguage', function (value) {
$scope.loadText($scope.currentLanguage);
});
$scope.loadText($scope.currentLanguage);
$scope.getInputType = function (once) {
return once ? 'radio' : 'checkbox';
};
$scope.start = function () {
$scope.started = true;
$scope.points = Math.floor((Math.random() * 100) + 1);
$scope.refresh();
};
$scope.tooExpensive = function (value, selected) {
if (selected) return false;
return value + $scope.total < 0;
};
$scope.selectionChange = function (pane, line, id, selected) {
if (line.id == id && line.func) line.func($scope);
if (selected && pane.once) {
angular.forEach($scope.data, function (tab) {
if (tab.name == pane.name) {
angular.forEach(tab.content, function (line) {
if (line.id != id) line.selected = false;
});
}
});
}
$scope.refresh();
//if issue with auto deselect, uncheck the last checkbox
if ($scope.total < 0) {
angular.forEach(pane.content, function (line) {
if (line.id == id) line.selected = false;
});
$scope.refresh();
}
};
$scope.refresh = function () {
$scope.selected = [];
angular.forEach($scope.data, function (tab) {
angular.forEach(tab.content, function (line) {
if (line.selected) {
$scope.selected.push(line);
}
});
});
$scope.total = $scope.getTotal();
};
$scope.getTotal = function () {
var sum = $scope.points;
angular.forEach($scope.selected, function (line) {
sum += line.value;
});
return sum;
};
});
|
'use strict';
var _client = require('./client');
var _client2 = _interopRequireDefault(_client);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var client = new _client2.default('YOUR_USERNAME_HERE', 'YOUR_PASSWORD_HERE');
exports.handler = function (event, context, callback) {
client.getAccounts().then(function (result) {
callback(null, {
amex: Number(result.replace(/[^0-9.,]+/, '').replace('"', ''))
});
});
};
|
import React from "react";
import ReactDOM from "react-dom";
import ClassBasedComponent from "./classBased/ClassBasedComponent";
ReactDOM.render(<ClassBasedComponent></ClassBasedComponent>, document.getElementsByTagName("div")[0]);
|
var spaceit = require("../support/simple_spaceit");
var simple_m = require("../support/simple_module");
function reverseSpace(str) {
return simple_m.reverse(spaceit(str));
};
exports.reverseSpace = reverseSpace;
|
(function ($) {
var $MessageList = $('#js-messages');
var $MessageDone = $('#done-msg');
function message(p_sMessage) {
$MessageList.append($('<li>' + p_sMessage + '</li>'));
}
function messageDone(p_sMessage) {
$MessageDone.append($('<li>' + p_sMessage + '</li>'));
}
window.Linkedin = {
init: function () {
message('The Linkedin JS has loaded.');
message('You can now login.');
$('.IN-widget').bind('click', function () {
message('You just clicked the Login Button');
window.parent.postMessage("LoginClicked", '*');
});
},
onAuthCallback: function () {
window.parent.postMessage("LoggedIn", '*');
message('You just logged in.');
message('Will retrieve your info.');
messageDone('Authentication successful...');
},
onLogoutCallback: function () {
message('You just logged out.');
},
userData: function (p_oUserInfo) {
var localUserInfo = p_oUserInfo;
//This is the best way of getting profile params
IN.API.Profile("me").fields(["picture-urls::(original)","pictureUrl","publicProfileUrl", "firstName", "lastName", "id", "headline"]).result(function (result) {
console.log(result);
if (result.values[0].pictureUrls && result.values[0].pictureUrls._total) {
message('' + ' <img src="' + result.values[0].pictureUrls.values[0] + '" \/>' + result.values[0].firstName + ' ' + result.values[0].lastName + ' -- ' + result.values[0].headline + ' (' + result.values[0].id + ')');
window.parent.postMessage(result.values[0].pictureUrls.values[0], '*');
IN.User.logout();
} else if (result.values[0].pictureUrl) {
message('' + ' <img src="' + result.values[0].pictureUrl + '" \/>' + result.values[0].firstName + ' ' + result.values[0].lastName + ' -- ' + result.values[0].headline + ' (' + result.values[0].id + ')');
window.parent.postMessage(result.values[0].pictureUrl, '*');
IN.User.logout();
} else {
message(result.values[0].firstName + ' ' + result.values[0].lastName + ' -- ' + result.values[0].headline + ' (' + result.values[0].id + ')');
window.parent.postMessage("NotFound", '*');
IN.User.logout();
}
});
}
};
} (jQuery));
|
var express = require('express');
var router = express.Router();
var appRoot = require('app-root-path');
var db_init = require(appRoot + "/db/db");
var sha256 = require("sha256");
/* GET home page. */
router.get('/', function(req, res, next) {
if(!req.body.logged_in){
res.render("join");
}else{
res.redirect("/");
};
});
router.post('/', function(req, res) {
var already_existing;
var username = req.body.username;
var password = req.body.password;
var email = req.body.email;
db_init.users.findOne({email:email}, function(e, result){
if (e) {
console.log("error: " + e);
};
if(result){
already_existing = true;
};
if (!already_existing) {
db_init.users.insert({
email:email,
username: username,
password: sha256(password),
}, function(){
if(req.session.admin){
res.redirect("/admin");
}else{
res.redirect("/");
};
});
};
});
});
module.exports = router;
|
var searchData=
[
['y',['y',['../structefp__atom.html#aa4a92c76d4a9a2b97f36eeaba42bd541',1,'efp_atom']]]
];
|
import { connect } from 'react-redux';
import OrderPage from '../fromOddDefine/components/OrderPage/OrderPage';
import helper, {fetchJson, getObject, postOption, showError} from '../../../common/common';
import {Action} from '../../../action-reducer/action';
import {getPathValue} from '../../../action-reducer/helper';
import {buildEditDialogState} from './common/state';
const STATE_PATH = ['basic', 'roleDataAuthority'];
const action = new Action(STATE_PATH);
const URL_ONE = '/api/basic/roleDataAuthority/one';
const URL_DEL = '/api/basic/roleDataAuthority/del';
const URL_SEARCH = '/api/basic/roleDataAuthority/search';
const getSelfState = (rootState) => {
return getPathValue(rootState, STATE_PATH);
};
const changeActionCreator = (key, value) => (dispatch) =>{
dispatch(action.assign({[key]: value}, 'searchData'));
};
const checkActionCreator = (isAll, checked, rowIndex) => (dispatch, getState) =>{
isAll && (rowIndex = -1);
dispatch(action.update({checked}, 'tableItems', rowIndex));
};
const searchAction = async (dispatch, getState) => {
const {searchData} = getSelfState(getState());
const {result, returnCode} = await fetchJson(URL_SEARCH, postOption({...searchData}));
if (returnCode !== 0) {
showError('搜索失败, 未能找到');
return;
}
return dispatch(action.assign({tableItems: result}));
};
const resetAction = (dispatch) =>{
dispatch( action.assign({searchData: {}}) );
};
const addAction = (dispatch, getState) => {
const {editConfig} = getSelfState(getState());
const payload = buildEditDialogState(editConfig, {}, [], false);
payload.data= editConfig.data;
payload.merge= editConfig.merge;
helper.setOptions('content', payload.tableCols, []);
dispatch(action.assign(payload, 'edit'));
};
const x = (id ,data) => {
let option = {};
data.find((items) => {
if (items.id === id) {
option={
value: items.id,
title: items.ruleTypeName
};
}
});
return option;
};
const y = (tenantRuleTypeId, ruleId, data) => {
let option = {};
const list = data.find((items) => items.id === tenantRuleTypeId);
list.relationList.find((items) => {
if (items.id === ruleId) {
option={
value: items.id,
title: items.ruleName
};
}
});
return option;
};
const getEdit = (result, data) => {
let all = [];
result.dataRoleRuleList && result.dataRoleRuleList.map((items, index) => {
const content = items.content.reduce((result, item) => {
result.push(item.value);
return result;
}, []);
const options = {content: items.content};
const tenantRuleTypeId = x(items.tenantRuleTypeId, data);
const ruleId = y(items.tenantRuleTypeId, items.ruleId, data);
const dataRoleRemark = items.dataRoleRemark;
all.push({content: content, tenantRuleTypeId: tenantRuleTypeId, ruleId: ruleId, dataRoleRemark: dataRoleRemark, options});
});
return all;
};
const getoption = (items, data, merge) => {
let tenantRuleTypeId, ruleId, array = [], arr;
items.map((item) => {
tenantRuleTypeId = item.tenantRuleTypeId.value;
ruleId = item.ruleId.value;
const {relationList} = data.find((item) => item.id === tenantRuleTypeId);
const {relationTable} = relationList.find((item) => item.id === ruleId);
if (relationTable === 'relation_table_user') {
arr = merge.use.data.find(item => item.value === '0');
if (arr) {
item.options.content = merge.use.data
}else {
merge.use.data.unshift({value: '0', title: '本人'});
item.options.content = merge.use.data
}
} else if (relationTable === 'relation_table_customer') {
item.options.content = merge.customer
} else if (relationTable === 'relation_table_supply') {
item.options = merge.supply
} else if (relationTable === 'relation_table_department') {
arr = merge.department.data.find(item => item.value === '0');
if (arr) {
//merge.department.data.unshift({value: '0', title: '本部门'});
item.options.content = merge.department.data
}else {
merge.department.data.unshift({value: '0', title: '本部门'});
item.options.content = merge.department.data
}
}else if (relationTable === 'relation_table_institution') {
merge.institution.data.map((data) => {
array.push({
value: data.guid,
title: data.institutionName
})
});
if (arr) {
arr = array.find(item => item.value === '0');
}else {
array.unshift({value: '0', title: '本机构'});
item.options.content = array;
}
}else if (relationTable === 'relation_table_task_unit') {
//let array = [];
merge.taskUnit.map((result) => {
array.push({
value: result.taskUnitCode,
title: result.taskUnitTypeName
})
});
item.options.content = array;
}else if (relationTable === 'relation_table_product') {
merge.product.map((item) => {
array.push({value: item.productTypeGuid.value, title: item.productTypeGuid.title})
});
item.options.content = array;
}
});
return items;
};
const editAction = async (dispatch, getState) => {
const {editConfig, tableItems, merge} = getSelfState(getState());
const {data} = editConfig;
const index = helper.findOnlyCheckedIndex(tableItems);
if (index !== -1) {
const item = tableItems[index];
const {result} = await fetchJson(`${URL_ONE}/${item.id}`);
const newData = helper.getObjectExclude(tableItems[index], ['checked']);
const payload = buildEditDialogState(editConfig, newData, getEdit(result, data), true, index);
payload.tableItems = getoption(getEdit(result, data), data, merge);
if (payload.tableItems.find(o => o['content'])) {
helper.setOptions('content', payload.tableCols, merge.supply);
}
payload.data = data;
payload.merge = editConfig.merge;
dispatch(action.assign(payload, 'edit'));
}else {
helper.showError('请勾选一个');
}
};
const doubleClickActionCreator = (rowIndex) => async (dispatch, getState) => {
const {editConfig, tableItems, merge} = getSelfState(getState());
const item = tableItems[rowIndex];
const {data} = editConfig;
const {result} = await fetchJson(`${URL_ONE}/${item.id}`);
const payload = buildEditDialogState(editConfig, tableItems[rowIndex], getEdit(result, data), false);
payload.tableItems = getoption(getEdit(result, data), data, merge);
if (payload.tableItems.find(o => o['content'])) {
helper.setOptions('content', payload.tableCols, merge.supply);
}
payload.data = data;
payload.merge = editConfig.merge;
dispatch(action.assign(payload, 'edit'));
};
const delAction = async (dispatch, getState) => {
const {tableItems} = getSelfState(getState());
const index = helper.findOnlyCheckedIndex(tableItems);
if (index === -1) {
helper.showError('请勾选一条记录进行删除');
return;
}
const item = tableItems[index];
const {returnCode, returnMsg} = await fetchJson(`${URL_DEL}/${item.id}`, 'delete');
if (returnCode === 0) {
dispatch(action.del('tableItems', index));
helper.showSuccessMsg('删除成功');
}else {
helper.showError(returnMsg);
}
};
const toolbarActions = {
reset: resetAction,
search: searchAction,
add: addAction,
edit: editAction,
del: delAction,
};
const clickActionCreator = (key) => {
if (toolbarActions.hasOwnProperty(key)) {
return toolbarActions[key];
} else {
console.log('unknown key:', key);
return {type: 'unknown'};
}
};
const mapStateToProps = (state) => {
return getObject(getSelfState(state), OrderPage.PROPS);
};
const actionCreators = {
onClick: clickActionCreator,
onChange: changeActionCreator,
onCheck: checkActionCreator,
onDoubleClick: doubleClickActionCreator
};
const Container = connect(mapStateToProps, actionCreators)(OrderPage);
export default Container;
|
'use strict';
angular.module('angularTest')
.controller('HomeCtrl', function ($scope, HomeService) {
var home = this;
$scope.currentColor = 'white';
home.title = 'Doom';
$scope.sampleText = "fd asfd fadsf dasfdas fadsfsda fsa fasdf asdfas dfdas fadsf asdf dsaf";
HomeService.all()
.then(function(data) {
$scope.data = data;
HomeService.contacts = data.users;
})
.catch(function() {
//
})
.finally(function() {
//
})
$scope.saveContact = function (isValid) {
if($scope.newcontact && isValid) {
HomeService.save($scope.newcontact);
}
$scope.newcontact = {};
}
$scope.delete = function (id) {
HomeService.delete(id);
if ($scope.newcontact.id == id) $scope.newcontact = {};
}
$scope.edit = function (id) {
$scope.newcontact = angular.copy(HomeService.get(id));
}
})
;
|
import React from 'react'
import PropTypes from 'prop-types'
const FontAwesome = (props) => {
return (
<i className={`${props.brand === 'true' ? 'fab' : 'fa'} fa-${props.icon} fa-${props.size || 1}x ${props.class}`} />
)
}
FontAwesome.propTypes = {
icon: PropTypes.string.isRequired,
size: PropTypes.number,
class: PropTypes.string,
brand: PropTypes.string,
}
export default FontAwesome
|
const navToggle = document.querySelector(".nav-toggle");
const directorBtns = document.querySelectorAll(".add-social-btn");
navToggle.addEventListener("click", () => {
document.body.classList.toggle("nav-open");
});
directorBtns.forEach((btn) => {
btn.addEventListener("click", () => {
btn.parentNode.classList.toggle("director-flip");
});
});
|
/*
* ProGade API
* http://api.progade.de/
*
* Copyright 2012, Hans-Peter Wandura (ProGade)
* You can find the Licenses, Terms and Conditions under: http://api.progade.de/api_terms.php
*
* Last changes of this file: Aug 22 2012
*/
/*
@start class
@param extends classPG_ClassBasics
*/
function classPG_Faq()
{
// Declarations...
this.asCategories = new Array();
this.asQuestions = new Array();
this.bCategoriesClosed = true;
this.bQuestionsClosed = true;
// Construct...
// Methods...
/* @start method */
this.init = function()
{
var i=0;
if (this.bCategoriesClosed == true) {for (i=0; i<this.asCategories.length; i++) {this.closeCategory(this.asCategories[i]);}}
if (this.bQuestionsClosed == true) {for (i=0; i<this.asQuestions.length; i++) {this.closeQuestion(this.asQuestions[i]);}}
}
/* @end method */
/*
@start method
@param bUse
*/
this.useCategoriesClosed = function(_bUse) {this.bCategoriesClosed = _bUse;}
/* @end method */
/* @start method */
this.isCategoriesClosed = function() {return this.bCategoriesClosed;}
/* @end method */
/*
@start method
@param bUse
*/
this.useQuestionsClosed = function(_bUse) {this.bQuestionsClosed = _bUse;}
/* @end method */
/* @start method */
this.isQuestionsClosed = function() {return this.bQuestionsClosed;}
/* @end method */
/*
@start method
@param sCategoryID
*/
this.registerCategory = function(_sCategoryID)
{
this.asCategories.push(_sCategoryID);
}
/* @end method */
/*
@start method
@param sQuestionID
*/
this.registerQuestion = function(_sQuestionID)
{
this.asQuestions.push(_sQuestionID);
}
/* @end method */
/*
@start method
@param sCategoryID
*/
this.openCategory = function(_sCategoryID)
{
var _oCategory = this.oDocument.getElementById(_sCategoryID);
var _oCategoryIconOpen = this.oDocument.getElementById(_sCategoryID+'IconOpen');
var _oCategoryIconClose = this.oDocument.getElementById(_sCategoryID+'IconClose');
if (_oCategory)
{
_oCategory.style.display = 'block';
if (_oCategoryIconOpen) {_oCategoryIconOpen.style.display = 'inline';}
if (_oCategoryIconClose) {_oCategoryIconClose.style.display = 'none';}
}
}
/* @end method */
/*
@start method
@param sCategoryID
*/
this.closeCategory = function(_sCategoryID)
{
var _oCategory = this.oDocument.getElementById(_sCategoryID);
var _oCategoryIconOpen = this.oDocument.getElementById(_sCategoryID+'IconOpen');
var _oCategoryIconClose = this.oDocument.getElementById(_sCategoryID+'IconClose');
if (_oCategory)
{
_oCategory.style.display = 'none';
if (_oCategoryIconOpen) {_oCategoryIconOpen.style.display = 'none';}
if (_oCategoryIconClose) {_oCategoryIconClose.style.display = 'inline';}
}
}
/* @end method */
/*
@start method
@param sCategoryID
*/
this.switchCategory = function(_sCategoryID)
{
var _oCategory = this.oDocument.getElementById(_sCategoryID);
if (_oCategory)
{
if (_oCategory.style.display == 'none') {this.openCategory(_sCategoryID);}
else {this.closeCategory(_sCategoryID);}
}
}
/* @end method */
/*
@start method
@param sQuestionID
*/
this.openQuestion = function(_sQuestionID)
{
var _oQuestion = this.oDocument.getElementById(_sQuestionID);
var _oQuestionIconOpen = this.oDocument.getElementById(_sQuestionID+'IconOpen');
var _oQuestionIconClose = this.oDocument.getElementById(_sQuestionID+'IconClose');
if (_oQuestion)
{
_oQuestion.style.display = 'block';
if (_oQuestionIconOpen) {_oQuestionIconOpen.style.display = 'inline';}
if (_oQuestionIconClose) {_oQuestionIconClose.style.display = 'none';}
}
}
/* @end method */
/*
@start method
@param sQuestionID
*/
this.closeQuestion = function(_sQuestionID)
{
var _oQuestion = this.oDocument.getElementById(_sQuestionID);
var _oQuestionIconOpen = this.oDocument.getElementById(_sQuestionID+'IconOpen');
var _oQuestionIconClose = this.oDocument.getElementById(_sQuestionID+'IconClose');
if (_oQuestion)
{
_oQuestion.style.display = 'none';
if (_oQuestionIconOpen) {_oQuestionIconOpen.style.display = 'none';}
if (_oQuestionIconClose) {_oQuestionIconClose.style.display = 'inline';}
}
}
/* @end method */
/*
@start method
@param sQuestionID
*/
this.switchQuestion = function(_sQuestionID)
{
var _oQuestion = this.oDocument.getElementById(_sQuestionID);
if (_oQuestion)
{
if (_oQuestion.style.display == 'none') {this.openQuestion(_sQuestionID);}
else {this.closeQuestion(_sQuestionID);}
}
}
/* @end method */
}
/* @end class */
classPG_Faq.prototype = new classPG_ClassBasics();
var oPGFaq = new classPG_Faq();
|
socket.on('users-connected', (conectados)=>{
var users_online = window.document.getElementById('users-online');
users_online.innerText = "Users online: " + conectados;
});
socket.on('play-video', (msg) => {
if(player) {
player.playVideo();
}
});
socket.on('pause-video', (msg) => {
if(player) {
player.pauseVideo();
}
updateActualSinger('');
});
//player-time
var player_time = window.document.getElementById('player-time');
socket.on('current-video-time', (curr, singer) =>{
window.singer_time = curr;
var time = new Date(curr.toFixed(2) * 1000).toISOString().substr(14, 5);
var who_is_singing;
if(singer == socket.id) {
who_is_singing = 'You are at time: ';
} else {
who_is_singing = 'The singer is at time: ';
}
player_time.innerText = who_is_singing + time;
});
socket.on('adjust-video-time', (curr) =>{
if(curr == undefined){
curr = window.singer_time+0.4;
}
if(player){
player.playVideo();
player.seekTo(curr);
}
});
// //audio capture
// var constraints = { audio: true };
// navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) {
// var mediaRecorder = new MediaRecorder(mediaStream);
// mediaRecorder.onstart = function(e) {
// this.chunks = [];
// };
// mediaRecorder.ondataavailable = function(e) {
// this.chunks.push(e.data);
// };
// mediaRecorder.onstop = function(e) {
// var blob = new Blob(this.chunks, { 'type' : 'audio/ogg; codecs=opus' });
// socket.emit('radio', blob);
// };
// Start song
window.song_time_interval = '';
window.start_song = document.getElementById('start-song');
start_song.addEventListener('click', ()=>{
socket.emit('i-started-sing', socket.id);
});
// Stop song
window.stop_song = document.getElementById('pause-song');
stop_song.addEventListener('click', ()=>{
socket.emit('singer-paused-song', socket.id);
});
// });
socket.on('allowed-to-sing', ()=>{
//start_button.click();
if(player) {
player.playVideo();
socket.emit('video-played');
}
updateActualSinger('YOU are singing now');
song_time_interval = setInterval(function() {
if(window.player){
//shows on screen the current time
// var time = new Date(window.player.getCurrentTime().toFixed(2) * 1000).toISOString().substr(14, 5);
// player_time.innerText = 'VOCE está cantando: ' + time;
socket.emit('current-video-time', window.player.getCurrentTime());
//adjust all users video time
//if(parseInt(window.player.getCurrentTime())%30 == 0) {
//socket.emit('adjust-video-time', window.player.getCurrentTime());
//}
}
}, 1000);
});
socket.on('singer-not-allowed', ()=>{
var alert_div = document.getElementById('alert-singer-singing');
alert_div.style.backgroundColor='red';
alert_div.innerText = 'SOMEONE IS SINGING NOW';
setTimeout(()=>{alert_div.innerText = ''}, 1500);
if(player && player.getPlayerState() == 5){ //video not started
player.loadVideoById(now_playing_song);
setTimeout(()=>{
player.playVideo();
sync_btn.click();
},2000);
} else if(player.getPlayerState() == 1){ //video playing
sync_btn.click();
}
});
socket.on('singer-allowed-pause', ()=>{
//stop_button.click();
socket.emit('video-paused');
clearInterval(song_time_interval);
});
socket.on('singer-not-allowed-pause', ()=>{
var alert_div = document.getElementById('alert-singer-singing');
alert_div.style.backgroundColor = 'red';
alert_div.innerText = 'SOMEONE IS SINGING NOW';
setTimeout(()=>{alert_div.innerText = ''}, 1500);
});
// When the client receives a voice message it will play the sound
socket.on('voice', function(arrayBuffer) {
var blob = new Blob([arrayBuffer], { 'type' : 'audio/ogg; codecs=opus' });
var audio = document.createElement('audio');
audio.src = window.URL.createObjectURL(blob);
audio.play();
});
var add_music_btn = document.getElementById('add-music');
add_music_btn.addEventListener('click', ()=>{
var text_content = document.getElementById('video-link');
var video_url = text_content.value;
text_content.value = '';
var videoId = getVideoId(video_url);
socket.emit('added-music', videoId, socket.id);
})
socket.on('update-playlist', (musics)=>{
musics_queue = musics;
updatePlaylist();
})
socket.on('singer-started', (singer) =>{
//stop_button.click();
document.getElementById('actual-singer').innerText = singer + ' está cantando';
});
socket.on('next-song', (musicVideoId) =>{
//ligar a voz
//start_button.click();
//tocar proxima musica
player.loadVideoById(musicVideoId);
setTimeout(()=>{player.pauseVideo();}, 2000);
});
window.next_song = document.getElementById('next-song');
next_song.addEventListener('click', ()=>{
socket.emit('call-next-song');
});
socket.on('load-now-playing', (videoId)=>{
window.now_playing_song = videoId;
});
//youtube player API
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
var now_playing_song = window.now_playing_song || '3Uj-F8Ff7eU';
player = new YT.Player('player', {
height: '100%',
width: '100%',
videoId: now_playing_song,
events: {
}
});
player.addEventListener("onStateChange", function(state){
//video ended
if(state.data === 0){
// the video is end, do something here.
socket.emit('song-ended');
}
});
}
document.getElementById('rewind-1').addEventListener('click', ()=>{
player.seekTo(window.player.getCurrentTime()-1);
});
document.getElementById('forward-1').addEventListener('click', ()=>{
player.seekTo(window.player.getCurrentTime()+1);
});
function getVideoId(video_link){
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
var match = video_link.match(regExp);
return match[7];
}
socket.on('load-musics-queue', (queue)=>{
window.musics_queue = queue;
updatePlaylist();
});
socket.on('load-actual-singer', (singer)=>{
if(singer){
updateActualSinger(singer + ' está cantando');
} else {
document.getElementById('actual-singer').innerText = '';
}
});
function updateActualSinger(msg){
document.getElementById('actual-singer').innerText = msg;
}
function updatePlaylist(){
var musics_queue_div = document.getElementById('musics-queue-div');
//clean actual child
musics_queue_div.innerHTML = '';
//insert child
musics_queue.forEach((item)=>{
let headers = new Headers();
var str = item.user + ' added ' + item.music;
var mus = document.createElement('p');
mus.innerText = item.title || str;
musics_queue_div.appendChild(mus);
});
}
function updateUsersList(users){
var users_list_div = document.getElementById('users-list');
users_list_div.innerHTML = '';
for (key in users) {
// check if the property/key is defined in the object itself, not in parent
if (users.hasOwnProperty(key)) {
var usr = document.createElement('p');
usr.innerText = users[key];
users_list_div.appendChild(usr);
}
}
}
function cleanMusicsQueue(){
socket.emit('clean-music-queue');
}
function cleanActualSinger(){
socket.emit('clean-actual-singer');
}
var change_nick_btn = document.getElementById('change-nick')
change_nick_btn.addEventListener('click', ()=>{
docCookies.removeItem('nick');
window.nick_modal.open();
});
function nickSetted(nick){
socket.emit('nick-setted', socket.id, nick);
}
socket.on('update-users-list', (users)=>{
updateUsersList(users);
})
socket.on('update-now-playing-song', (song)=>{
now_playing_song = song;
})
var sync_btn = document.getElementById('sync-music');
sync_btn.addEventListener('click', function(){
socket.emit('ask-to-adjust-video-time');
})
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
|
var RomoColorSelect = RomoComponent(function(elem) {
this.elem = elem;
this.defaultCaretClass = undefined;
this.defaultCaretPaddingPx = 5;
this.defaultCaretWidthPx = 18;
this.defaultCaretPosition = 'right'
this.defaultValuesDelim = ',';
this.defaultOptionItems = this._buildDefaultOptionItems();
this.doRefreshColorItemsJson();
this.doInit();
this._bindElem();
Romo.trigger(this.elem, 'romoColorSelect:ready', [this]);
});
RomoColorSelect.prototype.doSetValue = function(value) {
var items, values, displayText;
items = Romo.array(value).map(Romo.proxy(function(v) {
return this.colorItems.find(function(i) { return i.value === v; });
}, this));
items = items.filter(function(i) { return i !== undefined; });
items = items.map(function(i) {
return {
'value': i.value,
'displayText': i.displayText
};
});
values = items.map(function(i) { return i.value; });
if (this.romoSelectedOptionsList !== undefined) {
displayText = '';
this.romoSelectedOptionsList.doSetItems(items);
} else if (items[0]) {
displayText = items[0].displayText;
this.romoOptionListDropdown.doSetSelectedItem(values[0]);
} else {
displayText = Romo.data(this.elem, 'romo-color-select-empty-option-display-text') || '';
this.romoOptionListDropdown.doSetSelectedItem(undefined);
}
this._setValuesAndDisplayText(values, displayText);
this._refreshUI();
}
RomoColorSelect.prototype.doRefreshColorItemsJson = function() {
var items, values;
itemTuples = Romo.data(this.elem, 'romo-color-select-items-json');
values = this._elemValues();
this.colorItems = itemTuples.map(Romo.proxy(function(itemTuple) {
return this._buildColorItem(values, {
'value': itemTuple[0],
'name': itemTuple[1]
});
}, this));
}
// private
RomoColorSelect.prototype._buildColorItem = function(elemValues, itemData) {
return {
'value': itemData.value,
'displayText': itemData.name,
'displayHtml': this._buildColorItemDisplayHtml(itemData),
'selected': elemValues.includes(itemData.value)
}
}
RomoColorSelect.prototype._buildColorItemDisplayHtml = function(itemData) {
return (
'<div class="romo-color-select-item">'+
'<div class="romo-color-select-item-color"'+
'style="background-color: '+itemData.value+'"> </div>'+
'<div class="romo-color-select-item-name">'+itemData.name+'</div>'+
'</div>'
);
}
RomoColorSelect.prototype._bindElem = function() {
this._bindOptionListDropdown();
this._bindSelectedOptionsList();
Romo.on(this.elem, 'romoColorSelect:triggerToggle', Romo.proxy(function(e) {
Romo.trigger(this.romoOptionListDropdown.elem, 'romoOptionListDropdown:triggerToggle', []);
}, this));
Romo.on(this.elem, 'romoColorSelect:triggerPopupOpen', Romo.proxy(function(e) {
Romo.trigger(this.romoOptionListDropdown.elem, 'romoOptionListDropdown:triggerPopupOpen', []);
}, this));
Romo.on(this.elem, 'romoColorSelect:triggerPopupClose', Romo.proxy(function(e) {
Romo.trigger(this.romoOptionListDropdown.elem, 'romoOptionListDropdown:triggerPopupClose', []);
}, this));
Romo.on(this.elem, 'romoColorSelect:triggerRefreshColorItemsJson', Romo.proxy(function(e) {
this.doRefreshColorItemsJson();
}, this));
this._setUnfilteredListItems();
this.doSetValue(this._elemValues());
if (Romo.attr(this.elem, 'id') !== undefined) {
var labelElem = Romo.f('label[for="'+Romo.attr(this.elem, 'id')+'"]');
Romo.on(labelElem, 'click', Romo.proxy(function(e) {
e.preventDefault();
this.romoOptionListDropdown.doFocus();
}, this));
}
Romo.on(window, "pageshow", Romo.proxy(function(e) {
this._refreshUI();
}, this));
Romo.on(this.elem, 'romoColorSelect:triggerSetValue', Romo.proxy(function(e, value) {
this.doSetValue(value)
}, this));
}
RomoColorSelect.prototype._bindSelectedOptionsList = function() {
this.romoSelectedOptionsList = undefined;
if (this.elem.multiple === true) {
if (Romo.data(this.elem, 'romo-color-select-multiple-item-class') !== undefined) {
Romo.setData(
this.romoOptionListDropdown.elem,
'romo-selected-options-list-item-class',
Romo.data(this.elem, 'romo-color-select-multiple-item-class')
);
}
if (Romo.data(this.elem, 'romo-color-select-multiple-max-rows') !== undefined) {
Romo.setData(
this.romoOptionListDropdown.elem,
'romo-selected-options-list-max-rows',
Romo.data(this.elem, 'romo-color-select-multiple-max-rows')
);
}
this.romoSelectedOptionsList = new RomoSelectedOptionsList(this.romoOptionListDropdown.elem);
Romo.on(
this.romoSelectedOptionsList.elem,
'romoSelectedOptionsList:itemClick',
Romo.proxy(function(e, itemValue, romoSelectedOptionsList) {
var currentValues = this._elemValues();
var index = currentValues.indexOf(itemValue);
if (index > -1) {
currentValues.splice(index, 1);
this._setValuesAndDisplayText(currentValues, '');
}
this.romoSelectedOptionsList.doRemoveItem(itemValue);
this._refreshUI();
Romo.trigger(this.elem, 'change');
Romo.trigger(
this.elem,
'romoSelect:multipleChange',
[currentValues, itemValue, this]
);
}, this)
);
Romo.on(
this.romoSelectedOptionsList.elem,
'romoSelectedOptionsList:listClick',
Romo.proxy(function(e, romoSelectedOptionsList) {
Romo.trigger(this.romoOptionListDropdown.elem, 'romoDropdown:triggerPopupClose', []);
this.romoOptionListDropdown.doFocus(false);
}, this)
);
Romo.before(this.elemWrapper, this.romoSelectedOptionsList.elem);
this.romoSelectedOptionsList.doRefreshUI();
}
}
RomoColorSelect.prototype._bindOptionListDropdown = function() {
this.romoOptionListDropdown = new RomoOptionListDropdown(
this._buildOptionListDropdownElem()
);
Romo.on(
this.romoOptionListDropdown.elem,
'romoOptionListDropdown:romoDropdown:toggle',
Romo.proxy(function(e, romoDropdown, optionListDropdown) {
Romo.trigger(this.elem, 'romoColorSelect:romoDropdown:toggle', [romoDropdown, this]);
}, this)
);
Romo.on(
this.romoOptionListDropdown.elem,
'romoOptionListDropdown:romoDropdown:popupOpen',
Romo.proxy(function(e, romoDropdown, optionListDropdown) {
Romo.trigger(this.elem, 'romoColorSelect:romoDropdown:popupOpen', [romoDropdown, this]);
}, this)
);
Romo.on(
this.romoOptionListDropdown.elem,
'romoOptionListDropdown:romoDropdown:popupClose',
Romo.proxy(function(e, romoDropdown, optionListDropdown) {
Romo.trigger(this.elem, 'romoColorSelect:romoDropdown:popupClose', [romoDropdown, this]);
}, this)
);
Romo.on(
this.romoOptionListDropdown.elem,
'romoOptionListDropdown:filterChange',
Romo.proxy(function(e, filterValue, romoOptionListDropdown) {
var wbFilter = new RomoWordBoundaryFilter(filterValue, this.colorItems, function(item) {
// The romo word boundary filter by default considers a space, "-" and "_"
// as word boundaries. We want to also consider other non-word characters
// (such as ":", "/", ".", "?", "=", "&") as word boundaries as well.
return item.displayText.replace(/\W/g, ' ');
});
wbFilter.matchingItems.forEach(function(i){ i.hidden = false; });
wbFilter.notMatchingItems.forEach(function(i){ i.hidden = true; });
if (filterValue !== '') {
this._setFilteredListItems();
Romo.trigger(
this.romoOptionListDropdown.elem,
'romoOptionListDropdown:triggerListOptionsUpdate',
[this.romoOptionListDropdown.optItemElems()[0]]
);
} else {
this._setUnfilteredListItems();
Romo.trigger(
this.elem,
'romoOptionListDropdown:triggerListOptionsUpdate',
[this.romoOptionListDropdown.selectedItemElem()]
);
}
}, this)
);
Romo.on(
this.romoOptionListDropdown.elem,
'romoOptionListDropdown:itemSelected',
Romo.proxy(function(e, itemValue, itemDisplayText, optionListDropdown) {
this.romoOptionListDropdown.doFocus();
Romo.trigger(this.elem, 'romoColorSelect:itemSelected', [itemValue, itemDisplayText, this]);
}, this)
);
Romo.on(
this.romoOptionListDropdown.elem,
'romoOptionListDropdown:newItemSelected',
Romo.proxy(function(e, itemValue, itemDisplayText, optionListDropdown) {
if (this.romoSelectedOptionsList !== undefined) {
var currentValues = this._elemValues();
if (!currentValues.includes(itemValue)) {
this._setValuesAndDisplayText(currentValues.concat([itemValue]), '');
this.romoSelectedOptionsList.doAddItem({
'value': itemValue,
'displayText': itemDisplayText
});
}
} else {
this._setValuesAndDisplayText([itemValue], itemDisplayText);
}
this._refreshUI();
Romo.trigger(this.elem, 'romoColorSelect:newItemSelected', [itemValue, itemDisplayText, this]);
}, this)
);
Romo.on(
this.romoOptionListDropdown.elem,
'romoOptionListDropdown:change',
Romo.proxy(function(e, newValue, prevValue, optionListDropdown) {
Romo.trigger(this.elem, 'change');
if (this.romoSelectedOptionsList !== undefined) {
Romo.trigger(
this.elem,
'romoColorSelect:multipleChange',
[this._elemValues(), newValue, this]
);
} else {
Romo.trigger(this.elem, 'romoColorSelect:change', [newValue, prevValue, this]);
}
}, this)
);
}
RomoColorSelect.prototype._buildOptionListDropdownElem = function() {
var romoOptionListDropdownElem = Romo.elems(
'<div class="romo-color-select romo-btn" tabindex="0">'+
'<span class="romo-color-select-text"></span>'+
'</div>'
)[0];
Romo.setData(romoOptionListDropdownElem, 'romo-dropdown-overflow-x', 'hidden');
Romo.setData(romoOptionListDropdownElem, 'romo-dropdown-width', 'elem');
Romo.setData(
romoOptionListDropdownElem,
'romo-option-list-focus-style-class',
'romo-color-select-focus'
);
if (Romo.data(this.elem, 'romo-color-select-dropdown-position') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-dropdown-position',
Romo.data(this.elem, 'romo-color-select-dropdown-position')
);
}
if (Romo.data(this.elem, 'romo-color-select-dropdown-style-class') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-dropdown-style-class',
Romo.data(this.elem, 'romo-color-select-dropdown-style-class')
);
}
if (Romo.data(this.elem, 'romo-color-select-dropdown-min-height') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-dropdown-min-height',
Romo.data(this.elem, 'romo-color-select-dropdown-min-height')
);
}
if (Romo.data(this.elem, 'romo-color-select-dropdown-max-height') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-dropdown-max-height',
Romo.data(this.elem, 'romo-color-select-dropdown-max-height')
);
}
if (Romo.data(this.elem, 'romo-color-select-dropdown-height') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-dropdown-height',
Romo.data(this.elem, 'romo-color-select-dropdown-height')
);
}
if (Romo.data(this.elem, 'romo-color-select-dropdown-append-to-closest') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-dropdown-append-to-closest',
Romo.data(this.elem, 'romo-color-select-dropdown-append-to-closest')
);
}
if (Romo.data(this.elem, 'romo-color-select-dropdown-append-to') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-dropdown-append-to',
Romo.data(this.elem, 'romo-color-select-dropdown-append-to')
);
}
if (Romo.data(this.elem, 'romo-color-select-filter-placeholder') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-option-list-dropdown-filter-placeholder',
Romo.data(this.elem, 'romo-color-select-filter-placeholder')
);
}
if (Romo.data(this.elem, 'romo-color-select-filter-indicator') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-option-list-dropdown-filter-indicator',
Romo.data(this.elem, 'romo-color-select-filter-indicator')
);
}
if (Romo.data(this.elem, 'romo-color-select-filter-indicator-width-px') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-option-list-filter-indicator-width-px',
Romo.data(this.elem, 'romo-color-select-filter-indicator-width-px')
);
}
if (Romo.data(this.elem, 'romo-color-select-no-filter') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-option-list-dropdown-no-filter',
Romo.data(this.elem, 'romo-color-select-no-filter')
);
}
if (Romo.data(this.elem, 'romo-color-select-open-on-focus') !== undefined) {
Romo.setData(
romoOptionListDropdownElem,
'romo-option-list-dropdown-open-on-focus',
Romo.data(this.elem, 'romo-color-select-open-on-focus')
);
}
if (Romo.data(romoOptionListDropdownElem, 'romo-dropdown-max-height') === undefined) {
Romo.setData(romoOptionListDropdownElem, 'romo-dropdown-max-height', 'detect');
}
if (Romo.attr(this.elem, 'class') !== undefined) {
Romo.addClass(romoOptionListDropdownElem, Romo.attr(this.elem, 'class'));
}
if (Romo.attr(this.elem, 'style') !== undefined) {
Romo.setAttr(romoOptionListDropdownElem, 'style', Romo.attr(this.elem, 'style'));
}
Romo.setStyle(romoOptionListDropdownElem, 'width', Romo.width(this.elem)+'px');
if (Romo.attr(this.elem, 'disabled') !== undefined) {
Romo.setAttr(this.romoOptionListDropdown.elem, 'disabled', Romo.attr(this.elem, 'disabled'));
}
Romo.after(this.elem, romoOptionListDropdownElem);
Romo.hide(this.elem);
this.elemWrapper = Romo.elems('<div class="romo-color-select-wrapper"></div>')[0];
if (Romo.data(this.elem, 'romo-color-select-btn-group') === true) {
Romo.addClass(this.elemWrapper, 'romo-btn-group');
}
Romo.before(romoOptionListDropdownElem, this.elemWrapper);
Romo.append(this.elemWrapper, romoOptionListDropdownElem);
Romo.parentChildElems.add(this.elem, [this.elemWrapper]);
this.caretElem = undefined;
var caretClass = Romo.data(this.elem, 'romo-color-select-caret') || this.defaultCaretClass;
if (caretClass !== undefined && caretClass !== 'none') {
this.caretElem = Romo.elems('<i class="romo-color-select-caret '+caretClass+'"></i>')[0];
Romo.setStyle(
this.caretElem,
'line-height',
Romo.css(romoOptionListDropdownElem, 'line-height')
);
Romo.on(this.caretElem, 'click', Romo.proxy(this._onCaretClick, this));
Romo.append(romoOptionListDropdownElem, this.caretElem);
var caretPaddingPx = this._getCaretPaddingPx();
var caretWidthPx = this._getCaretWidthPx();
var caretPosition = this._getCaretPosition();
// add a pixel to account for the default input border
Romo.setStyle(this.caretElem, caretPosition, caretPaddingPx+1+'px');
// left-side padding
// + caret width
// + right-side padding
var dropdownPaddingPx = caretPaddingPx + caretWidthPx + caretPaddingPx;
Romo.setStyle(
romoOptionListDropdownElem,
'padding-'+caretPosition,
dropdownPaddingPx+'px'
);
}
return romoOptionListDropdownElem;
}
RomoColorSelect.prototype._setUnfilteredListItems = function() {
this.romoOptionListDropdown.doSetListItems(
this.defaultOptionItems.concat(this._buildOptionItems())
);
}
RomoColorSelect.prototype._setFilteredListItems = function() {
this.romoOptionListDropdown.doSetListItems(
this._buildOptionItems().concat(this._buildCustomOptionItems())
);
}
RomoColorSelect.prototype._buildOptionItems = function() {
return this.colorItems.filter(function(i) { return i.hidden !== true; }).map(function(i) {
return {
'type': 'option',
'value': i.value,
'displayText': i.displayText,
'displayHtml': i.displayHtml,
'selected': i.selected
}
});
}
RomoColorSelect.prototype._buildDefaultOptionItems = function() {
var items = [];
if (Romo.data(this.elem, 'romo-color-select-empty-option') === true) {
var text = Romo.data(this.elem, 'romo-color-select-empty-option-display-text') || '';
items.push({
'type': 'option',
'value': '',
'displayText': text,
'displayHtml': '<span>'+text+'</span>'
});
}
return items;
}
RomoColorSelect.prototype._buildCustomOptionItems = function() {
var items = [];
var value = this.romoOptionListDropdown.optionFilterValue();
if (value !== '' && Romo.data(this.elem, 'romo-color-select-custom-option') === true) {
var prompt = Romo.data(this.elem, 'romo-color-select-custom-option-prompt');
if (prompt !== undefined) {
items.push({
'type': 'optgroup',
'label': prompt,
'items': [this._buildCustomOptionItem(value)]
});
} else {
items.push(this._buildCustomOptionItem(value));
}
}
return items;
}
RomoColorSelect.prototype._buildCustomOptionItem = function(value) {
return {
'type': 'option',
'value': value,
'displayText': value,
'displayHtml': '<span>'+value+'</span>'
};
}
RomoColorSelect.prototype._setValuesAndDisplayText = function(newValues, displayText) {
this.elem.value = newValues.join(this._elemValuesDelim());
this.colorItems.forEach(function(colorItem) {
if (newValues.includes(colorItem.value)) {
colorItem.selected = true;
} else {
colorItem.selected = false;
}
});
Romo.setData(this.elem, 'romo-color-select-display-text', displayText);
}
RomoColorSelect.prototype._elemValues = function() {
return this.elem.value.split(this._elemValuesDelim()).filter(function(v){ return v !== ''; });
}
RomoColorSelect.prototype._elemValuesDelim = function() {
return Romo.data(this.elem, 'romo-color-select-values-delim') || this.defaultValuesDelim;
}
RomoColorSelect.prototype._refreshUI = function() {
if (this.romoSelectedOptionsList !== undefined) {
this.romoSelectedOptionsList.doRefreshUI();
}
var textElem = Romo.find(this.romoOptionListDropdown.elem, '.romo-color-select-text')[0];
var text = Romo.data(this.elem, 'romo-color-select-display-text') || '';
if (text === '') {
Romo.updateHtml(textElem, '<span> </span>');
} else {
Romo.updateText(textElem, text);
}
}
RomoColorSelect.prototype._getCaretPaddingPx = function() {
return (
Romo.data(this.elem, 'romo-color-select-caret-padding-px') ||
this.defaultCaretPaddingPx
);
}
RomoColorSelect.prototype._getCaretWidthPx = function() {
return (
Romo.data(this.elem, 'romo-color-select-caret-width-px') ||
this._parseCaretWidthPx()
);
}
RomoColorSelect.prototype._getCaretPosition = function() {
return (
Romo.data(this.elem, 'romo-color-select-caret-position') ||
this.defaultCaretPosition
);
}
RomoColorSelect.prototype._parseCaretWidthPx = function() {
var widthPx = Romo.width(this.caretElem);
if (isNaN(widthPx)) {
widthPx = this.defaultCaretWidthPx;
}
return widthPx;
}
// event functions
RomoColorSelect.prototype.romoEvFn._onCaretClick = function(e) {
if (this.elem.disabled === false) {
this.romoOptionListDropdown.doFocus();
Romo.trigger(this.elem, 'romoColorSelect:triggerPopupOpen');
}
}
// init
Romo.addElemsInitSelector('[data-romo-color-select-auto="true"]', RomoColorSelect);
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsViewAgenda = {
name: 'view_agenda',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 13H3c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h17c.55 0 1-.45 1-1v-6c0-.55-.45-1-1-1zm0-10H3c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h17c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1z"/></svg>`
};
|
// @flow
export default ["test-1.css", "test-1.html"]
|
'use strict';
//@flow strict
/*:: import type { JestMockT } from 'jest' */
const read/*:JestMockT*/ = require('../read');
jest.mock('../read');
const fs = require('fs');
jest.mock('fs');
//$FlowFixMe
fs.writeFile = jest.fn((path, content, callback) => callback && callback(null));
const write = require('../write');
afterEach(() => {
jest.clearAllMocks();
});
describe('write file tests', () => {
test('writes the file', () => {
return write('/blah', 'content')
.then(v => {
expect(v).toBe(true);
expect(read.mock.calls).toEqual([
['/blah'],
]);
//$FlowFixMe
expect(fs.writeFile.mock.calls).toEqual([
['/blah', 'content', expect.anything()],
]);
});
});
test('does not write the file if the content is the same', () => {
read.mockImplementationOnce(path => Promise.resolve('test content'));
return write('/blah', 'test content')
.then(v => {
expect(v).toBe(false);
expect(read.mock.calls).toEqual([
['/blah'],
]);
//$FlowFixMe
expect(fs.writeFile.mock.calls).toEqual([]);
});
});
test('writes the file if the read throws an error', () => {
read.mockImplementationOnce(path => Promise.resolve('oh oh'));
return write('/blah', 'content')
.then(v => {
expect(v).toBe(true);
//$FlowFixMe
expect(fs.writeFile.mock.calls).toEqual([
['/blah', 'content', expect.anything()],
]);
});
});
});
|
import React from "react"
import axios from "axios"
import { Send } from "react-feather"
import BirthdayInvite from "./BirthdayInvite/index"
import BirthdayInviteList from "./BirthdayInviteList/index"
import AttendingList from "./AttendingList/index"
class ConfirmationPage extends React.Component {
constructor(props) {
super(props)
this.state = {
emails: [],
currentEmail: { text: "", key: "" },
emailsSent: false,
party: "",
content: "",
link: ""
}
this.findMatchingEvent = this.findMatchingEvent.bind(this)
this.clickHandler = this.clickHandler.bind(this)
this.sendInvites = this.sendInvites.bind(this)
}
componentWillMount() {
this.findMatchingEvent()
}
componentDidMount() {
document.getElementById("email-input").focus()
document.title = "Tojj - Bekräftelse"
}
/**
* Function that gets the correct event.
* This so the client can send invites to only his/her birthdayparty.
*/
async findMatchingEvent() {
let party = await axios({
method: "get",
url: `/api/events/populated/${this.props.eventLink}`
})
party = party.data
this.setState({
party: party,
link: party.link
})
this.updateContent(party)
}
/**
* Updates the rendered content after Axios got the data.
*/
updateContent = party => {
let date = new Date(party.date).toLocaleDateString("sv-SE", {
weekday: "short",
day: "numeric",
month: "long",
hour: "numeric",
minute: "numeric"
})
date = date.split(" ")
const emailTemplate = `<body style="margin: 0; padding: 30px 0; width: 100%; background-color: #fbf7ee; background-image: ${
party.image
}">
<div style="padding: 30px 50px 50px; text-align: center; background: #fff; max-width: 600px; margin: 0 auto 15px; box-shadow: 0 0 5px 0px rgba(0,0,0,0.4)">
<img src="http://i.imgur.com/0aOsg8B.png" alt="Välkommen på kalas" style="width: 80%; height: auto" />
<h1 style="font-weight: bold; color: #6C80C5; text-transform: uppercase">${
party.title
}</h1>
<h2 style="font-weight: bold; text-transform: uppercase">${date[0]} ${
date[1]
} ${date[2]}</h2>
<h3 style="font-weight: bold; margin-bottom: 20px; text-transform: uppercase">Kl ${
date[3]
}</h3>
<h4 style="font-weight: bold; margin-bottom: 50px"> ${
party.child
} ska ha kalas och du är bjuden! Klicka på länken nedan för att svara på om du kommer.</h4>
<a href="${window.location.origin +
"/kalas/" +
party.link}" style="word-wrap: none; text-decoration: none; font-size: 16px; font-weight: bold; background: #6C80C5; color: #fff; padding: 15px 30px; border-radius: 100px; opacity: 0.8; margin: 20px 0">TILL KALASET</a>
</div>
<div style="padding: 20px 50px; background: #fff; max-width: 600px; margin: 0 auto; box-shadow: 0 0 5px 0px rgba(0,0,0,0.4)">
<h4 style="font-weight: bold">Vad är Tojj?</h4>
<p>Ingen mer stress kopplad till kalasfirande! Hos Tojj kan man skapa en digital kalasinbjudan och låta de inbjudna gästerna bidra till en bestämd present till födelsedagsbarnet genom Swish. Enkelt för alla och som grädde på moset kan man välja att bidra till en välgörenhet.</p>
<a href="${
window.location.origin
}" style="text-decoration: none; color: #6C80C5">Läs mer ></a>
</div>
</body>`
this.setState({
content: emailTemplate,
subject: party.title
})
}
/**
* Handles input for what users to send mail to.
*/
handleInput = e => {
const emailText = e.target.value
const currentEmail = { text: emailText, key: Date.now() }
this.setState({
currentEmail
})
}
/**
* Adds mail adresses in an array where its waiting to be sent using another onClick function.
* Data is what the User types.
*/
addEmail = e => {
e.preventDefault()
const newEmail = this.state.currentEmail
if (newEmail.text !== "") {
const emails = [...this.state.emails, newEmail]
this.setState({
emails: emails,
currentEmail: { text: "", key: "" },
emailsSent: false
})
document.getElementById("email-input").focus()
}
}
/**
* Deletes mail.
* Function made in case of misstype or mistake.
*/
deleteEmail = key => {
const filteredEmails = this.state.emails.filter(email => {
return email.key !== key
})
this.setState({
emails: filteredEmails
})
}
/**
* Redirects you to your birthday template when (onClick function)
*/
redirectToYourParty = () => {
this.props.history.push("/kalas/" + this.props.eventLink)
}
/**
* Sending all emails in the array
* And activating sendInvites method
* Changes state so client see that the emails are sent
*/
async clickHandler() {
await this.sendInvites()
this.setState({ emailsSent: true })
}
/**
* Function for sending invites.
*/
async sendInvites() {
let emailList = []
this.state.emails.map(email => {
return emailList.push(email.text)
})
for (let email of emailList) {
this.sendEmail(email, this.state.content, this.state.link)
if (!this.state.party.invited.includes(email)) {
this.state.party.invited.push(email)
await axios({
method: "put",
url: `/api/events/id/${this.state.party._id}/invites`,
data: {
invited: this.state.party.invited
}
})
this.setState({ emails: [] })
}
}
}
/**
* Function that takes the data that is to be sent.
*/
sendEmail = (email, message, subject) => {
fetch("/api/send", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email: email,
subject: `Inbjudan till kalas ${subject}`,
message: message
})
})
.then(res => res.json())
.then(res => { })
.catch(err => { })
}
render() {
return (
<div className="conf-wrapper">
<div className="invite-container">
<h1 className="conf-headline">Hurra ditt kalas är skapat!</h1>
<p className="conf-info">
En bekräftelse har skickats till den mail du angett.
</p>
<p className="conf-info">
Kalaset finns nu tillgängligt för andra med länken och du når sidan via <a className="text-info" style={{textDecoration: 'none'}} href={"/kalas/" + this.props.eventLink}>{window.location.origin}/kalas/{this.props.eventLink}</a>
</p>
<p className="conf-info mt-5">
Om du vill bjuda in gästerna via epost kan du enkelt göra det nedan genom att fylla i de epostadresser du vill skicka en inbjudan till.
</p>
<BirthdayInvite
addEmail={this.addEmail}
inputElement={this.inputElement}
handleInput={this.handleInput}
currentEmail={this.state.currentEmail}
sent={this.state.emailsSent}
invitedList={this.state.party.invited}
/>
<BirthdayInviteList
entries={this.state.emails}
deleteEmail={this.deleteEmail}
invitedList={this.state.party.invited}
/>
{this.state.emailsSent ? (
"SKICKAT"
) : this.state.emails < 1 ? (
<button disabled className="send-button disabled btn btn-info">
<Send /> Skicka
</button>
) : (
<button
onClick={this.clickHandler}
className="send-button btn btn-info"
>
<Send /> Skicka
</button>
)}
{this.state.emails < 1 && !this.state.emailsSent ? (
<p
style={{
fontStyle: "italic",
fontSize: ".8rem",
color: "#555",
marginTop: "10px"
}}
>
Lägg till minst en epost för att skicka inbjudan.
</p>
) : null}
</div>
<div className="invite-container">
<h4 className="conf-info mt-4 mb-2">
Följande personer har meddelat att de kommer{" "}
{this.state.party.attending
? `(${this.state.party.attending.length} st)`
: "(0 st)"}
:
</h4>
<p>Personer med en "*" följt efter sitt namn har lämnat en kommentar</p>
<AttendingList attending={this.state.party.attending} />
</div>
<div className="msg-container">
<div className="msg-text">
<ul className="my-4">
<li>
När kalasets OSA-datum har nåtts kommer ett mail skickas till dig med aktuell information.
</li>
<li>
Presenten skickas så fort summan är nådd, bra va?</li>
<li>
Du kan alltid skicka ut fler inbjudningar vid ett senare
tillfälle om du råkar glömma någon.
</li>
<li>
Undrar du något? Skriv till oss{" "}
<a href="mailto:tojjinfo@gmail.com">här</a>!
</li>
</ul>
<p className="mt-5 mb-3 text-center">
Vi hoppas att {this.state.party.child} får en underbar dag!
</p>
<a
href={"/kalas/" + this.props.eventLink}
type="btn"
className="party-button btn btn-info"
>
Till kalaset!
</a>
</div>
</div>
</div>
)
}
}
export default ConfirmationPage
|
const async = require('async');
const tasks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const queue = async.queue((task, completed) => {
console.log('Currently Busy Processing Task ' + task);
setTimeout(() => {
const remaining = queue.length();
completed(null, { task, remaining });
}, 1000);
}, 5);
console.log(`Did the queue start ? ${queue.started}`);
tasks.forEach(task => {
queue.push(task, (error, { task, remaining }) => {
if (error) {
console.log(`An error occurred while processing task ${task}`);
} else {
console.log(`Finished processing task ${task}. ${remaining} tasks remaining`);
}
});
});
queue.drain(() => {
console.log('Successfully processed all items');
});
console.log(`Did the queue start ? ${queue.started}`);
|
{
"class" : "Page::ring::app::business_cat_directory"
}
|
import React from "react";
import { Link } from "react-router-dom";
import "../styles/MovieInfo.css";
import Star from "../styles/images/star.png";
import Placeholder from "../styles/images/placeholder.png";
import MoviePlaceholder from "../styles/images/moviePlaceholder.png";
const MovieInfo = (props) => {
console.log(props);
let posterImg = "https://image.tmdb.org/t/p/w300" + props.movie.poster_path;
const genres = props.movie.genres.map((genre, i) => {
return (
<h4 key={i}>{genre.name}</h4>
);
});
let director = null;
for (let i = 0; i < props.movie.credits.crew.length; i++) {
if (props.movie.credits.crew[i].job === "Director") {
director = props.movie.credits.crew[i].name;
break;
}
}
let videoLink = "";
for (let i = 0; i < props.movie.videos.results.length; i++) {
if (props.movie.videos.results[i].type === "Trailer") {
videoLink = "https://www.youtube.com/embed/" + props.movie.videos.results[i].key;
break;
}
}
const shortenCast = props.movie.credits.cast.slice(0, 10);
const cast = shortenCast.map((actor, i) => {
let actorImg = "https://image.tmdb.org/t/p/w300" + actor.profile_path;
let link = "/actor/" + actor.id;
return (
<Link to={link} key={i}>
<div className="actor">
<img src={actor.profile_path === null ? Placeholder : actorImg} alt="actor img"/>
<p>{actor.name}</p>
</div>
</Link>
);
});
const similarArr = props.movie.similar.results.slice(0, 10);
const similarMovies = similarArr.map((movie, i) => {
let movieImg = "https://image.tmdb.org/t/p/w300" + movie.poster_path;
let link = "/movie/" + movie.id;
return (
<Link to={link} key={i}>
<div className="similarMovie">
<img src={movie.poster_path !== null ? movieImg : MoviePlaceholder} alt="movie img"/>
</div>
</Link>
);
});
return (
<div className="movieInfo">
<div className="top">
<div className="left">
<div className="poster">
<img src={props.movie.poster_path !== null ? posterImg : MoviePlaceholder} alt="movie poster"/>
</div>
</div>
<div className="right">
<div className="description">
<h1>{props.movie.title} ({props.movie.release_date.slice(0, 4)})</h1>
{props.movie.credits.crew.length !== 0 && <h3>Directed By {director}</h3>}
<div className="genres">
{genres}
</div>
<h4 className="runtime">{props.movie.runtime} minutes</h4>
<div className="summary">
<h3>{props.movie.overview}</h3>
</div>
<div className="rating">
<h2><img src={Star} alt="rating icon"/> {props.movie.vote_average}/10</h2>
</div>
</div>
</div>
</div>
<div className="cast">
<h1>Cast</h1>
{cast}
</div>
{videoLink !== "" &&
<div className="trailer">
<h1>Trailer</h1>
<iframe title="trailer" className="video" src={videoLink} allow="encrypted-media"></iframe>
</div>}
<div className="similar">
<h1>Similar movies</h1>
{similarMovies}
</div>
</div>
);
}
export default MovieInfo;
|
import React, { useState, useEffect, useCallback, useRef, memo } from 'react';
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Footer from '../components/footer';
import hljs from 'highlight.js';
async function fetchTodos() {
const res = await fetch('/api/todos');
if (res.ok) {
const json = await res.json();
return json.todos;
} else {
return [];
}
}
function TodoAdder({ onChangeTodo, onAddTodo, addTodoText }) {
return (
<>
<input type="text" onChange={onChangeTodo} value={addTodoText} />
<button onClick={onAddTodo}>Add</button>
</>
);
}
const TodoList = memo(function TodoList({ todos, onTodosChange }) {
onTodosChange();
return (
<>
{todos.map(todo => (
<div className={styles.todo} key={todo.name}>
<input type="checkbox" checked={todo.done} readOnly />
{todo.name}
</div>
))}
</>
);
});
function TodoApp() {
const [todos, setTodos] = useState([]);
const [addTodoText, setAddTodoText] = useState('');
useEffect(async () => {
const t = await fetchTodos();
setTodos(t);
}, []);
const onAddTodo = useCallback(() => {
setTodos([{
name: addTodoText,
done: false,
}].concat(todos))
}, [addTodoText, todos]);
const onChangeTodo = useCallback(e => setAddTodoText(e.target.value), []);
const onTodosChange = useCallback(() => console.log('Todos change', todos), [todos]);
return (
<div className={styles.todoContainer}>
<h1>My Todo List</h1>
<TodoAdder onChangeTodo={onChangeTodo} onAddTodo={onAddTodo} addTodoText={addTodoText} />
<TodoList todos={todos} onTodosChange={onTodosChange} />
</div>
)
}
export default function Callbacks() {
const codeRef = useRef(null);
useEffect(() => {
hljs.highlightElement(codeRef.current);
}, [codeRef]);
return (
<div className={styles.container}>
<Head>
<title>Callbacks</title>
<meta name="description" content="React workshop" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Callbacks
</h1>
<p>
One of the most expensive operations we can perform with React is re-rendering, it should be avoided where possible. In the previous example, each time
we type some text into the addTodoText input box, we caused a re-render on <code>{'<TodoList />'}</code>. This is because we are re-creating the <code>onTodosChange</code>
method each time <code>{'<TodoApp />'}</code> has any of it's state change. To fix this, we wrap our methods in a <code>useCallback</code> hook. This hook will cache each method
rather than re-creating them on each render. We've also wrapped our <code>{'<TodoList />'}</code> component in a <code>React.memo()</code> call. This will tell the component that it should
only re-render once any of it's props change.
</p>
<pre className={styles.code}>
<code ref={codeRef}>
{`
async function fetchTodos() {
const res = await fetch('/api/todos');
if (res.ok) {
const json = await res.json();
return json.todos;
} else {
return [];
}
}
function TodoAdder({ onChangeTodo, onAddTodo, addTodoText }) {
return (
<>
<input type="text" onChange={onChangeTodo} value={addTodoText} />
<button onClick={onAddTodo}>Add</button>
</>
);
}
const TodoList = memo(function TodoList({ todos, onTodosChange }) {
onTodosChange();
return (
<>
{todos.map(todo => (
<div className={styles.todo} key={todo.name}>
<input type="checkbox" checked={todo.done} readOnly />
{todo.name}
</div>
))}
</>
);
});
function TodoApp() {
const [todos, setTodos] = useState([]);
const [addTodoText, setAddTodoText] = useState('');
useEffect(async () => {
const t = await fetchTodos();
setTodos(t);
}, []);
const onAddTodo = useCallback(() => {
setTodos([{
name: addTodoText,
done: false,
}].concat(todos))
}, [addTodoText, todos]);
const onChangeTodo = useCallback(e => setAddTodoText(e.target.value), []);
const onTodosChange = useCallback(() => console.log('Todos change', todos), [todos]);
return (
<div className={styles.todoContainer}>
<h1>My Todo List</h1>
<TodoAdder onChangeTodo={onChangeTodo} onAddTodo={onAddTodo} addTodoText={addTodoText} />
<TodoList todos={todos} onTodosChange={onTodosChange} />
</div>
)
}
<TodoApp />
`}
</code>
</pre>
<TodoApp />
<p><a href="/7_reducers">Next</a></p>
</main>
<Footer />
</div>
)
}
|
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import SeasonDisplay from './SeasonDisplay'
import Spinner from './Spinner';
// *******************************************************************
// Functional Component Example Counter
// const Contador = () => {
// let [contador, setContador] = useState(51);
// return (
// <div>
// <span>{contador}</span>
// <button
// onClick={() => {
// setContador(contador + 1);
// }}
// >
// Incrementar
// </button>
// <button
// onClick={() => {
// setContador(contador - 1);
// }}
// >
// Decrementar
// </button>
// </div>
// );
// };
// const App = () => {
// return (
// <div>
// <Contador />
// </div>
// );
// };
// *******************************************************************
// ******************************** Example with class component *******************************
// Class Component Example
class App extends React.Component {
// Babel transform this in a constructor function itself.
state = { lat: null, errorMessage: '' };
componentDidMount () {
window.navigator.geolocation.getCurrentPosition(
(position) => this.setState({ lat: position.coords.latitude }),
(err) => this.setState({ errorMessage: err.message }),
)
}
componentDidUpdate () {
console.log("Component Updated!!");
}
renderContent () {
if (!this.state.errorMessage && this.state.lat) {
return <SeasonDisplay lat={this.state.lat} />;
}
if (!this.state.lat && this.state.errorMessage) {
return <div>Error: {this.state.errorMessage}</div>;
}
return <Spinner message='Please accept location request...' />;
}
// Render method
render () {
return (
<div className="border red">
{this.renderContent()}
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('#root'))
|
WebApp.Views.Help = Backbone.Marionette.View.extend({
className: 'help',
template: 'help',
initialize: function () {
this.render();
},
render: function () {
App.renderTemplate(this.template, {}, App._bind(function (html) {
App.layouts.content
.empty()
.append(this.$el.html(html));
}, this));
}
});
|
var extend = require('extend');
var event = require('./event');
// data from (event + policy)
var insuredEvent = {};
extend(insuredEvent, event, {
insuredDuration: {
type: 'Duration',
label: 'Период страхования, кол-во дней'
}
});
module.exports = insuredEvent;
|
import Head from "next/head";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Nav from "../../_components/Nav";
export default function Home() {
return (
<div className="h-screen">
<Head>
<title>Mission Idea Contest Application | UNISEC Thailand</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Nav></Nav>
<div>
<div className="container mx-auto py-20 mt-5">
<h1 className="text-4xl font-bold text-center mx-10 md:mx-0">
Applicant Login
</h1>
</div>
</div>
<div>
<div className="container mx-auto py-20">
Login with
<div>google</div>
<div>facebook</div>
</div>
</div>
<div className="bottom-0 absolute w-full bg-blue-unisec text-white">
<div className="container mx-auto px-20 py-10">
CopyRight © UNISEC Thailand, All Rights Reserved.
</div>
</div>
</div>
);
}
|
import { Avatar, Card, Col, Dropdown, Form, Icon, List, Menu, Row, Select, Tooltip } from 'antd';
import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import numeral from 'numeral';
import StandardFormRow from './components/StandardFormRow';
import TagSelect from './components/TagSelect';
import styles from './style.less';
import CreateForm from '../UserList/components/CreateForm';
import ProjectScore from './components/ProjectScore';
import Input from 'antd/es/input';
import { Link } from 'react-router-dom';
const { Option } = Select;
const FormItem = Form.Item;
class UserProject extends Component {
state={
scoreVisible:false,
selectProject:{
id:-1,
pid:-1
},
status:"",
author:""
};
handleDelete = (student_id,pid)=>{
const {dispatch } = this.props;
dispatch({
type: 'userProject/remove',
payload: {
student_id,
pid
},
})
};
handleScoreModalVisible = (flag,student_id,pid) => {
if (student_id !==undefined){
this.setState({
selectProject:{
student_id,
pid
},
})
}
this.setState({
scoreVisible: !flag,
});
};
handleScore = fields => {
const { dispatch } = this.props;
dispatch({
type: 'userProject/score',
payload: {
...fields
},
});
};
componentDidMount() {
const { dispatch ,location} = this.props;
dispatch({
type:'userProject/getProject'
});
dispatch({
type: 'userProject/fetch',
payload: {
...location.query
},
});
}
render() {
const {
userProject: { list },
userProject: { params },
loading,
form,
myProjects
} = this.props;
const {author,status} = this.state;
const { getFieldDecorator } = form;
const projectMethods={
handleScore :this.handleScore,
handleScoreModalVisible: this.handleScoreModalVisible,
};
const myStatus=["未申请","已申请","第一周","第二周","已提交"];
const CardInfo = ({ projectStatus, projectScore,student_name,student_class}) => (
<div className={styles.cardInfo} >
<div style={{textAlign:"center",marginBottom:"5px"}}>
<p >{"学生姓名"}</p>
<p style={{fontSize:14}}>{student_name}</p>
</div >
<div style={{textAlign:"center",marginBottom:"5px"}}>
<p>完成进度</p>
<p style={{fontSize:14}}>{myStatus[projectStatus]}</p>
</div>
<div style={{textAlign:"center"}}>
<p >{"学生班级"}</p>
<p style={{fontSize:12}}>{student_class}</p>
</div>
<div style={{textAlign:"center"}}>
<p>项目评分</p>
<p>{projectScore}</p>
</div>
</div>
);
const formItemLayout = {
wrapperCol: {
xs: {
span: 24,
},
sm: {
span: 16,
},
},
};
const itemMenu = (
<Menu>
<Menu.Item>
<a target="_blank" rel="noopener noreferrer" href="https://www.alipay.com/">
1st menu item
</a>
</Menu.Item>
<Menu.Item>
<a target="_blank" rel="noopener noreferrer" href="https://www.taobao.com/">
2nd menu item
</a>
</Menu.Item>
<Menu.Item>
<a target="_blank" rel="noopener noreferrer" href="https://www.tmall.com/">
3d menu item
</a>
</Menu.Item>
</Menu>
);
return (
<div className={styles.filterCardList}>
<Card bordered={false}>
<Form layout="inline">
<StandardFormRow
title="所属项目"
block
style={{
paddingBottom: 11,
}}
>
<FormItem>
{getFieldDecorator('category')(
<TagSelect expandable>
{
myProjects.map(item=>{
return <TagSelect.Option value={item.id} key={item.id}>{item.title}</TagSelect.Option>
})
}
</TagSelect>,
)}
</FormItem>
</StandardFormRow>
<StandardFormRow title="其它选项" grid last>
<Row gutter={16}>
<Col lg={8} md={10} sm={10} xs={24}>
<FormItem {...formItemLayout} label="学生学号">
{getFieldDecorator('author', {
initialValue:params.author
})(
<Input
placeholder="不限"
style={{
maxWidth: 200,
width: '100%',
}}
>
</Input>,
)}
</FormItem>
</Col>
<Col lg={8} md={10} sm={10} xs={24}>
<FormItem {...formItemLayout} label="完成进度">
{getFieldDecorator('status', {
initialValue: params.status
})(
<Select
style={{
maxWidth: 200,
width: '100%',
}}
>
<Option value="">不限</Option>
<Option value="0">未申请</Option>
<Option value="1">第一周</Option>
<Option value="2">第二周</Option>
<Option value="3">已提交</Option>
</Select>,
)}
</FormItem>
</Col>
</Row>
</StandardFormRow>
</Form>
</Card>
<br />
<List
rowKey="key"
grid={{
gutter: 24,
xl: 4,
lg: 3,
md: 3,
sm: 2,
xs: 1,
}}
loading={loading}
dataSource={list}
renderItem={item => (
<List.Item key={item.key}>
<Card
hoverable
bodyStyle={{
paddingBottom: 20,
}}
actions={[
<Tooltip key="edit" title="评分" onClick={()=>this.handleScoreModalVisible(this.state.scoreVisible,item.student_id,item.pid)}>
<Icon type="edit" />
</Tooltip>,
<Link to ={ "userproject/detail?pid="+item.pid+"&student_id="+item.student_id}><Tooltip key="calendar" title="查看进度">
<Icon type="calendar" />
</Tooltip></Link>,
<Tooltip title="删除" key="delete" onClick={()=>this.handleDelete(item.student_id,item.pid)}>
<Icon type="delete" />
</Tooltip>,
]}
>
<Card.Meta avatar={<Avatar size="small" src={item.avatar} />} title={item.title} />
<div className={styles.cardItemContent}>
<CardInfo
projectStatus={item.status}
projectScore={numeral(item.score).format('0,0')}
student_name={item.student_name}
student_class = {item.student_class}
/>
</div>
</Card>
</List.Item>
)}
/>
<ProjectScore {...projectMethods} scoreVisible={this.state.scoreVisible} select={this.state.selectProject}/>
</div>
);
}
}
const WarpForm = Form.create({
onValuesChange({ dispatch },props) {
//console.log(props);
// 表单项变化时请求数据
// 模拟查询表单生效
dispatch({
type: 'userProject/getChange',
payload: {
...props
},
});
},
})(UserProject);
export default connect(({ userProject, loading }) => ({
userProject,
myProjects:userProject.projects,
loading: loading.models.userProject,
}))(WarpForm);
|
//漫画目录
import React, {
PureComponent
} from 'react';
import {
Text,
View,
Image,
FlatList,
StyleSheet,
TouchableHighlight,
ToastAndroid,
Platform,
AlertIOS,
} from 'react-native';
import Color from '../../common/color'
import screen from '../../common/screen'
import ComicCellSeparatorComponent from '../../widget/component/ComicCellSeparatorComponent'
export default class ComicMainPage extends PureComponent {
state : {
dataList : Array<Object>,
refreshing : boolean,
}
constructor(props: Object){
super(props);
this.state = {
dataList : [],
refreshing : false,
}
{ (this : any).requestData = this.requestData.bind(this) }
}
componentDidMount() {
this.requestData()
}
requestData() {
this.setState({ refreshing : true })
this.requestList()
}
async requestList() {
try {
let url="http://cartoon.reader.qq.com/v6_5_6/nativepage/cartoon/columns?pagestamp=1&pageType=0"
let response = await fetch(url,{
method:"GET",
headers:{
// 'loginType':'1',
// 'cookie': 'skey=Mq3jiToUaW',
// 'supportmh': '1',
// 'nosid' :'1',
// 'timi' :'1606020697',
// 'gselect': '1',
// 'qimei' :'f3b8238b9d2cf59f',
// 'os': 'android',
// 'supportTS': '2',
'c_platform': 'android',
// 'mversion': '6.5.6.688',
// 'ckey' :'1000010101',
// 'tinkerid': 'qqreader_6.5.6.0888_android-common-327224',
// 'sid': '150252058228180',
// 'safekey':'0977FB8EB0485154F281164A0BF2C92B',
// 'qqnum': '1606020697',
// 'ua': 'OnePlus5#OnePlus5#25',
// 'c_version': 'qqreader_6.5.6.0888_android',
// 'themeid': '1000',
// 'skey': 'Mq3jiToUaW',
// 'channel': '00000',
// 'Host': 'cartoon.reader.qq.com',
// 'Connection': 'Keep-Alive',
}
})
let json = await response.json()
console.log('ComicMainPage:', json)
let dataList = []
for (let i in json.data.dataList) {
let dict = json.data.dataList[i]
var item = new Object()
if(dict.templateType==4){
item.templateType = dict.templateType
item.data = dict.bookList
dataList.push(item)
console.log('11:', item)
}
}
this.setState({
dataList: dataList,
refreshing: false,
})
} catch( error ){
this.setState( {refreshing : false} )
}
}
_onRefresh(){
this.componentDidMount()
}
onPressImg(cid){
var thiz=this
thiz.props.navigation.navigate('ComicDetail',{id:cid})
}
_renderItem (info) {
switch(info.item.templateType)
{
case 0: // 横4:书库 榜单 免费 包月
{
return <View>
</View>
}
break;
case 1: // 一
{
return <View>
</View>
}
break;
case 2:
{
return <View>
</View>
}
break;
case 3: //三
{
return <View>
</View>
}
break;
case 4: // 横2两排
{
return <View style={{justifyContent: 'center', alignItems: 'center',}}>
<TouchableHighlight onPress={()=> this.onPressImg(info.item.data[0].bid)} activeOpacity ={0.5} underlayColor={"#e3e4e5"} >
<Image style={{width:screen.width,height:150,paddingLeft:15,paddingRight:15}}
source={{ uri :info.item.data[0].bookCover }}
resizeMode={Image.resizeMode.stretch}>
</Image>
</TouchableHighlight>
<Text
style={styles.name}
numberOfLines ={1}
ellipsizeMode='tail'
>
{info.item.data[0].name}
</Text>
<Text
style={styles.content}
numberOfLines ={1}
ellipsizeMode='tail'
>
{info.item.data[0].author}
</Text>
<ComicCellSeparatorComponent />
<TouchableHighlight onPress={()=> this.onPressImg(info.item.data[1].bid)} activeOpacity ={0.5} underlayColor={"#e3e4e5"} >
<Image style={{width:screen.width,height:150,paddingLeft:15,paddingRight:15}}
source={{ uri :info.item.data[1].bookCover }}
resizeMode={Image.resizeMode.stretch}>
</Image>
</TouchableHighlight>
<Text
style={styles.name}
numberOfLines ={1}
ellipsizeMode='tail'
>
{info.item.data[1].name}
</Text>
<Text
style={styles.content}
numberOfLines ={1}
ellipsizeMode='tail'
>
{info.item.data[1].author}
</Text>
<ComicCellSeparatorComponent />
<TouchableHighlight onPress={()=> this.onPressImg(info.item.data[2].bid)} activeOpacity ={0.5} underlayColor={"#e3e4e5"} >
<Image style={{width:screen.width,height:150,paddingLeft:15,paddingRight:15}}
source={{ uri :info.item.data[2].bookCover }}
resizeMode={Image.resizeMode.stretch}>
</Image>
</TouchableHighlight>
<Text
style={styles.name}
numberOfLines ={1}
ellipsizeMode='tail'
>
{info.item.data[2].name}
</Text>
<Text
style={styles.content}
numberOfLines ={1}
ellipsizeMode='tail'
>
{info.item.data[2].author}
</Text>
<ComicCellSeparatorComponent />
</View>
}
break;
case 5:
{
return <View>
</View>
}
break;
case 6: // 横3两排
{
return <View>
</View>
}
break;
default:
break;
}
}
// keyExtractor(item) {
// return item.module
// }
render() {
return (
<View style={styles.container}>
<FlatList
data = { this.state.dataList }
onRefresh = { this.requestData }
refreshing = { this.state.refreshing }
showsVerticalScrollIndicator ={false}
// keyExtractor = { this.keyExtractor }
onRefresh={this._onRefresh.bind(this)}
renderItem = { this._renderItem.bind(this) }
/>
</View>
);
}
}
// define your styles
const styles = StyleSheet.create({
container : {
flex : 1,
backgroundColor: 'white'
},
fourItemCard: {
width: screen.width,
},
name:{
backgroundColor:'transparent',
color:Color.text_color_c101,
fontSize:14,
},
content:{
backgroundColor:'transparent',
color:Color.text_color_c103,
fontSize:12,
},
wonderful: {
height: 150,
width: screen.width,
},
introduction: {
height: 100,
width: screen.width,
},
catalogue: {
height: 50,
width: screen.width,
},
scrollableCell: {
width: screen.width,
},
copyRight: {
width: screen.width,
},
commonCell: {
width: screen.width,
},
advCell: {
width: screen.width,
},
originalBook: {
width: screen.width,
},
bookList: {
width: screen.width,
},
});
|
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
export function MyDatePicker({ selected, handleDateSelect, handleDateChange }) {
return (
<DatePicker
selected={selected}
onSelect={handleDateSelect}
onChange={handleDateChange}
/>
);
}
|
import React, { useState, useEffect } from "react";
import JoditEditor from "jodit-react";
import { TextField, makeStyles, Button, Paper } from "@material-ui/core";
import axios from "../../utils/axios";
import AdminLayout from "../../components/admin/AdminLayout";
import { useSnackbar } from "notistack";
import { useParams } from "react-router-dom";
const useStyles = makeStyles((theme) => ({
postContainer: {
height: "fit-content",
padding: theme.spacing(4),
width: "100%",
"& >div": {
margin: "15px 0",
},
},
}));
const config = {
readonly: false,
height: 600,
uploader: {
insertImageAsBase64URI: true,
},
style: {
fontFamily: "charter",
fontSize: 18,
},
};
export default function EditPost() {
const params = useParams();
const [content, setContent] = useState("");
const classes = useStyles();
const { enqueueSnackbar } = useSnackbar();
const [blogValues, setBlogValues] = useState({
topic: "",
blogAvatar: "",
isPublished: true,
});
const handleChange = async (ev) => {
setBlogValues((prev) => ({
...prev,
[ev.target.id]: ev.target.value,
}));
};
useEffect(() => {
const getBlog = async () => {
try {
const { data } = await axios.get(`/api/blog/${params.blogId}`);
setContent(data.blog?.content);
setBlogValues((prevState) => ({
...prevState,
topic: data.blog?.topic,
blogAvatar: data.blog?.blogAvatar,
}));
} catch (err) {
enqueueSnackbar("Error", { variant: "error" });
}
};
getBlog();
// eslint-disable-next-line
}, []);
const handlePostBlog = async (ev) => {
try {
ev.preventDefault();
await axios.put(`/api/admin/blog/${params.blogId}`, {
...blogValues,
content,
});
enqueueSnackbar("Blog Updated", { variant: "success" });
} catch (err) {
enqueueSnackbar("Error", { variant: "error" });
}
};
return (
<AdminLayout>
<h1>Post</h1>
<form onSubmit={handlePostBlog}>
<Paper>
<div className={classes.postContainer}>
<TextField
type="text"
placeholder="Topic"
variant="outlined"
fullWidth
required
onChange={handleChange}
id="topic"
value={blogValues.topic}
/>
<TextField
type="text"
placeholder="Blog Avatar URL"
variant="outlined"
fullWidth
id="blogAvatar"
onChange={handleChange}
value={blogValues.blogAvatar}
required
/>
<JoditEditor
config={config}
value={content}
// onBlur={(newContent) => setContent(newContent)}
tabIndex={1} // tabIndex of textarea
onChange={(newContent) => {
setContent(newContent);
}}
/>
<div>
<Button
type="submit"
variant="contained"
style={{ background: "#3D506E", color: "white" }}
>
Update Blog
</Button>
</div>
</div>{" "}
</Paper>
</form>
</AdminLayout>
);
}
|
/**
* Created by Administrator on 2016/12/21.
*/
function dragDown(obj) {
/**
* 定义变量
*/
var wrapObj = document.querySelector(".wrap");
var targetObj = document.getElementById(obj);
var el = document.documentElement;
var startPos = {};
/**
* 给文档绑定触摸事件
*/
function bindEvent() {
el.addEventListener("touchstart",touchStartFun,false);
el.addEventListener("touchmove",touchMoveFun,false);
el.addEventListener("touchend",touchEndFun,false);
}
/**
* 开始触摸处理函数
*/
function touchStartFun(evt) {
var touchObj = evt.touches[0];
startPos.startX = touchObj.clientX;
startPos.startY = touchObj.clientY;
}
/**
* 创建html节点
*/
function loaddingHtml() {
var divNode = document.createElement("div");
var textNode = document.createTextNode("加载中……");
divNode.appendChild(textNode);
divNode.setAttribute("id","loadding");
wrapObj.appendChild(divNode);
}
/**
* 触摸过程中处理函数
*/
function touchMoveFun(evt) {
var touchObj = evt.changedTouches[0];
var endX = touchObj.clientX;
var endY = touchObj.clientY;
var dValue = endY - startPos.startY;
wrapObj.style.transform = "translateY("+ dValue +"px)";
}
/**
*结束触摸处理函数
*/
function touchEndFun(evt) {
wrapObj.style.transform = "translateY(0)";
var touchObj = evt.changedTouches[0];
var endX = touchObj.clientX;
var endY = touchObj.clientY;
if(startPos.startY > endY) {
loaddingHtml();
}
}
/**
* 判断是否支持触摸事件
*/
function isTouchDevice() {
try {
document.createEvent("TouchEvent");
bindEvent();
}
catch (e) {
alert("您的浏览器不支持TouchEvent事件!");
}
}
isTouchDevice();
}
dragDown("listBox");
|
/* our variable to hold ajax data */
var data;
/* our variable for based url */
var base_url;
/* our variable for api based url */
var apiurl;
/* our variable for based url for image */
var img_base_url = 'http://teamskeetimages.com/design/smallsitema/ae';
/* our variable for ma based url */
var ma_baseurl;
/* our variable for username */
var username;
/* our variable for password */
var password;
/* our variable for email */
var email;
/* our variable for ip */
var ip;
/* our variable for girlname */
var girlname;
/* our variable for girl id */
var girlid;
/* check if we are on girls loop or not. default is no */
var isinloop = 'no';
/* check if we are on favorite page, if yes, lets remove the favorite of selected container on remove */
var isinfavorite = 'no';
/* our variable to hold rating percentage */
var ratingpercentage;
/* our variable to hold rating total vote */
var totalvote;
/* our variable to check if we are on index page */
var isinindex = 'no';
/* our variable for comment start */
var commentstart = 5;
/* our variable for comment count of all */
var commentall = 5;
/* our variable for sitename */
var sitename;
/*check if user has already rated*/
var rated = 0;
var votedis = new Array();
var useragent;
$(function(){
/* For submitting and posting of comments */
$('.bottom').on('click', '#show-comments', function(){
$('#comments-section').fadeIn();
//$('#comments-section').animate({"height": "auto"}, "fast");
})
$('#comment-form > .button').on('click', 'button', function(){
var testonly = {};
/* get today time and date */
var todaydate = $.datepicker.formatDate( "mm/dd/yy", new Date() );
var todaytime = new Date().toString("h:mm tt").toLowerCase();
/* get or comments details */
var comment = $('#comment-form').children('textarea').val();
var commentor = username;
var comment_girl_name = girlname;
var comment_date = todaydate + ' ' +todaytime;
/*clone our container for comments. get the first one only*/
var cloned_div = $('.comments:first').clone().removeClass('first');
/*replace value with new details we get*/
var spanval = $(cloned_div).find('span').html(commentor + ' ' + '<span class="comment-date">' + comment_date + '</span>');
var pval = $(cloned_div).find('p').text(comment);
data = {
name : 'Comments',
commentor_name : commentor,
commentor_nats_id : 99999,
comment : comment,
comment_type : 'video',
comment_girl_name : comment_girl_name.toLowerCase(),
comment_date : Date.parse(comment_date)/1000,
};
if(comment == ''){
alert('Please enter your comment.');
}else{
$.ajax({
type: "POST",
url: apiurl +'rest/comments?sitename=' +sitename,
data: data,
success: function(data){
/*if(data !=0){
$('.modal-body').text('Your comment has been successfully sent!');
}else{
$('.modal-body').text('Something went wrong. please try again');
}
$('#myModal').modal({show:true});*/
/*append the data to our main sub container for comments*/
$(cloned_div).prependTo('#comments-sub-container');
/*var classnumber = $('.comments').length;
console.log(classnumber);
if(classnumber > 5){
$('.comments:last').remove();
}*/
}
});
/*clear textarea value*/
$('#comment-form').children('textarea').val('');
}
});
/* End submitting and posting of comments */
/* For adding girls to favorites */
$('.favorite').on('click', '.favorite-btn', function(){
/*check if we are in a loop of girls or not. if yes, use this var*/
if(isinloop == 'yes'){
girlname = $(this).attr('name');
data = {
username : username,
mid : $(this).attr('girlid'),
};
}else{
data = {
username : username,
mid : girlid,
};
}
if(isinindex == 'yes'){
data.mid = girlid;
}
//console.log(data);
var link = $(this);
var fav_img = $(this).parent();
var operation = $(this).attr('id');
//console.log(fav_img.children('img')).prop('src');
$.ajax({
type: operation,
url: apiurl+'rest/favorites?sitename=' +sitename,
data: data,
success: function(){
if(operation == 'delete'){
link.attr('id', 'post');
if(isinloop == 'yes'){
link.html('<img src="'+img_base_url + '/favorite_icon.png" alt="Remove from favorites" title="Remove from favorites">');
}else{
link.text('ADD TO FAVORITE');
fav_img.children('img').attr('src', img_base_url + '/favorite_icon.png');
}
}else{
link.attr('id', 'delete');
if(isinloop == 'yes' && isinindex == 'no'){
link.html('<img src="'+img_base_url + '/favorite_icon_grayed.png" alt="Add to favorites" title="Add to favorites">');
}else{
link.text('REMOVE FROM FAVORITE');
fav_img.children('img').attr('src', img_base_url + '/favorite_icon_grayed.png');
}
}
if(isinfavorite == 'yes'){
var favorite_id = link.parents().eq(3).attr('id');
console.log(favorite_id);
console.log(data);
var removedFavorite = $('#favorite' + data.mid).fadeOut('fast', function(){
/*if($('.scenes-container:hidden').length('display') === 0) {
$('#scene-list').html('Your favorite list is empty!');
console.log('remove');
}*/
});
console.log(removedFavorite);
}
if( useragent == 'desktop') {
//$('.modal-body').text(girlname + ' ' + data);
//$('#myModal').modal({show:true});
}
},
error: function() {
console.log($.makeArray(arguments));
}
});
});
/* End adding girls to favorites */
/*Adding girl for index only, to avoid conflict with above code*/
$('.favorite-main').on('click', 'a', function(){
girlname = $(this).attr('name');
data = {
username : username,
mid : $(this).attr('girlid'),
};
console.log(data);
var link = $(this);
var operation = $(this).attr('id');
var fav_img = $(this).parent();
$.ajax({
type: operation,
url: apiurl+'rest/favorites?sitename=' +sitename ,
data: data,
success: function(data){
if(operation == 'delete'){
link.attr('id', 'post');
link.text('ADD TO FAVORITE');
fav_img.children('img').attr('src', img_base_url + '/favorite_icon.png');
}else{
link.attr('id', 'delete');
link.text('REMOVE FROM FAVORITE');
fav_img.children('img').attr('src', img_base_url + '/favorite_icon_grayed.png');
}
if( useragent == 'desktop') {
//$('.modal-body').text(girlname + ' ' + data);
//$('#myModal').modal({show:true});
}
},
error: function() {
console.log($.makeArray(arguments));
}
});
});
/* For support such as suggestions and tickets */
$('.suggestion-popup').on('click', function(){
$.ajax({
type: 'GET',
url: baseurl+'/support/Suggestions',
data: data,
success: function(data){
$('.modal-body').html(data);
$('#myModal').modal({show:true});
}
});
});
$('.ticket-popup').on('click', function(){
$.ajax({
type: 'GET',
url: baseurl+'/support/Tickets',
data: data,
success: function(data){
$('.modal-body').html(data);
$('#myModal').modal({show:true});
}
});
});
/* end support such as suggestions and tickets */
/* For ratings. we use raty library to use as our rating modules http://wbotelhos.com/raty */
$(document).on('click', '.rateme', function(){
var girlid = $(this).attr('girlid');
var rating = $(this).attr('id');
if(jQuery.inArray(girlid, votedis) === -1){
$(this).parent().children('.vote-notify').fadeIn().animate({top:-30}, 200, function() {}).delay(3000).fadeOut();
totalvote = $(this).parent().children('span.thumbs-votes').attr('id');
data = {
username : username,
girlid : girlid,
rating: rating
};
console.log(data);
$.ajax({
type: 'POST',
url: apiurl+'rest/ratings?sitename=' + sitename,
data: data,
success: function(data){
//$('.modal-body').html(data);
//$('#myModal').modal({show:true});
}
});
var newvotevalue = parseInt(totalvote) + 1;
$(this).parent().children('span.thumbs-votes').text(newvotevalue + ' votes');
votedis.push(girlid);
}else{
alert('You have already voted on this video');
}
})
/* end ratings */
/* for comments section modal */
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
$('.comments-showmore').on('click', function(){
data = {
girlname: girlname,
commentstart: commentstart,
commentlimit: 5,
type: 'video',
}
$.ajax({
type: 'GET',
url: apiurl+'rest/comments?sitename=' + sitename,
data: data,
dataType: 'json',
success: function(data){
//$(data).appendTo('#comments-sub-container').hide().slideDown();
$.each(data, function(index, element) {
//console.log(element);
var d = new Date;
var dformat = [(d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/') +' ' +
[d.getHours().padLeft(),
d.getMinutes().padLeft()].join(':');
if(d.getHours >= 12){
var timeformat = ' pm';
}else{
var timeformat = ' am';
}
var divelement = '<div class="comments">\
<div class="comment-details">\
<span>paper_rayjohn <span class="comment-date">'+ dformat + timeformat + '</span></span>\
</div>\
<div class="comment-section">\
<p>'+ element.comment +'</p>\
</div>\
</div>';
$(divelement).appendTo('#comments-sub-container').hide().slideDown();
});
}
});
commentstart = commentstart+5;
if(commentstart >= commentall){
$(this).hide();
}
});
$('.comments-popup').on('click', function(){
data = {
girlname: girlname,
}
$.ajax({
type: 'GET',
url: base_url+'/support/Comments',
data: data,
success: function(data){
$('.modal-body').html(data);
$('#myModal').modal({show:true});
}
});
});
/* end comments section modal */
/*tracking for thumbs*/
$('.scenes , .scenes_largeimage').on('click', 'a', function(){
var girl = $(this).children('img').attr("id");
data = {
name: username,
girl: girl,
click_type: 'thumb',
}
$.ajax({
type: 'POST',
url: apiurl+'rest/tracker/create?sitename=' +sitename,
data: data,
success: function(data){
}
});
});
/*tracking for downloads*/
$('.download').on('click', function(){
var girl = $(this).attr("id");
var click_type = $(this).attr("type");
data = {
name: username,
girl: girl,
click_type: click_type,
}
$.ajax({
type: 'POST',
url: apiurl+'rest/tracker/create?sitename=' +sitename,
data: data,
success: function(data){
}
});
});
/*tracking for pictures*/
$('.gallery').on('click', 'a', function(){
console.log($(this));
var girl = $(this).children('img').attr("id");
data = {
name: username,
girl: girl,
click_type: "picture",
}
$.ajax({
type: 'POST',
url: apiurl+'rest/tracker/create?sitename=' +sitename,
data: data,
success: function(data){
}
});
});
/*tracking for video*/
$('#playerwrapper').on('click', function(){
console.log($(this).attr('name'));
/*var girl = $(this).children('img').attr("id");
data = {
name: username,
girl: girl,
click_type: "picture",
}
$.ajax({
type: 'POST',
url: base_url+'/tracker/create',
data: data,
success: function(data){
alert(data);
}
});*/
});
/*for login*/
/*$('#log-me-in').on('click', function(){
$('#err-msg').text('');
var form = $('#log-me-in-form');
var rememberme;
if($('#rememberme').is(":checked")){
rememberme = 1;
}else{
rememberme = 0;
}
data = {
username : $("[name='username']", form).val(),
password : $("[name='password']", form).val(),
captcha : $("[name='captcha']", form).val(),
rememberme : rememberme,
}
$.ajax({
type: 'POST',
url: baseurl+'/login',
data: data,
success: function(data){
if(data == 1){
location.reload();
}else{
$('#err-msg').html(data);
}
}
});
});*/
/* show more story */
$(function(){
$('.readmore').on('click', 'a', function(){
$(this).parent().parent().children('.bot').removeClass('story');
$(this).parent().hide();
});
});
});
|
$(document).ready(function(){
$('.slider').slick(
{
autoplay:true,
autoplaySpeed:4000,
fade:true,
});
var modal = document.getElementsByClassName("modal")[0];
var button = document.getElementById("feedback-but");
var closing = document.getElementsByClassName("close")[0];
button.onclick = function() {
modal.style.display = "block";
}
closing.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
$(':submit').click(function(e) {
let name = document.getElementById('name').value;
let phone = document.getElementById('phone').value;
let email = document.getElementById('email').value;
let nameReg = /^[a-zA-Z\u0401\u0451\u0410-\u044f]{2,40}$/;
let emailReg = /^\S+@\S+\.\S+$/;
let phoneReg = /^[0-9\-\+]{9,15}$/;
let errors = 0;
if (!(name.search(nameReg))) {
$(".error-name").text("");
}
if (!(phone.search(phoneReg))) {
$(".error-phone").text("");
}
if (!(email.search(emailReg))) {
$(".error-email").text("");
}
if ((name==null)||(name.search(nameReg))){
$("#name").addClass("form-error");
$("#name").attr('placeholder', "Поле обязательно для заполнения");
errors++;
if (name.search(nameReg)){
$(".error-name").text("Неверное имя");
}
} else {
$("#name").removeClass("form-error");
$("#name").attr('placeholder', "");
}
if ((phone==null)||(phone.search(phoneReg))){
$("#phone").addClass("form-error");
$("#phone").attr('placeholder', "Поле обязательно для заполнения");
errors++;
if (phone.search(phoneReg)){
$(".error-phone").text("Неверный номер");
}
} else {
$("#phone").removeClass("form-error");
$("#phone").attr('placeholder', "");
}
if ((email==null)||(email.search(emailReg))){
$("#email").addClass("form-error");
$("#email").attr('placeholder', "Поле обязательно для заполнения");
errors++;
if (email.search(emailReg)){
$(".error-email").text("Неверный email");
}
} else {
$("#email").removeClass("form-error");
$("#email").attr('placeholder', "");
}
if (errors == 0) {
return true;
}
if (errors > 0) {
e.preventDefault();
}
})
});
|
//Global Variables
var pattern = [];
var progress = 0;
var gamePlaying = false;
var tonePlaying = false;
var volume = 0.5; //must be between 0.0 and 1.0
var guessCounter = 0;
var numTries = 3; //number of tries
var clueHoldTime = 400; //how long to hold each clue's light/sound
var timer = 0;
var time = 10;
var startTime = 0;
const numButtons = 6; //number of game buttons
const patternSize = 8; //number of patterns
const cluePauseTime = 333; //how long to pause in between clues
const nextClueWaitTime = 1000; //how long to wait before starting playback of the clue sequence
function guessTimer() {
//decrement time by 1 each time
document.getElementById("timeLeft").innerHTML = "Time Left: " + time;
if (time <= 0) {
loseGame();
}
time--;
}
function findDifficulty() {
document.getElementById("easy").classList.remove("hidden");
document.getElementById("medium").classList.remove("hidden");
document.getElementById("hard").classList.remove("hidden");
}
/* set difficulty on click and playsequence */
function setTimeDifficulty(time) {
startTime = time;
document.getElementById("easy").classList.add("hidden");
document.getElementById("medium").classList.add("hidden");
document.getElementById("hard").classList.add("hidden");
document.getElementById("triesLeft").innerHTML = "Tries Left: " + numTries;
playClueSequence();
}
function resetTime() {
time = startTime;
}
function clearTimer() {
clearInterval(timer);
resetTime();
}
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function startGame() {
//initialize game variables
progress = 0;
numTries = 3;
gamePlaying = true;
clueHoldTime = 400;
clearTimer();
// initialize the pattern array with size: patternSize element
for (let i = 0; i < patternSize; i++) {
// getRandomInt: [1,6]
pattern[i] = getRandomInt(numButtons) + 1;
}
document.getElementById("startBtn").classList.add("hidden");
document.getElementById("stopBtn").classList.remove("hidden");
// make visible difficultly buttons
findDifficulty();
}
function stopGame() {
gamePlaying = false;
clearTimer();
document.getElementById("triesLeft").innerHTML = "";
document.getElementById("timeLeft").innerHTML = "";
document.getElementById("startBtn").classList.remove("hidden");
document.getElementById("stopBtn").classList.add("hidden");
// hide difficulty buttons
document.getElementById("easy").classList.add("hidden");
document.getElementById("medium").classList.add("hidden");
document.getElementById("hard").classList.add("hidden");
}
function lightButton(btn){
document.getElementById("button"+btn).classList.add("lit")
}
function clearButton(btn){
document.getElementById("button"+btn).classList.remove("lit")
}
function playSingleClue(btn){
if(gamePlaying){
lightButton(btn);
playTone(btn,clueHoldTime);
setTimeout(clearButton,clueHoldTime,btn);
}
}
function playClueSequence(){
clearTimer();
guessCounter = 0;
let delay = nextClueWaitTime; //set delay to initial wait time
clueHoldTime -= 40; //decrease clueHoldTime by 20 each time
for(let i=0;i<=progress;i++){ // for each clue that is revealed so far
console.log("play single clue: " + pattern[i] + " in " + delay + "ms")
setTimeout(playSingleClue,delay,pattern[i]) // set a timeout to play that clue
delay += clueHoldTime;
delay += cluePauseTime;
}
timer = setInterval(guessTimer, 1000);
}
function guess(btn){
console.log("user guessed: " + btn);
if(!gamePlaying){
return;
}
//guess correct
if (pattern[guessCounter] == btn) {
// the current pattern is completed
if (guessCounter == progress) {
// the last pattern is completed so win
if (progress == pattern.length - 1) {
winGame();
}
// else, continue with next pattern
else {
++progress;
playClueSequence();
}
}
else {
++guessCounter;
}
}
// guess incorrect
else {
// decrease number of tries
--numTries;
document.getElementById("triesLeft").innerHTML = "Tries Left: " + numTries;
// two tries used
if (numTries == 0) {
loseGame();
}
}
}
function loseGame(){
document.getElementById("triesLeft").innerHTML = "";
document.getElementById("timeLeft").innerHTML = "";
clearTimer();
stopGame();
alert("Game Over. You lost.");
}
function winGame(){
document.getElementById("triesLeft").innerHTML = "";
document.getElementById("timeLeft").innerHTML = "";
clearTimer();
stopGame();
alert("Game Over. You won!");
}
// Sound Synthesis Functions
const freqMap = {
1: 201.6,
2: 260.6,
3: 322,
4: 380.2,
5: 443.3,
6: 500.3
}
function playTone(btn,len){
o.frequency.value = freqMap[btn]
g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025)
tonePlaying = true
setTimeout(function(){
stopTone()
},len)
}
function startTone(btn){
if(!tonePlaying){
o.frequency.value = freqMap[btn]
g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025)
tonePlaying = true
}
}
function stopTone(){
g.gain.setTargetAtTime(0,context.currentTime + 0.05,0.025)
tonePlaying = false
}
//Page Initialization
// Init Sound Synthesizer
var context = new AudioContext()
var o = context.createOscillator()
var g = context.createGain()
g.connect(context.destination)
g.gain.setValueAtTime(0,context.currentTime)
o.connect(g)
o.start(0)
|
var f = require('./formatters');
var SolidityType = require('./type');
/**
* SolidityTypeInt is a prootype that represents int type
* It matches:
* int
* int[]
* int[4]
* int[][]
* int[3][]
* int[][6][], ...
* int32
* int64[]
* int8[4]
* int256[][]
* int[3][]
* int64[][6][], ...
*/
var SolidityTypeInt = function () {
this._inputFormatter = f.formatInputInt;
this._outputFormatter = f.formatOutputInt;
};
SolidityTypeInt.prototype = new SolidityType({});
SolidityTypeInt.prototype.constructor = SolidityTypeInt;
SolidityTypeInt.prototype.isType = function (name) {
return !!name.match(/^int([0-9]*)?(\[([0-9]*)\])*$/);
};
module.exports = SolidityTypeInt;
|
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
window.URL = window.URL || window.webkitURL;
var camvideo = document.getElementById('monitor');
if (!navigator.getUserMedia)
{
document.getElementById('messageError').innerHTML =
'Sorry. <code>navigator.getUserMedia()</code> is not available.';
}
navigator.getUserMedia({video: true}, gotStream, noStream);
function gotStream(stream)
{
if (window.URL)
{ camvideo.src = window.URL.createObjectURL(stream); }
else // Opera
{ camvideo.src = stream; }
camvideo.onerror = function(e)
{ stream.stop(); };
stream.onended = noStream;
}
function noStream(e)
{
var msg = 'No camera available.';
if (e.code == 1)
{ msg = 'User denied access to use camera.'; }
document.getElementById('errorMessage').textContent = msg;
}
<!-- Baseado em http://www.adobe.com/devnet/html5/articles/javascript-motion-detection.html -->
var anterior = "";
var frame_ = 0;
var resposta = "";
//~
//~ var audio1 = new Audio('som/no.wav');
//~ var audio2 = new Audio('som/yes.wav');
//~
var audio1 = new Howl({
urls: ['/static/som/no.wav']
})
var audio2 = new Howl({
urls: ['/static/som/yes.wav']
})
// assign global variables to HTML elements
var video = document.getElementById( 'monitor' );
var videoCanvas = document.getElementById( 'videoCanvas' );
var videoContext = videoCanvas.getContext( '2d' );
var layer2Canvas = document.getElementById( 'layer2' );
var layer2Context = layer2Canvas.getContext( '2d' );
var blendCanvas = document.getElementById( "blendCanvas" );
var blendContext = blendCanvas.getContext('2d');
//~ var messageArea = document.getElementById( "messageArea" );
// these changes are permanent
videoContext.translate(videoCanvas.width, 0);
videoContext.scale(-1, 1);
// background color if no video present
videoContext.fillStyle = '#2C3E50';
videoContext.fillRect( 0, 0, videoCanvas.width, videoCanvas.height );
var buttons = [];
var button1 = new Image();
button1.src ="/static/img/apps/webcam/down.png";
var buttonData1 = { name:"1", image:button1, x:20, y:100, w:120, h:120 };
buttons.push( buttonData1 );
var button2 = new Image();
button2.src ="/static/img/apps/webcam/up-r.png";
var buttonData2 = { name:"2", image:button2, x:700, y:100, w:120, h:120 };
buttons.push( buttonData2 );
animate();
var tempo;
function animate()
{
//~ requestAnimationFrame( animate );
render();
blend();
checkAreas();
tempo = setTimeout("animate()", 60);
}
var lastImageData;
function blend()
{
var width = videoCanvas.width;
var height = videoCanvas.height;
// get current webcam image data
var sourceData = videoContext.getImageData(0, 0, width, height);
// create an image if the previous image doesn't exist
if (!lastImageData) lastImageData = videoContext.getImageData(0, 0, width, height);
// create a ImageData instance to receive the blended result
var blendedData = videoContext.createImageData(width, height);
// blend the 2 images
differenceAccuracy(blendedData.data, sourceData.data, lastImageData.data);
// draw the result in a canvas
blendContext.putImageData(blendedData, 0, 0);
// store the current webcam image
lastImageData = sourceData;
}
function differenceAccuracy(target, data1, data2)
{
if (data1.length != data2.length) return null;
var i = 0;
while (i < (data1.length * 0.25))
{
var average1 = (data1[4*i] + data1[4*i+1] + data1[4*i+2]) / 3;
var average2 = (data2[4*i] + data2[4*i+1] + data2[4*i+2]) / 3;
var diff = threshold(fastAbs(average1 - average2));
target[4*i] = diff;
target[4*i+1] = diff;
target[4*i+2] = diff;
target[4*i+3] = 0xFF;
++i;
}
}
function fastAbs(value)
{
return (value ^ (value >> 31)) - (value >> 31);
}
function threshold(value)
{
return (value > 0x15) ? 0xFF : 0;
}
// check if white region from blend overlaps area of interest (e.g. triggers)
function checkAreas()
{
for (var b = 0; b < buttons.length; b++)
{
// get the pixels in a note area from the blended image
var blendedData = blendContext.getImageData( buttons[b].x, buttons[b].y, buttons[b].w, buttons[b].h );
// calculate the average lightness of the blended data
var i = 0;
var sum = 0;
var countPixels = blendedData.data.length * 0.25;
while (i < countPixels)
{
sum += (blendedData.data[i*4] + blendedData.data[i*4+1] + blendedData.data[i*4+2]);
++i;
}
// calculate an average between of the color values of the note area [0-255]
var average = Math.round(sum / (3 * countPixels));
if (average > 50) // more than 20% movement detected
{
//console.log( "Button " + buttons[b].name + " triggered." ); // do stuff
//~ layer2Context.clearRect(0,80,800,300);
if(buttons[b].name=="1") {
//~ anterior = 1;
frame_ = 0;
resposta = "NÃO";
if (anterior != buttons[b].name){
audio1.play();
anterior = buttons[b].name;
}
}
if(buttons[b].name=="2") {
//~ anterior = 2;
frame_ = 0;
resposta = "SIM";
if (anterior != buttons[b].name){
audio2.play();
anterior = buttons[b].name;
}
}
}
}
}
function render() {
if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
// mirror video
layer2Context.clearRect(0,0,videoCanvas.width, videoCanvas.height);
frame_ +=1;
if(frame_===14){
anterior = "999";
if (_invertPosition.checked){
var position = Math.floor((Math.random()*2)+1);
if (position ===1) {buttons[0].x = 20; buttons[1].x=700;
buttons[0].image.src="/static/img/apps/webcam/down.png";
buttons[1].image.src="/static/img/apps/webcam/up-r.png";
}
else {buttons[1].x = 20; buttons[0].x=700;
buttons[0].image.src="/static/img/apps/webcam/down-r.png";
buttons[1].image.src="/static/img/apps/webcam/up.png";
}}
if (_invertTela.checked){
var invert = Math.floor((Math.random()*2)+1);
if (invert ===1){
videoContext.translate(videoCanvas.width, 0);
videoContext.scale(-1, 1);}
}
}
layer2Context.globalAlpha = 0.8;
if (frame_ < 15) {
buttons[0].y-=35; buttons[1].y-=35;
layer2Context.beginPath();
layer2Context.font = '120px arial';
layer2Context.textBaseline = "midle";
layer2Context.textAlign = 'center';
layer2Context.fillStyle = "#fff";
layer2Context.fillText(resposta, 420,120);
layer2Context.globalAlpha = 0.7;
}
else {
buttons[0].y = 51;
buttons[1].y=16;
frame_ = 42;
}
for ( var i = 0; i < buttons.length; i++ )
{layer2Context.drawImage( buttons[i].image, buttons[i].x, buttons[i].y, buttons[i].w, buttons[i].h );}
videoContext.drawImage( video, 0, 0, videoCanvas.width, videoCanvas.height );
}
}
|
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const {SpecReporter} = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./e2e/**/*.e2e-spec.ts' //These are the specs that we want protractor to run. In this case, we’ll be running all the test that we have in the e2e directory and the .e2e-spec.js suffix and extension.
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true, // This tells Protractor to directly connect to the webdriver (instead of connecting to a local Selenium server
// baseUrl: 'http://localhost:4200/',
baseUrl: 'http://localhost:8080',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function () {
}
},
onPrepare() {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
jasmine.getEnv().addReporter(new SpecReporter({spec: {displayStacktrace: true}}));
}
};
|
'use strict';
const propsNames = Array.from(document.getElementsByTagName('th'));
function handleTableClick(event) {
if(event.target.classList.contains('prop__name')) {
if(!event.target.dataset.dir || event.target.dataset.dir === '-1') {
event.target.setAttribute('data-dir', 1);
} else {
event.target.setAttribute('data-dir', -1);
}
table.setAttribute('data-sort-by', event.target.dataset.propName);
sortTable(event.target.dataset.propName, event.target.dataset.dir);
}
}
|
import axios from 'axios'
import {BaseRequests} from "../BaseRequests";
export class AuthRequests extends BaseRequests{
constructor() {
super();
}
async login(userName,password){
const response = await axios.post(this.baseAddress+'login',{userName,password});
return response;
}
async testManagementAuthentication(){
const response = await this.axios.get('login/test/management');
return response.status === 200;
}
async testPersonnelAuthentication(){
const response = await this.axios.get('login/test/personnel');
return response.status === 200;
}
}
|
var SceneInitial = new Phaser.Scene('SceneInitial')
SceneInitial.init = function(data){
}
SceneInitial.preload = function(){
this.load.image('kandinsky', 'assets/amarelovermelhoazulKardinsky.jpg');
this.load.image('faces', 'assets/operariostarsiladoamaral.png' );
this.load.image('job_face', 'assets/job_face.jpg');
this.load.image('salvador', 'assets/persistenciadamemoriaSalvadorDali.jpg');
this.load.image('romeroBrito', 'assets/RomeroBrito.jpg');
this.load.image('seta1', 'assets/seta1.png');
this.load.image('seta2', 'assets/seta2.png');
this.load.image('verse_card', 'assets/verse_card.png');
this.load.image('conectando', 'assets/conectando.png');
this.load.image('start1', 'assets/start1.png');
this.load.image('start2', 'assets/start2.png');
this.load.image('bg', 'assets/bg.png')
this.load.image('bg_card', 'assets/bg_card.png')
this.load.image('frame1', 'assets/frame1.png')
this.load.image('frame2', 'assets/frame2.png')
this.load.image('frame3', 'assets/frame3.png')
this.load.image('agradecimento', 'assets/agradecimentos.png')
this.load.image('theme', 'assets/Theme.png')
}
SceneInitial.create = function(){
var bg = this.add.image(centerX, centerY, 'verse_card').setSize(2440, 1920);
var bg_text = this.add.image(centerX + 100, centerY + 300, 'conectando').setScale(0.5);
var start = this.add.image(centerX - 70, centerY + 420, 'start1').setScale(0.5).setActive(false).setVisible(false).setInteractive();
var i = 0
var connect = setInterval(() => {
i++;
if(i >= 2){
clearInterval(connect);
bg_text.setActive(false).setVisible(false);
start.setActive(true).setVisible(true)
start.on('pointerup', function(){
game.scene.stop('SceneInitial');
game.scene.start('Apresentation');
})
start.on('pointerover', function(){
start.setTexture('start2');
})
start.on('pointerout', function(){
start.setTexture('start1')
})
}
}, 1000);
}
SceneInitial.update = function(){
}
|
// import {createApp} from './app.js'
// const vuexMixin = {
// data: () => ({
// }),
// computed: {
// ...Vuex.mapState(["data", "downloaded"]),
// ...Vuex.mapGetters([])
// },
// methods: {
// ...Vuex.mapActions([
// "loadData"
// ]),
// ...Vuex.mapMutations(["write2state", "stQueryParse"]),
// }
// }
// Vue.mixin(vuexMixin)
// const { i18n, store, router, vm } = createApp()
// router.onReady(() => {
// vm.$mount('#vm')
// })
// // console.log(performance.now() - t0)
|
// handleScroll function 개선해야됨
// 현재는 단순 구현된 부분
class Scroll {
constructor() {
this.sections = document.querySelectorAll(".section");
this.navList = document.querySelector(".nav__list");
this.navItems = document.querySelectorAll(".nav__list li");
this.home = document.querySelector("#home");
this.skills = document.querySelector("#skills");
this.projects = document.querySelector("#projects");
this.aboutMe = document.querySelector("#aboutMe");
this.navHome = document.querySelector(".nav__home");
this.navSkills = document.querySelector(".nav__skills");
this.navProjects = document.querySelector(".nav__projects");
this.navAboutMe = document.querySelector(".nav__aboutMe");
this.setEventListener();
}
setEventListener = () => {
this.navList.addEventListener("click", this.handleClick);
window.addEventListener("scroll", this.handleScroll);
};
handleClick = (e) => {
const target = e.target;
this.sections.forEach((section) => {
if (target.dataset.scroll === section.dataset.scroll) {
section.scrollIntoView({ behavior: "smooth" });
}
});
};
handleScroll = (e) => {
this.navItems.forEach((item) => item.classList.remove("active"));
const homeHeight = this.home.getBoundingClientRect().height;
const skillsHeight = this.skills.getBoundingClientRect().height;
const projectsHeight = this.projects.getBoundingClientRect().height;
const aboutMeHeight = this.aboutMe.getBoundingClientRect().height;
if (scrollY <= this.home.offsetTop + homeHeight / 2) {
setTimeout(() => {
this.navHome.classList.add("active");
}, 100);
} else if (scrollY <= this.skills.offsetTop + skillsHeight / 2) {
setTimeout(() => {
this.navSkills.classList.add("active");
}, 100);
} else if (scrollY <= this.projects.offsetTop + projectsHeight / 2) {
setTimeout(() => {
this.navProjects.classList.add("active");
}, 100);
} else if (scrollY <= this.aboutMe.offsetTop + aboutMeHeight / 2) {
setTimeout(() => {
this.navAboutMe.classList.add("active");
}, 100);
}
};
}
export default Scroll;
|
import React, { useContext } from 'react';
import styled from 'styled-components';
import Container from '../common/Container';
import {Link} from 'react-router-dom';
import { Input } from 'antd';
import {ShoppingCartOutlined} from '@ant-design/icons';
import AuthContext from "../auth/AuthContext";
import logo from './image/shopee-logo.png';
const StyledHeaderSection = styled.div`
display: flex;
justify-content:space-between;
padding-top: 8px;
align-items: center;
`;
const StyledHeader = styled.header`
background-color: #d1011c;
width: 100vw;
padding: 16px 0px;
`
const Navigator = styled.div`
a{
margin: 0px 4px;
color: white;
text-decoration: none;
}
`;
const Toolbar = styled.div`
a{
margin: 0px 6px;
color: white;
text-decoration: none;
}
`;
const Flex = styled.div`
display: flex;
align-items: center;
justify-content:space-between;
`
const Header = ({className}) =>{
const {isAuthenticated, logout}= useContext(AuthContext)
return (
<StyledHeader>
<Container>
<StyledHeaderSection>
<Navigator>
<a href="#">蝦皮購物</a>
<a href="#">下載</a>
<a href="#">追蹤我們</a>
<a href="#">部落格</a>
</Navigator>
<Toolbar>
<a href="#">通知</a>
<a href="#">幫助中心</a>
{isAuthenticated ?(
<div>
<a href="#">Celine</a>
<span onClick={()=>logout()}>登出</span>
</div>
):(
<Link to="/login">登入/註冊</Link>
)}
</Toolbar>
</StyledHeaderSection>
<StyledHeaderSection>
<Link to="/">
{/* <img src="https://images.squarespace-cdn.com/content/v1/587757c93a04116470cb31a9/1567639331318-RCXPSZB9MKSBUX5DMOTT/shopee-logo.png?format=1000w" alt="logo" width="80"></img> */}
<img src={logo} alt="logo" width="80"></img>
</Link>
<Flex>
<Input.Search style={{marginRight: 8}} placeholder="在商城搜尋" onSearch={(value)=>console.log(value)} enterButton />
<Link to="/cart">
<ShoppingCartOutlined style ={{fontSize:32, color:'white'}}/>
</Link>
</Flex>
</StyledHeaderSection>
</Container>
</StyledHeader>
);
};
export default Header;
|
/**
* Route Mappings
* (sails.config.routes)
*
* Your routes tell Sails what to do each time it receives a request.
*
* For more information on configuring custom routes, check out:
* https://sailsjs.com/anatomy/config/routes-js
*/
module.exports.routes = {
/***************************************************************************
* *
* Make the view located at `views/homepage.ejs` your home page. *
* *
* (Alternatively, remove this and add an `index.html` file in your *
* `assets` directory) *
* *
***************************************************************************/
'/': { view: 'pages/homepage' },
//Adding another route
'/items': 'ItemsController.items',
// '/findById/:postId': 'PostsController.findById', //concept called slug
'GET /item/:itemId': 'ItemsController.findById',
//'POST /item': 'ItemsController.create',
//If we want to use Sails actions then:
'POST /item': 'item/create',
//'DELETE /item/:itemId': 'ItemsController.delete',
//If we want to use action file then:
'DELETE /item/:itemId': 'item/delete',
'GET /home': 'home/home'
/***************************************************************************
* *
* More custom routes here... *
* (See https://sailsjs.com/config/routes for examples.) *
* *
* If a request to a URL doesn't match any of the routes in this file, it *
* is matched against "shadow routes" (e.g. blueprint routes). If it does *
* not match any of those, it is matched against static assets. *
* *
***************************************************************************/
};
|
(function () {
'use strict';
angular.module('BlurAdmin.pages.user')
.controller('UserCtrl', UserCtrl);
/** @ngInject */
function UserCtrl($scope, $uibModal, $http) {
var vm = this;
//Função para abri modal usado para criação e edição de clientes
$scope.showUserModal = function (page, size) {
$uibModal.open({
animation: true,
templateUrl: page,
size: size,
scope: $scope,
resolve: {
items: function () {
return $scope.items;
}
}
});
};
//Abre o modal para inserir um novo cliente
$scope.showModalToCreateUser = function(){
$scope.updateUserData = undefined;
$scope.showUserModal('app/pages/user/userModal.html', 'lg');
}
$scope.getPersonById = function(){
if($scope.personSearch.id == undefined){
return;
}
$http({
method : 'POST',
url: '/person/getPersonById',
data: $scope.personSearch.id
})
.success(
function(data) {
$scope.listUsers = []
$scope.listUsers[0] = data;
})
.error(function(result) {
$scope.listUsers = []
});
}
// Lista todos os clientes
$scope.getAllUsers = function () {
$http({
method : 'GET',
url: '/person/getAllPersons',
})
.success(
function(data) {
$scope.listUsers = data;
})
.error(function(result) {
alert("Falha ao listar Pessoas!")
});
};
$scope.getAllUsers();
//Remove um cliente
$scope.deleteUser = function (data) {
if (confirm("Deseja deletar o cliente "+data.name+" ?")) {
$http({
method : 'POST',
url: '/person/deletePerson',
data: {data: data}
})
.success(
function(data) {
$scope.getAllUsers();
})
.error(function(result) {
alert("Falha ao remover pessoa!");
});
}
};
//Exibe o modal para editar um cliente
$scope.showModalToEditUser = function (data) {
$scope.updateUserData = angular.copy(data);
$scope.showUserModal('app/pages/user/userModal.html', 'lg');
};
// Exibe o modal para realizar um asimulação
$scope.showModalToSimulate = function (data) {
$scope.updateUserData = angular.copy(data);
$scope.showUserModal('app/pages/user/userSimulateModal.html', 'md');
};
}
})();
|
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function getSumFib(n) {
let prev = 0;
let current = 1;
let result = 0;
for(let i = 0; ;i++) {
let next = prev + current;
if(next > n) {
break;
}
if(next % 2 === 0) {
result += next;
}
prev = current;
current = next;
}
return result;
}
function main() {
var t =+readLine();
for(var a0 = 0; a0 < t; a0++){
var n = +readLine();
process.stdout.write(getSumFib(n).toString()+"\n");
}
}
|
'use strict';
angular.module('projetCineFilms')
.directive('testAuthent', function () {
return {
restrict: 'A',
controller: function(user) {
user.validConnection();
}
}
});
|
/*
This examples shows net calculating tic tac results.
The database (csv-tic.csv) encodes 80% 0f the complete set of possible board configurations at the end of tic-tac-toe games,
where "X" is assumed to have played first. The target concept is "win for X" (i.e., 1 when "X" has one of 8 possible ways to create a "three-in-a-row").
Attribute Information:
1. top-left-square: {1, 0, 0.5} //1 for X, 0 for o and 0.5 for blank cell
2. top-middle-square: {1, 0, 0.5}
3. top-right-square: {1, 0, 0.5}
4. middle-left-square: {1, 0, 0.5}
5. middle-middle-square: {1, 0, 0.5}
6. middle-right-square: {1, 0, 0.5}
7. bottom-left-square: {1, 0, 0.5}
8. bottom-middle-square: {1, 0, 0.5}
9. bottom-right-square: {1, 0, 0.5}
10. Class: {positive,negative} (1, 0)
The test database (test.csv) encodes rest part of possible board configuration.
*/
var NeuroNet = require('./../Netconstructor.js');
var neuro = new NeuroNet();
neuro.init({csv:true,hidden:[5,3],input:9,est_error:0.01, output:1,l2:0.001,activation:'sigmoid',batch:10,test:100,console_logging:{show_test_error:true,step:10}})
.train('csv-tic.csv','test.csv') //first argument - string of relative path to training data, second - relative path to test data
.save('tic-tac-net.dat')
|
//错误未打印 原因 他的错误信息是在原型上的 但json只能识别本身上的
// 解决 util自带的模块上的format 作用把error转换成一个字符串 会把原型上的检测出来进行转化
const util = require('util');
module.exports = () => {
return (err,req,res,next) => {
res.status(500).json({
// error: err
error: util.format(err)
})
}
}
|
import React ,{useState , useEffect} from 'react';
import {Link} from 'react-router-dom';
import axios from 'axios';
import Header from '../../Header';
import {useDispatch, useSelector} from "react-redux";
import { selectFollowerusers} from "../../../../redux/slices/followeruserSlice";
import { selectNotifications} from "../../../../redux/slices/notificationSlice";
import { Formik } from "formik";
import * as Yup from "yup";
import ReactNotification from 'react-notifications-component'
import 'react-notifications-component/dist/theme.css'
import { store } from 'react-notifications-component';
import { Modal,Button, } from 'react-bootstrap';
import dateFormat from 'dateformat';
const EducationScreen = ({history,match}) =>{
const id = match.params.id;
const [skills,setSkills] = useState([]);
const [user, setUser]= useState(Object);
const [followers,setFollowers] = useState([]);
const [numbersF,setNumbersF] = useState(0);
const [numbersFby,setNumbersFby] = useState(0);
const [etat, setEtat]= useState('Follow');
const [etat1, setEtat1]= useState('');
const [allfollowers,setAllFollowers] = useState([]);
//const [notif, setNotif]= useState([]);
const [notif1, setNotif1]= useState([]);
//const [allfollowers, err, reload] =useSelector(selectFollowerusers);
const [notif, errN, reloadN] =useSelector(selectNotifications);
const [f, setF]= useState([]);
const dateB=dateFormat(user.dateBirth, "mmmm dS, yyyy");
useEffect(() => {
if(!localStorage.getItem("authToken")){
history.push("/login")
}
const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem("authToken")}`
}
axios.get(`https://aaweni.herokuapp.com/api/auth/user/${id}`, {
headers: headers
})
.then((response) => {
setUser(response.data.data);
console.log(user)
})
.catch((error) => {
console.log(error)
})
/** education */
axios.get(`https://aaweni.herokuapp.com/skill/getAll/${id}`, {
headers: headers
})
.then((response) => {
setSkills(response.data);
})
.catch((error) => {
console.log(error)
})
/**get all followers */
axios.get(`https://aaweni.herokuapp.com/followuser/getAllu/${id}`, {
headers: headers
})
.then((response) => {
setFollowers(response.data);
console.log(response.data)
})
.catch((error) => {
console.log(error)
})
axios.get(`https://aaweni.herokuapp.com/followuser/numbers/${id}`, {
headers: headers
})
.then((response) => {
setNumbersF(response.data);
console.log(response.data)
})
.catch((error) => {
console.log(error)
})
axios.get(`https://aaweni.herokuapp.com/followuser/numbersfu/${id}`, {
headers: headers
})
.then((response) => {
setNumbersFby(response.data);
console.log(response.data)
})
.catch((error) => {
console.log(error)
})
/** end followers */
/** Condition d'etat du bouton */
/**get all my followers */
axios.get(`https://aaweni.herokuapp.com/followuser/getAll`, {
headers: headers
})
.then((response) => {
setAllFollowers(response.data);
console.log(response.data)
})
.catch((error) => {
console.log(error)
})
for (let i of allfollowers){
if(id==i.FollowerId){
setEtat('Followed')
console.log(etat)
}else{
setEtat('Follow')
}
}
/**get all my notifs
axios.get(`/notif/getNotif`, {
headers: headers
})
.then((response) => {
setNotif(response.data);
console.log(response.data)
})
.catch((error) => {
console.log(error)
})*/
/* for (let i of notif){
if(id==i._id){
setEtat('Accept invitation')
setEtat1('Refuse invitation')
console.log(etat)
}
}*/
}
,[history,etat,allfollowers]);//,notif,allfollowers
const inviHandler = async () => {
const id = match.params.id;
const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${localStorage.getItem("authToken")}`
}
if (etat=='Follow'){
axios.post(`https://aaweni.herokuapp.com/followuser/add/${id}`,{},{
headers: headers
})
.then((response) => {
console.log(response.data.data);
})
.catch((error) => {
console.log(error)
})
axios.post(`https://aaweni.herokuapp.com/notif/add/${id}`,{body:`you have an invitation from ${user.username} `,title:"new invitation"}, {
headers: headers
})
.then((response) => {
console.log(response.data.data);
})
.catch((error) => {
console.log(error)
})
}else if (etat=='Followed'){
axios.get(`https://aaweni.herokuapp.com/followuser/getAll/${id}`, {
headers: headers
})
.then((response) => {
setF(response.data);
console.log(response.data)
})
.catch((error) => {
console.log(error)
})
for (let i of f){
if(i.FollowerId==id){
axios.delete(`https://aaweni.herokuapp.com/followuser/delete/${i._id}`,{},{
headers: headers
})
.then((response) => {
//console.log(response.data.data);
})
.catch((error) => {
console.log(error)
})
/* axios.post(`/notif/add/${id}`,{body:`${user.username} has deleted his follow `,title:"invitation has been deleted"}, {
headers: headers
})
.then((response) => {
console.log(response.data.data);
})
.catch((error) => {
console.log(error)
}) */ }
}
}
}
return (
<>
<Header/>
<body>
<ReactNotification/>
<div id="wrapper">
<div class="main_content">
<div class="mcontainer">
<div class="profile user-profile bg-white rounded-2xl -mt-4">
<div class="profiles_banner">
<img src={user.coverPicture} alt=""/>
<div class="profile_action absolute bottom-0 right-0 space-x-1.5 p-3 text-sm z-50 lg:flex">
</div>
</div>
<div class="profiles_content">
<div class="profile_avatar">
<div class="profile_avatar_holder">
<img src={user.profilePicture} alt="profle picture"/>
</div>
<div class="user_status status_online"></div>
<div class="icon_change_photo" hidden> <ion-icon name="camera" class="text-xl"></ion-icon> </div>
</div>
<div class="profile_info">
<h1> {user.username} </h1>
<p> Family , Food , Fashion , Fourever <a href="#">Edit </a></p>
</div>
</div>
<div class="flex justify-between lg:border-t flex-col-reverse lg:flex-row">
<nav class="cd-secondary-nav pl-2 is_ligh -mb-0.5 border-transparent">
<ul>
<li ><a href="#0">Posts</a></li>
<li ><Link to={`/userdetails/${user._id}`} >Educations</Link></li>
<li ><Link to={`/userdetailsE/${user._id}`} >Experiences </Link></li>
<li ><Link to={`/userdetailsP/${user._id}`} >Projects </Link></li>
<li class="active"><Link to={`/userdetailsS/${user._id}`} >Skills</Link></li>
</ul>
</nav>
<div class="flex items-center space-x-1.5 flex-shrink-0 pr-3 justify-center order-1">
{/**<a href="#" class="text-blue-500"> See all </a> */}
<button onClick={inviHandler} class="flex items-center justify-center h-10 px-5 rounded-md bg-blue-600 text-white space-x-1.5">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-5">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V7z" clip-rule="evenodd"></path>
</svg>
<span> {etat} </span>
</button>
</div>
</div>
</div>
<div class="lg:flex lg:mt-8 mt-4 lg:space-x-8">
<div class="space-y-5 flex-shrink-0 lg:w-7/12">
<img src="assets/user/images/education.jpg" style={{width:'150px', height:'150px',marginLeft:'200px'}} alt=""/>
{/** Educations */}
{ skills.map((val,key) => {
const dateS=dateFormat(val?.startDate, "mmmm dS, yyyy");
const dateF=dateFormat(val?.endDate, "mmmm dS, yyyy");
return(
<div key={key}>
<div class="row">
<div class="card border-info mb-3" style={{height:'50px',width:'570px'}}>
<div class="card-body">
<h5 style={{marginLeft:'10px'}} class="card-title">{val?.name}</h5>
</div>
</div>
</div>
</div>
)})}
{/** Educations */}
</div>
<div class="lg:w-4/12 space-y-6">
{/*<!-- start about -->*/}
<div class="widget">
<h4 class="text-2xl mb-3 font-semibold"> About </h4>
<ul class="text-gray-600 space-y-4">
<li class="flex items-center space-x-2">
<ion-icon name="globe" class=" rounded-full bg-gray-200 text-xl p-1.5 mr-3"></ion-icon>
Birthday <strong> {dateB} </strong>
</li>
<li class="flex items-center space-x-2">
<ion-icon name="heart-sharp" class=" rounded-full bg-gray-200 text-xl p-1.5 mr-3"></ion-icon>
From <strong> {user.country} </strong>
</li>
<li class="flex items-center space-x-2">
<ion-icon name="heart-sharp" class=" rounded-full bg-gray-200 text-xl p-1.5 mr-3"></ion-icon>
Adress <strong> {user.address} </strong>
</li>
<li class="flex items-center space-x-2">
<ion-icon name="home-sharp" class=" rounded-full bg-gray-200 text-xl p-1.5 mr-3"></ion-icon>
Email <strong> {user.email} </strong>
</li>
<li class="flex items-center space-x-2">
<ion-icon name="home-sharp" class=" rounded-full bg-gray-200 text-xl p-1.5 mr-3"></ion-icon>
Phone Number <strong> {user.numTel} </strong>
</li>
<li class="flex items-center space-x-2">
<ion-icon name="logo-rss" class=" rounded-full bg-gray-200 text-xl p-1.5 mr-3"></ion-icon>
Flowwed By <strong> {numbersFby} Peaple </strong>
</li>
</ul>
</div>
{/*<!-- end about -->*/}
{/*<!-- start friends -->*/}
<div class="widget border-t pt-4">
<div class="flex items-center justify-between mb-4">
<div>
<h4 class="text-2xl -mb-0.5 font-semibold"> Friends </h4>
<p> {numbersF} Friends</p>
</div>
<a class="text-blue-600 ">See all</a>
</div>
<div class="grid grid-cols-3 gap-3 text-gray-600 font-semibold">
{ followers.map((val,key) => {
return(
<div key={key}>
<a href="#">
<div class="avatar relative rounded-md overflow-hidden w-full h-24 mb-2">
<img src={val.profilePicture} alt="" class="w-full h-full object-cover absolute"/>
</div>
<div> {val.username} </div>
</a>
</div>
)})}
</div>
<a class="text-blue-600 "></a><a href="#" class="bg-gray-100 py-2.5 text-center font-semibold w-full mt-4 block rounded"> See all </a>
</div>
{/*<!-- end friends -->*/}
</div>
</div>
</div>
</div>
</div>
</body>
</>
)
}
export default EducationScreen;
|
// import React from 'react';
// // import { createStackNavigator } from "@react-navigation/stack";
// // import { createCompatNavigatorFactory } from "@react-navigation/compat";
// // import { NavigationContainer } from '@react-navigation/native';
// import RegisterDevice from './RegisterDevice';
// import RegistrationComplete from './RegistrationComplete';
// import DeviceScanner from './DeviceScanner';
// const Stack = createStackNavigator();
// function App() {
// return (
// <NavigationContainer>
// <Stack.Navigator initialRouteName="RegisterDevice">
// <Stack.Screen name="RegisterDevice" component={RegisterDevice} />
// <Stack.Screen name="RegistrationComplete" component={RegistrationComplete} />
// <Stack.Screen name="DeviceScanner" component={DeviceScanner} />
// </Stack.Navigator>
// </NavigationContainer>
// );
// }
// export default App;
|
import CONSTANT from "../src/constants.js";
export default (data) => {
const err = {};
if (!data.value) {
err[data.name] = CONSTANT.EMPTY_QUERY;
}
return err;
};
export const isEmpty = (value) => {
return value.length === 0;
};
export const isEmptyObj = (obj) => {
return Object.keys(obj).length === 0;
};
|
import { connect } from 'react-redux';
import EmailAcceptConfigurationEditDialog from './EmailAcceptConfigurationEditDialog';
import {Action} from '../../../action-reducer/action';
import {getPathValue} from '../../../action-reducer/helper';
import helper,{postOption, fetchJson, showError, validValue} from '../../../common/common';
import {updateTable} from './EmailAcceptConfigurationContainer';
import LeadDialog from './LeadDialog';
import showPopup from '../../../standard-business/showPopup';
const prefix = ['config', 'emailAccept', 'accept', 'edit'];
const action = new Action(prefix);
const parent_fix = ['config', 'emailAccept', 'accept'];
const CLOSE_ACTION = action.assignParent({edit: undefined});
const URL_LEAD_LIST ='/api/config/emailAccept/lead_list';
const URL_EMAIL_DROP = '/api/config/emailAccept/email_drop';
const URL_ACCEPT_ADD = '/api/config/emailAccept/accept_add';
const URL_ACCEPT_EDIT = '/api/config/emailAccept/accept_edit';
const URL_EXCEL_LIST = '/api/config/emailAccept/excel';
const getSelfState = (rootState) => {
return getPathValue(rootState, prefix);
};
export const buildEditState = (config, data={}, edit, editIndex=-1) => {
return {
...config,
edit,
editIndex,
title: edit ? config.edit : config.add,
visible: true,
value: data,
tableItems: edit ? data.details : []
};
};
const changeActionCreator = (key, value) => (dispatch, getState) => {
const { editControls, editControls1} = getSelfState(getState());
if(key === 'uploadMode' && value){
if(value === 'upload_mode_epld_excel'){
dispatch(action.update({type: 'search', required: true}, 'editControls', {key: 'key', value: 'excelModelConfigId'}));
dispatch(action.update({type: 'search', required: true}, 'editControls1', {key: 'key', value: 'excelModelConfigId'}));
}else{
dispatch(action.assign({[key]: value, excelModelConfigId: ''}, 'value'));
dispatch(action.update({type: 'readonly', required: false}, 'editControls', {key: 'key', value: 'excelModelConfigId'}));
dispatch(action.update({type: 'readonly', required: false}, 'editControls1', {key: 'key', value: 'excelModelConfigId'}));
}
}
dispatch(action.assign({[key]: value}, 'value'));
};
const formSearchActionCreator = (key, title) => async (dispatch, getState) => {
const {controls, value, editControls, editControls1} = getSelfState(getState());
let body, res;
if(key === 'emailAddressConfigId'){
body = {maxNumber: 10, filter: title};
res = await fetchJson(URL_EMAIL_DROP, postOption(body));
let index = {key: 'key', value: 'emailAddressConfigId'};
dispatch(action.update({options: res.result}, 'controls', index));
dispatch(action.update({options: res.result}, 'editControls1', index));
} else if(key ==='excelModelConfigId'){
res = await fetchJson(`${URL_EXCEL_LIST}/${value.importTemplateConfigId.value}`);
let index = {key: 'key', value: 'excelModelConfigId'};
dispatch(action.update({options: res.result}, 'editControls', index));
dispatch(action.update({options: res.result}, 'editControls1', index));
}else if(key ==='importTemplateConfigId'){
body = {maxNumber: 10, filter: title};
res = await fetchJson(URL_LEAD_LIST, postOption(body));
let options = [];
res.result.map((item) => {
options.push({
value: item.id,
title: item.uploadSubject
})
});
let index = {key: 'key', value: 'importTemplateConfigId'};
dispatch(action.update({options}, 'editControls1', index));
}
};
const contentChangeActionCreator = (rowIndex, keyName, value) => (dispatch, getState) => {
dispatch(action.update({[keyName]: value}, 'tableItems', rowIndex));
};
const contentSearchActionCreator = (rowIndex, keyName, value) => async(dispatch, getState) => {
const {tableCols, tableItems} = getSelfState(getState());
if(keyName === 'excelModelConfigId' && tableItems[rowIndex].importTemplateConfigId){
const {returnCode, result, returnMsg} = await fetchJson(`${URL_EXCEL_LIST}/${tableItems[rowIndex].importTemplateConfigId.value}`);
if(returnCode !== 0){
showError(returnMsg);
return;
}
const newOptions = result;
const {options = {}} = tableItems[rowIndex];
const newOption = Object.assign({}, options, {'excelModelConfigId': newOptions});
dispatch(action.update({options: newOption}, 'tableItems', rowIndex));
}
};
const addActionCreator = async(dispatch, getState) => {
const {leadConfig, value, tableItems, result, edit} = getSelfState(getState());
const onOk = (checkedItems=[]) => {
for(let i = 0; i< checkedItems.length; i++) {
let isRequired = [];
let isReadonly = [];
if(checkedItems[i].uploadMode === 'upload_mode_epld_excel'){
checkedItems[i].isRequired=['excelModelConfigId'];
checkedItems[i].isReadonly = [];
}else{
checkedItems[i].isReadonly=['excelModelConfigId'];
checkedItems[i].isRequired = [];
}
}
if(tableItems.length <=0){
dispatch(action.assign({ tableItems: checkedItems }));
}else{
dispatch(action.assign({ tableItems: tableItems.concat(checkedItems) }));
}
};
const res = await fetchJson(URL_LEAD_LIST, postOption({ filter: ''}));
if(res.returnCode === 0) {
const leadDialogConfig = leadConfig;
const props = {
...leadDialogConfig,
items: res.result,
tableItems,
onOk
};
return showPopup(LeadDialog, props);
}else if(res.returnCode !== 0){
showError(res.returnMsg);
}
};
const delActionCreator = (dispatch, getState) => {
const state = getSelfState(getState());
const [ ...tableItems ] = state.tableItems;
const items = tableItems.filter(item => !item.checked);
dispatch(action.assign({tableItems: items}));
};
const okActionCreator = () => async (dispatch, getState) => {
const {edit, controls, value, tableItems, tableCols, editControls, editControls1} = getSelfState(getState());
let postData, res;
if(!edit){
const list = tableItems.filter(item=>item.isRequired && item.isRequired.length>0);
if(list.some(item => !item.excelModelConfigId) ){
return showError('请填写必填项!');
} else if (!validValue(controls, value)) {
dispatch(action.assign({valid: true}));
return;
}else if (!helper.validArray(tableCols, tableItems.filter(item => !item.readonly))) {
dispatch(action.assign({valid: true, form: false}));
return;
}
postData = {
id: edit? value.id: '',
emailAddressConfigId: value.emailAddressConfigId.value,
datas: tableItems? tableItems.map(item => helper.convert(item)) : []
};
res = await fetchJson(URL_ACCEPT_ADD, postOption(postData));
}else{
if(value.active === "active_unactivated"){
if (!validValue(editControls1, value)) {
dispatch(action.assign({valid: true}));
return;
}
}else{
if (!validValue(editControls, value)) {
dispatch(action.assign({valid: true}));
return;
}
}
res = await fetchJson(URL_ACCEPT_EDIT, postOption(helper.convert(value), 'put'));
}
if (res.returnCode !== 0) {
showError(res.returnMsg);
return;
}
dispatch(CLOSE_ACTION);
return updateTable(dispatch, getState);
};
const exitValidActionCreator = () => {
return action.assign({valid: false});
};
const cancelActionCreator = () => (dispatch) => {
dispatch(CLOSE_ACTION);
};
const toolbars = {
add: addActionCreator,
del: delActionCreator
};
const clickActionCreator = (key) => {
if (toolbars.hasOwnProperty(key)) {
return toolbars[key];
} else {
console.log('unknown key:', key);
return {type: 'unknown'};
}
};
const mapStateToProps = (state) => {
return getSelfState(state);
};
const actionCreators = {
onOk: okActionCreator,
onCancel:cancelActionCreator,
onChange: changeActionCreator,
onSearch: formSearchActionCreator,
onContentChange: contentChangeActionCreator,
onContentSearch: contentSearchActionCreator,
onClick: clickActionCreator,
onExitValid: exitValidActionCreator
};
const container = connect(mapStateToProps, actionCreators)(EmailAcceptConfigurationEditDialog);
export default container;
|
import React from 'react';
import Proptypes from 'prop-types';
import classes from './index.module.css';
import {withRouter} from 'react-router-dom';
class SearchInputReact extends React.Component{
constructor(props) {
super(props);
}
componentDidMount() {
// this.props.onSubmit();
}
render() {
return (
<form onSubmit={this.props.onSubmit}>
<input
id="searchInput"
name="keyword"
type="text"
value={this.props.keyword}
className={`flex-fill p-0 form-control ${classes.searchInput}`}
placeholder="通过以下方式搜索"
onChange={this.props.onChange}
/>
{/*<button type="submit">submit</button>*/}
</form>
);
}
}
SearchInputReact.propTypes = {
keyword: Proptypes.string.isRequired,
onChange: Proptypes.func.isRequired,
onSubmit: Proptypes.func.isRequired
};
export const SearchInput = withRouter(SearchInputReact);
|
'use strict';
angular.module('vegewroApp')
.controller('GuideCtrl', ['$scope', function ($scope) {
$scope.jshint = 'scope is used';
}]);
|
import React from 'react';
import axios from 'axios';
function myHOC(Component, url) {
return class extends React.Component{
constructor(){
super();
this.state ={
data: null
}
}
getData = () => {
axios.get(url).then(stuff => {
this.setState({data: stuff.data})
})
}
render() {
return (
<>
{
this.state.data
? <Component {...this.props} data={this.state.data} />
:
this.getData()
}
</>
)}
}
}
export default myHOC;
|
// ARRAY METHODS
// var animal = "lion";
// var animals = ["sheep", "goat", "dog", "cat"];
// animals.unshift(animal);
// console.log(animals.pop());
// arr = ("i", "study", "javascript");
// arr.spice(1, 1);
// console.log (arr);
// arr.slice([start], [end])
// let arr = ["t", "e", "s", "t"];
// console.log(arr.slice(1, 3));
// console.log(arr.slice(-2));
// animals.forEach(function(animal) {
// console.log(`${animal} can also speak?`);
// });
// let users = [
// {id: 1, name: "john"},
// {id: 2, name: "pete"},
// {id: 3, name: "mary"},
// ];
// let someUsers = users.filter((item) =>item.id<3);
// console.log (someUsers[0].name);
// let users = [
// {id: 1, name: "john", age: 18},
// {id: 2, name: "pete", age: 20},
// {id: 3, name: "mary", age: 14},
// ];
// let underAge = users.filter(function (users){
// return users.age <19;
// });
// console.log(underAge);
// console.log(users);
// let arr = ["Bilbo", "Gandalf", "Nazgul"]
// let lengths = arr.map(item=>item.length);
// console.log(lengths);
// let arr2=[4, 89, 32]
// let calculate = arr2.map(item=>item*6);
// console.log(calculate)
// let calc = function (grade) {
// return grade / 2;
// }
// let arr2=[4, 89, 32]
// let calculate = arr2.map(calc);
// console.log(calculate);
let names = 'Bilbo, Gandalf, Nazgul';
let arr = names.split(', ');
arr.forEach((names)=>{
console.log (`A message to ${names}.`);
})
let arr2=["Bilbo", "Gandalf", "Nazgul"];
let str = arr2.john(';');
let combine=arr2.join('')
console.log (str);
console.log(combine)
|
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Home from "./components/Home";
/* import Login from './components/Login/Login';
import Products from './components/Products/Products';*/
import { MovieDetails } from "./components/MovieDetails.js";
import { Films } from "./data";
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route path="/" exact component={Home} Films={Films} />
{/* <Route path="/login" exact component={Login} />
<Route
path="/products"
exact
render={() => <Products products={products} />}
/>*/}
<Route
path="/MovieDetails/:id"
render={(props) => <MovieDetails {...props} Films={Films} />}
/>
</Switch>
</Router>
</div>
);
}
export default App;
|
import * as mysql from 'mysql2/promise';
import chalk from 'chalk';
export async function getTables(params, verbose) {
//
if (params.host !== 'localhost' && !params.hasOwnProperty('compress')) {
params.compress = true;
}
const conn = await mysql.createConnection(params).catch(logException);
if (conn === undefined) {
if (verbose) {
logVerbose("Can't create a connection");
}
return;
}
if (verbose) {
logVerbose('Connection established');
logVerbose('Query table list');
}
// Tables
var [rows, fields] = await conn
.query(
`
SELECT table_name, engine, table_collation, auto_increment, create_options
FROM information_schema.tables
WHERE table_schema = ? AND table_type = 'BASE TABLE'
ORDER BY table_name
`,
[params.database]
)
.catch(logException);
if (verbose) {
logVerbose('Got ' + rows.length + ' row(s), ' + fields.length + ' field(s)');
}
if (rows.length == 0) {
//Empty result
conn.end();
return [];
}
let tableProps = {};
let tables = rows.map(row => {
tableProps[row.table_name] = {
name: row.table_name,
engine: row.engine,
collation: row.table_collation,
auto_increment: row.auto_increment,
options: row.create_options,
columns: [],
indexes: []
};
return tableProps[row.table_name];
});
// Columns
if (verbose) {
logVerbose('Query columns');
}
[rows, fields] = await conn
.query(
`
SELECT table_name, column_name, column_type, is_nullable, column_default, extra
FROM information_schema.columns
WHERE table_schema = ?
ORDER BY table_name ASC, ordinal_position ASC
`,
[params.database]
)
.catch(logException);
if (verbose) {
logVerbose('Got ' + rows.length + ' row(s), ' + fields.length + ' field(s)');
}
for (let row of rows) {
let table = tableProps[row.table_name];
if (table === undefined) {
logWarning('Unexpected table name in columns result', row.table_name);
continue;
}
table.columns.push({
name: row.column_name,
type: row.column_type,
is_nullable: row.is_nullable.toUpperCase(),
default: row.column_default,
extra: row.extra.toUpperCase()
});
}
// Indexes
if (verbose) {
logVerbose('Query indexes');
}
[rows, fields] = await conn
.query(
`
SELECT table_name, index_name, index_name='PRIMARY' AS is_primary, NOT non_unique AS is_unique, GROUP_CONCAT(column_name ORDER BY seq_in_index) AS columns
FROM information_schema.statistics
WHERE table_schema=?
GROUP BY table_name, index_name
ORDER BY table_name, is_primary DESC, non_unique ASC, index_name ASC
`,
[params.database]
)
.catch(logException);
if (verbose) {
logVerbose('Got ' + rows.length + ' row(s), ' + fields.length + ' field(s)');
}
for (let row of rows) {
let table = tableProps[row.table_name];
if (table === undefined) {
logWarning('Unexpected table name in indexes result', row.table_name);
continue;
}
table.indexes.push({
name: row.index_name,
columns: row.columns,
is_primary: row.is_primary,
is_unique: row.is_unique
});
}
conn.end();
return tables;
}
function logException(e) {
console.error(chalk.redBright('Error: ' + e.message));
}
function logWarning(text) {
console.error(chalk.grey('Warning: ' + text));
}
function logVerbose(text) {
console.error(chalk.grey(text));
}
function formatColumn(col, tableName) {
let def = [];
def.push(' `' + col.name + '`');
def.push(col.type);
if (col.is_nullable === 'NO') {
def.push('NOT NULL');
}
let dv = col.default;
if (dv !== null) {
if (dv === 'NULL') {
def.push('DEFAULT NULL');
} else if (dv.search(/^\'[\s\S]*\'$/g) != -1) {
def.push('DEFAULT ' + dv);
} else {
def.push("DEFAULT '" + dv + "'");
}
} else if (col.is_nullable === 'NO') {
logVerbose('Notice: Column `' + tableName + '`.`' + col.name + '` is NOT NULL and has no DEFAULT value');
} else if (col.is_nullable === 'YES') {
logVerbose('Notice: Add DEFAULT NULL to column `' + tableName + '`.`' + col.name + '`');
def.push('DEFAULT NULL');
}
if (col.extra !== '') {
def.push(col.extra);
}
return def.join(' ');
}
function formatIndex(index, tableName) {
let def = [];
if (index.is_primary == 1) {
def.push(' PRIMARY KEY');
} else if (index.is_unique == 1) {
def.push(` UNIQUE KEY \`${index.name}\``);
} else {
def.push(` KEY \`${index.name}\``);
}
def.push(
'(' +
index.columns
.split(',')
.map(col => {
return `\`${col}\``;
})
.join(',') +
')'
);
return def.join(' ');
}
function formatTableProps(table) {
let def = [];
def.push('ENGINE=' + table.engine);
if (table.auto_increment !== null) {
def.push('AUTO_INCREMENT=N');
}
let charset = table.collation.split('_', 2)[0]; // in 'latin1_swedish_ci' a charset is the string before first '_' : 'latin1'
def.push('DEFAULT CHARSET=' + charset);
return def;
}
export function formatTableForComparison(table) {
//
let cols = table.columns.map(col => {
return formatColumn(col, table.name);
});
let sql = `CREATE TABLE \`${table.name}\` (\n`;
sql += cols.join(',\n');
let indexes = table.indexes.map(index => {
return formatIndex(index, table.name);
});
if (indexes.length > 0) {
sql += ',\n' + indexes.join(',\n');
}
sql += '\n)';
let props = formatTableProps(table);
if (props.length > 0) {
sql += '\n';
sql += props.join('\n');
}
return sql;
}
|
import React, { useState } from 'react';
import { Select, MenuItem, Typography, Grid, Toolbar, AppBar } from '@material-ui/core';
import Type from '../helper/pokeTypeHelper';
import logo from '../imgs/logo.png'
function Header(props) {
const [selectedLanguage, setSelectedLanguage] = useState("galarian");
const [selectedType, setSelectedType] = useState("normal");
return (
<AppBar position="static">
<Toolbar>
<Grid
container
justify="flex-start"
alignItems="center"
>
<Grid item>
<img height="40px" src={logo} alt="logo" />
</Grid>
<Grid item>
<Typography variant="h4" style={{ fontFamily: "galarian" }}>
PokeLair
</Typography>
</Grid>
</Grid>
<Grid
container
justify="flex-end"
alignItems="center"
>
<Grid item>
<Typography variant="caption">
Type Store:
</Typography>
</Grid>
<Grid item>
<Select
value={selectedType}
style={{textTransform: 'capitalize'}}
onChange={(e) => {
setSelectedType(e.target.value)
props.handleTypeChange(e.target.value)
}}
label="oie"
>
{Type.typeStringList.map((type) =>
<MenuItem key={type} style={{textTransform: 'capitalize'}} value={type}>
<Typography variant="caption">
{type}
</Typography>
</MenuItem>)
}
</Select>
</Grid>
<Grid item>
<Typography style={{ fontFamily: "classic" }} variant="caption">
Language:
</Typography>
</Grid>
<Grid item>
<Select
value={selectedLanguage}
onChange={(e) => {
setSelectedLanguage(e.target.value)
props.handleFontChange(e.target.value)
}}
>
<MenuItem value={"galarian"}>
<Typography variant="caption" style={{ fontFamily: "galarian" }}>
Galarian
</Typography>
</MenuItem>
<MenuItem value={"classic"}>
<Typography variant="caption" style={{ fontFamily: "classic" }}>
English
</Typography>
</MenuItem>
</Select>
</Grid>
</Grid>
</Toolbar>
</AppBar>
);
}
export default Header;
|
$(function () {
$("#tablaUsuario").DataTable();
setTimeout(function ()
{
$(".loader").fadeOut("slow");
}, 2000);
soloLetras($("#userName"));
soloLetras($("#userNameEditar"));
$(".editarUsuarios").click(function () {
editarEliminar("../AgregarUsuario", $(this).val());
});
$("#addUser").click(function () {
setTimeout(function ()
{
}, 2000);
addUsrs("../addUser", $("#formAddUsuario").serialize())
});
$("#updateUsuario").click(function(){
editarUsuario("../EditarEliminarUsuarios",$("#formEditarUsuario").serialize());
});
$("#eliminarUsuario").click(function(){
$("#exampleModalEliminar").modal("show");
$(".recibirEliminarUsuario").val($(this).val());
});
$(".recibirEliminarUsuario").click(function(){
eliminarEditar("../EditarEliminarUsuarios",$(this).val());
});
});
function addUsrs(url, datos) {
$.ajax({
url: url,
type: "POST",
data: datos,
success: function (res) {
console.log(res);
if (res == 1) {
$("#exampleModal").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("No deje campos vacios");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$("#exampleModal").modal("show");
}, 2000);
} else if (res == 2) {
} else if (res == 3) {
$("#exampleModal").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("Las contraseñas no coinciden");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$("#exampleModal").modal("show");
}, 2000);
} else if (res == 4) {
$("#exampleModal").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("Éste usuario ya existe");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$("#exampleModal").modal("show");
}, 2000);
} else if (res == 5) {
$("#exampleModal").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("Éste usuario se Agrego correctamente");
$(location).attr("href","../Vista/usuarios.jsp");
setTimeout(
function ()
{
$("#exampleModal").modal("hide");
}, 2000);
} else if (res == 6) {
$("#exampleModal").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("El usuario no se Agregó");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$("#exampleModal").modal("hide");
}, 2000);
}
},
error: function (jqXHR, status, error) {
console.log(status);
}, complete: function (jqXHR, status) {
console.log(status);
}, timeoute: 4000
});
return false;
}
function editarEliminar(url, data) {
$.ajax({
url: url,
type: "post",
data: {da: data},
success: function (respuesta) {
console.log(respuesta);
setTimeout(
function ()
{
$(".loader").fadeOut("slow");
}, 2000);
$("#claveUsuario").val(respuesta.clave_Usuario);
$("#userNameEditar").val(respuesta.nombre_Usuario);
console.log(respuesta.clave_Empleado);
},
error: function (jqXHR, status, error) {
console.log(status);
}, complete: function (jqXHR, status) {
console.log(status);
}, timeoute: 4000
});
return false;
}
function eliminarEditar(url, data) {
$.ajax({
url: url,
type: "GET",
data: {dat: data},
success: function (r) {
console.log(r);
if (r == 1) {
$("#exampleModalEditar").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("Éste usuario se elimino correctamente");
$("#exampleModalEliminar").modal("hide");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$(location).attr("href","../Vista/usuarios.jsp");
// actualizandoDatosAjax();
}, 2000);
} else if (r == 2) {
$("#exampleModal").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("El usuario no se elimino");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$("#exampleModal").modal("hide");
}, 2000);
}
setTimeout(
function ()
{
$(".loader").fadeOut("slow");
}, 2000);
},
error: function (jqXHR, status, error) {
console.log(status);
}, complete: function (jqXHR, status) {
console.log(status);
}, timeoute: 4000
});
return false;
}
function editarUsuario(url, data) {
$.ajax({
url: url,
type: "post",
data:data,
success: function (respuesta) {
console.log(respuesta);
if(respuesta==1){
$("#exampleModalEditar").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("No deje campos vacios");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$("#exampleModal").modal("show");
}, 2000);
}else if(respuesta==3){
$("#exampleModalEditar").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("Las contraseñas no coinciden");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$("#exampleModal").modal("show");
}, 2000);
}else if(respuesta==4){
$("#exampleModal").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("Éste usuario ya existe");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$("#exampleModal").modal("show");
}, 2000);
}else if(respuesta==5){
$("#exampleModalEditar").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("Éste usuario se Actualizo correctamente");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
// actualizandoDatosAjax();
}, 5000);
}else if(respuesta==6){
$("#exampleModal").modal("hide");
$("#exampleModalMensajeUsuario").modal("show");
$("#mensajeUsuario").text("Mensaje");
$(".mensajesUsuarios").text("El usuario no se Agregó");
setTimeout(
function ()
{
$("#exampleModalMensajeUsuario").modal("hide");
$("#exampleModal").modal("hide");
}, 2000);
}
setTimeout(
function ()
{
$(".loader").fadeOut("slow");
}, 2000);
},
error: function (jqXHR, status, error) {
console.log(status);
}, complete: function (jqXHR, status) {
console.log(status);
}, timeoute: 4000
});
return false;
}
function actualizandoDatosAjax() {
$.ajax({
url: "../cargandoUsuarios",
type: "post",
success: function (llenarDatosUsuarios) {
console.log(llenarDatosUsuarios);
$(".tableUsuario").html(llenarDatosUsuarios);
},
error: function (jqXHR, status, error) {
console.log(status);
}, complete: function (jqXHR, status) {
console.log(status);
}, timeoute: 4000
});
return false;
}
function valNum(num) {
$(num).bind('keypress', function (e) {
var value = $(num).val();
var characterCode = (e.which) ? e.which : e.keyCode;
if (characterCode == 46 && value.indexOf('.') != -1)
return false;
if (characterCode != 46 && characterCode > 31 && (characterCode < 48 || characterCode > 57))
return false;
return true;
});
}
function soloLetras(letra) {
$(letra).keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122)//letras mayusculas
&& (key.charCode < 65 || key.charCode > 90) //letras minusculas
&& (key.charCode != 45) //retroceso
&& (key.charCode != 241) //ñ
&& (key.charCode != 209) //Ñ
&& (key.charCode != 32) //espacio
&& (key.charCode != 225) //á
&& (key.charCode != 233) //é
&& (key.charCode != 237) //í
&& (key.charCode != 243) //ó
&& (key.charCode != 250) //ú
&& (key.charCode != 193) //Á
&& (key.charCode != 201) //É
&& (key.charCode != 205) //Í
&& (key.charCode != 211) //Ó
&& (key.charCode != 218) //Ú
)
return false;
});
}
|
$(document).ready(function(){
//发送请求,页面加载,默认开始加载分类为推荐的文章列表
var keyWord=window.location.search;
console.log(keyWord);
$.getJSON("/article/search"+keyWord,function(jsondata){
console.log(jsondata.code);
if (jsondata.code!=0) {
alert("系统繁忙,请稍后再试~~");
return false;
}
if (jsondata.data.length==0)
{
alert("系统没有找到相关内容,请重新输入关键字!");
return false;
}
else{
refreshArticleList(jsondata.data);
console.log(jsondata.data);
}
});
$("#search").click(function(){
$("#articleList").empty();
var keyWord=$("#keyWord").val();
console.log(keyWord);
$.getJSON("/article/search?key_word="+keyWord,function(jsondata){
if (jsondata.code!=0) {
alert("系统繁忙,请稍后再试~~");
return false;
}
if (jsondata.data.length==0)
{
alert("系统没有找到相关内容,请重新输入关键字!");
return false
}
else{
refreshArticleList(jsondata.data);
console.log(jsondata.data);
}
});
});
//页面加载每篇文章的信息
function refreshArticleList(articles){
$("#articleList").empty();
for (var i = 0; i < articles.length; i++) {
var articleDiv = getArticleDiv(articles[i]);
$("#articleList").append(articleDiv);
}
}
//页面加载单篇文章的具体内容
function getArticleDiv(article){
var section= "<section>"+
"<div class=\"l-top\">"+
"<img src=\"" + article.author_head_url + "\">"+
"<h5 class=\"l2\">" + article.like_cnt + "</h5>"+
"<h4><a href=\"/front/html/article.html?article_id=" + article.id + "\".id +>" +article.title+"</a></h4>"+
"<p><b>"+article.author+"</b><span>"+article.author_desp+"</span></p></div>"+
"<div class=\"l-buttom\"><div class=\"summary\">"+
"<img src=\""+article.cover_url+"\">"+
"<span class=\"p\">"+article.summary+"</span></div><div class=\"bottom\">"+
"<span class=\"r\" >阅读("+article.click_cnt+")</span>"+
"<span class=\"c\">点赞(" + article.like_cnt + ")</span></div></div>"+
"</section>"
return section;
}
window.onload = function(){
//登录后改变html内容和退出登录
function getCookieValue(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0)
{
return c.substring(name.length,c.length);
}
}
return "";
}
function checkCookie() {
var user_name=getCookieValue("user_name");
var role=getCookieValue("role");
console.log(user_name);
if (user_name!="" && role==1) {
console.log('add editer');
$("#register").text("退出");
$("#register").attr("href","/login/logout");
$("#writer").text(user_name+"编辑");
$("#writer").css("front-size","13px");
$("#writer").attr("href","/front/html/writer.html");
}
else if (user_name!=""){
$("#login").text(user_name);
$("#register").text("退出");
$("#register").attr("href","/login/logout");
}
console.log("role:" + role);
}
//导航条的点击变色和发送请求
checkCookie();
}
});
|
// Generated by CoffeeScript 1.7.1
(function() {
var Canvas, Circle, Color, Curve, Line, Polygon, Rectangle, Shape, Square, roundRectangle,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Color = (function() {
function Color() {}
Color.transparent = 'rgba(0,0,0,0)';
Color.red = 'rgb(255,0,0)';
Color.green = 'rgb(0,255,0)';
Color.blue = 'rgb(0,0,255)';
Color.yellow = 'rgb(255,255,0)';
Color.black = 'rgb(0,0,0)';
Color.white = 'rgb(255,255,255)';
Color.gray = 'rgb(127,127,127)';
Color.aqua = 'rgb(0,255,255)';
Color.redish = 'rgba(255,0,0,0.25)';
Color.greenish = 'rgba(0,255,0,0.25)';
Color.bluish = 'rgba(0,0,255,0.25)';
return Color;
})();
Canvas = (function() {
window.Canvas = Canvas;
function Canvas(id) {
var canvas, grid;
grid = (function(_this) {
return function(n, d, max) {
var color, gap, length, x, y, _i, _j, _ref, _results;
_ref = [50, 50, 500], n = _ref[0], gap = _ref[1], length = _ref[2];
for (x = _i = -n; -n <= n ? _i <= n : _i >= n; x = -n <= n ? ++_i : --_i) {
color = x === 0 ? Color.redish : Color.greenish;
new Line(_this, [gap * x, -length], [gap * x, length]).stroke(color).draw();
}
_results = [];
for (y = _j = -n; -n <= n ? _j <= n : _j >= n; y = -n <= n ? ++_j : --_j) {
color = y === 0 ? Color.redish : Color.bluish;
_results.push(new Line(_this, [-length, gap * y], [length, gap * y]).stroke(color).draw());
}
return _results;
};
})(this);
canvas = $("#" + id).get(0);
this.unsupported = canvas == null;
if (this.unsupported) {
"System error: No <canvas id=\'" + id + "\" /> DOM element.";
} else {
this.unsupported = canvas.getContext == null;
if (this.unsupported) {
"Sorry, your browser doesn't support drawing. (I.e., HTML5 canvas)";
} else {
this.context = canvas.getContext('2d');
grid();
}
}
}
Canvas.toRadians = function(angle) {
if (angle.degrees != null) {
return Math.PI / 180 * angle.degrees;
} else {
return angle.radians;
}
};
return Canvas;
})();
Shape = (function() {
function Shape(canvas) {
this.canvas = canvas;
this.context = this.canvas.context;
this.color = Color.transparent;
this.strokeColor = Color.black;
this.lineWidth = 1;
this.scaleWidthHeight = [1, 1];
this.translateXY = [1, 1];
}
Shape.prototype.fill = function(color) {
this.color = color;
return this;
};
Shape.prototype.stroke = function(strokeColor) {
this.strokeColor = strokeColor;
return this;
};
Shape.prototype.strokeWidth = function(lineWidth) {
this.lineWidth = lineWidth;
return this;
};
Shape.prototype.rotate = function(angle) {
this.angle = angle;
return this;
};
Shape.prototype.scale = function(scaleWidthHeight) {
this.scaleWidthHeight = scaleWidthHeight;
return this;
};
Shape.prototype.translate = function(translateXY) {
this.translateXY = translateXY;
return this;
};
Shape.prototype.drawShape = function(drawSpecfic) {
if (this.canvas.unsupported) {
return;
}
this.context.save();
this.context.fillStyle = this.color;
this.context.strokeStyle = this.strokeColor;
this.context.lineWidth = this.lineWidth;
this.context.beginPath();
this.context.rotate(this.angle * Math.PI / 180);
this.context.scale(this.scaleWidthHeight[0], this.scaleWidthHeight[1]);
this.context.translate(this.translateXY[0], this.translateXY[1]);
drawSpecfic();
this.context.closePath();
this.context.fill();
this.context.stroke();
this.context.restore();
return this;
};
return Shape;
})();
Line = (function(_super) {
__extends(Line, _super);
function Line(canvas, from, to) {
this.from = from;
this.to = to;
this.draw = __bind(this.draw, this);
Line.__super__.constructor.call(this, canvas);
}
Line.prototype.draw = function() {
return this.drawShape((function(_this) {
return function() {
_this.context.moveTo(_this.from[0], _this.from[1]);
return _this.context.lineTo(_this.to[0], _this.to[1]);
};
})(this));
};
return Line;
})(Shape);
Circle = (function(_super) {
__extends(Circle, _super);
function Circle(canvas, center, radius) {
this.center = center;
this.radius = radius;
this.draw = __bind(this.draw, this);
Circle.__super__.constructor.call(this, canvas);
}
Circle.prototype.draw = function() {
return this.drawShape((function(_this) {
return function() {
return _this.context.arc(_this.center[0], _this.center[1], _this.radius, 0, 2 * Math.PI, true);
};
})(this));
};
return Circle;
})(Shape);
Rectangle = (function(_super) {
__extends(Rectangle, _super);
function Rectangle(canvas, xy, wh) {
this.xy = xy;
this.wh = wh;
this.draw = __bind(this.draw, this);
Rectangle.__super__.constructor.call(this, canvas);
}
Rectangle.prototype.draw = function() {
return this.drawShape((function(_this) {
return function() {
return _this.context.rect(_this.xy[0], _this.xy[1], _this.wh[0], _this.wh[1]);
};
})(this));
};
return Rectangle;
})(Shape);
roundRectangle = (function(_super) {
__extends(roundRectangle, _super);
function roundRectangle(canvas, x, y, width, height, radius) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.radius = radius;
this.draw = __bind(this.draw, this);
roundRectangle.__super__.constructor.call(this, canvas);
}
roundRectangle.prototype.draw = function() {
return this.drawShape((function(_this) {
return function() {
_this.context.moveTo(_this.x + _this.radius, _this.y);
_this.context.lineTo(_this.x + _this.width - _this.radius, _this.y);
_this.context.quadraticCurveTo(_this.x + _this.width, _this.y, _this.x + _this.width, _this.y + _this.radius);
_this.context.lineTo(_this.x + _this.width, _this.y + _this.height - _this.radius);
_this.context.quadraticCurveTo(_this.x + _this.width, _this.y + _this.height, _this.x + _this.width - _this.radius, _this.y + _this.height);
_this.context.lineTo(_this.x + _this.radius, _this.y + _this.height);
_this.context.quadraticCurveTo(_this.x, _this.y + _this.height, _this.x, _this.y + _this.height - _this.radius);
_this.context.lineTo(_this.x, _this.y + _this.radius);
return _this.context.quadraticCurveTo(_this.x, _this.y, _this.x + _this.radius, _this.y);
};
})(this));
};
return roundRectangle;
})(Shape);
Square = (function(_super) {
__extends(Square, _super);
function Square() {
this.draw = __bind(this.draw, this);
return Square.__super__.constructor.apply(this, arguments);
}
Square.prototype.draw = function() {
return this.drawShape((function(_this) {
return function() {
return _this.context.rect(_this.xy[0], _this.xy[1], _this.wh, _this.wh);
};
})(this));
};
return Square;
})(Rectangle);
Polygon = (function(_super) {
__extends(Polygon, _super);
function Polygon(canvas, points) {
this.points = points;
this.draw = __bind(this.draw, this);
Polygon.__super__.constructor.call(this, canvas);
}
Polygon.prototype.draw = function() {
return this.drawShape((function(_this) {
return function() {
var i, _results;
i = 1;
_this.context.moveTo(_this.points[0][0], _this.points[0][1]);
_results = [];
while (i < _this.points.length) {
_this.context.lineTo(_this.points[i][0], _this.points[i][1]);
_results.push(i++);
}
return _results;
};
})(this));
};
return Polygon;
})(Shape);
Curve = (function(_super) {
__extends(Curve, _super);
function Curve(canvas, startP, cp1, cp2, xy) {
this.startP = startP;
this.cp1 = cp1;
this.cp2 = cp2;
this.xy = xy;
this.draw = __bind(this.draw, this);
Curve.__super__.constructor.call(this, canvas);
}
Curve.prototype.draw = function() {
return this.drawShape((function(_this) {
return function() {
_this.context.moveTo(_this.startP[0], _this.startP[1]);
return _this.context.bezierCurveTo(_this.cp1[0], _this.cp1[1], _this.cp2[0], _this.cp2[1], _this.xy[0], _this.xy[1]);
};
})(this));
};
return Curve;
})(Shape);
$().ready(function() {
var canvas, circle, curves, lines, polygon, rectCanvas, roundRectCanvas, trsCanvas;
canvas = new Canvas('robot');
new Polygon(canvas, [[150, 0], [50, 50], [250, 50]]).fill(Color.red).draw();
new Rectangle(canvas, [50, 50], [200, 100]).fill(Color.white).draw();
new Circle(canvas, [100, 75], 20).fill(Color.blue).draw();
new Circle(canvas, [200, 75], 20).fill(Color.blue).draw();
new Square(canvas, [137, 90], 25).fill(Color.green).draw();
new Line(canvas, [150, 90], [150, 115]).draw();
new Curve(canvas, [125, 125], [125, 150], [175, 150], [175, 125]).fill(Color.black).draw();
rectCanvas = new Canvas('rectangle');
new Rectangle(rectCanvas, [50, 0], [200, 100]).fill(Color.yellow).draw();
roundRectCanvas = new Canvas('roundRect');
new roundRectangle(roundRectCanvas, 100, 5, 100, 100, 20).fill(Color.aqua).draw();
trsCanvas = new Canvas('trs');
new Square(trsCanvas, [0, 0], 25).fill(Color.green).draw();
new Square(trsCanvas, [0, 0], 25).translate([25, 25]).scale([2, 2]).fill(Color.green).draw();
new Square(trsCanvas, [0, 0], 25).translate([75, 0]).scale([2, 2]).rotate(25).fill(Color.green).draw();
lines = new Canvas('line');
new Line(lines, [0, 0], [150, 115]).draw();
new Line(lines, [150, 0], [150, 115]).stroke(Color.red).strokeWidth(10).draw();
polygon = new Canvas('polygon');
new Polygon(polygon, [[150, 0], [50, 50], [250, 50]]).fill(Color.green).draw();
new Polygon(polygon, [[150, 50], [100, 75], [125, 125], [175, 125], [200, 75]]).fill(Color.red).draw();
curves = new Canvas('curves');
new Curve(curves, [125, 125], [125, 150], [175, 150], [175, 125]).fill(Color.black).draw();
new Curve(curves, [0, 50], [50, 0], [100, 50], [100, 50]).draw();
circle = new Canvas('circles');
new Circle(circle, [50, 75], 50).fill(Color.blue).draw();
return new Circle(circle, [200, 75], 10).fill(Color.blue).draw();
});
}).call(this);
|
define([
'jquery',
'underscore',
'backbone',
'js/config',
'js/templates/newEntry'
], function($, _, Backbone, APP){
APP.Views.NewEntry = Backbone.View.extend({
template : _.template(APP.Templates.newEntry),
// events: {
// 'click #minusEmail': 'removeEmail',
// 'click #minusNumber': 'removeNumber'
// },
render: function(){
this.$el.html( this.template(this.model.attributes));
return this;
}
// removeEmail: function(){
// this.remove();
// },
// removeNumber: function(){
// this.remove();
// }
});
});
|
const data = [
{
team_number: 228,
nickname: "Letitia",
city: "Cetronia",
country: "U.S",
state_prov: "Palau",
address: "Seigel Court",
website: "https://www.google.com",
competition: "sfr",
},
{
team_number: 152,
nickname: "Williamson",
city: "Mansfield",
country: "U.S",
state_prov: "Kansas",
address: "Sapphire Street",
website: "https://www.google.com",
competition: "sfr",
},
{
team_number: 1954,
nickname: "Phyllis",
city: "Alderpoint",
country: "U.S",
state_prov: "Puerto Rico",
address: "Vanderbilt Avenue",
website: "https://https://www.google.com",
competition: "sfr",
},
{
team_number: 1714,
nickname: "Jill",
city: "Gardiner",
country: "U.S",
state_prov: "Virgin Islands",
address: "Heath Place",
website: "https://www.google.com",
competition: "sfr",
},
{
team_number: 492,
nickname: "Love",
city: "Leeper",
country: "U.S",
state_prov: "Kentucky",
address: "Hutchinson Court",
website: "https://www.google.com",
competition: "sfr",
},
{
team_number: 482,
nickname: "Young",
city: "Katonah",
country: "U.S",
state_prov: "Georgia",
address: "Bank Street",
website: "https://www.google.com",
competition: "sfr",
},
{
team_number: 610,
nickname: "Soto",
city: "Accoville",
country: "U.S",
state_prov: "Idaho",
address: "Bond Street",
website: "https://www.google.com",
competition: "sfr",
},
{
team_number: 687,
nickname: "Whitaker",
city: "Succasunna",
country: "U.S",
state_prov: "Texas",
address: "Division Place",
website: "https://www.google.com",
competition: "sfr",
},
{
team_number: 684,
nickname: "Fleming",
city: "Wescosville",
country: "U.S",
state_prov: "North Carolina",
address: "Lincoln Terrace",
website: "https://www.google.com",
competition: "sfr",
},
{
team_number: 1011,
nickname: "Park",
city: "Watchtower",
country: "U.S",
state_prov: "Florida",
address: "Batchelder Street",
website: "https://https://www.google.com",
competition: "sfr",
},
]
/* @type {
[key: string]: { mean: number; standardDeviation: number }
} */
const s = data.reduce(
(pv, cv) => ({
...pv,
[cv.team_number]: {
matchData: [{ "Team Number": cv.team_number }],
stats: {
"Number of Balls": {
mean: Math.floor(Math.random() * 60),
standardDeviation: Math.floor(Math.floor(Math.random() * 60)),
},
"Number of Rings": {
mean: Math.floor(Math.random() * 60),
standardDeviation: Math.floor(Math.floor(Math.random() * 60)),
},
"Points Scored": {
mean: Math.floor(Math.random() * 100),
standardDeviation: Math.floor(Math.floor(Math.random() * 100)),
},
},
},
}),
{}
)
module.exports.teams = data
module.exports.data = s
|
require('./../server')
const chai = require('chai')
chai.use(require('chai-http'))
global.httpTest = chai.request(`http://localhost:${config.port}`)
global.expect = chai.expect
const bluebird = require('bluebird')
const redis = require('redis')
bluebird.promisifyAll(redis)
global.storeTest = redis.createClient()
|
import React, { useState, useEffect } from "react";
import WorkItem from "../elements/WorkItem";
import works from "../data/WorksData.json";
function Works() {
const [filter, setFilter] = useState("all works");
const [projects, setProjects] = useState([]);
useEffect(() => {
setProjects([works.items]);
}, []);
useEffect(() => {
setProjects([]);
let worksUpdated = [];
for (let i = 0; i < works.items.length; i++) {
if (
filter !== "all works" &&
!works.items[i].category.includes("portfolio-hidden")
) {
works.items[i].category = `${works.items[i].category} portfolio-hidden`;
}
if (filter === "all works") {
let x = works.items[i].category.split(" ");
works.items[i].category = x[0];
}
if (works.items[i].category.includes(filter)) {
works.items[i].category = filter;
}
worksUpdated.push(works.items[i]);
}
setProjects(worksUpdated);
}, [filter]);
const worksFilters = ["all works", "frontend", "fullstack"];
const displayWorks = projects.map((item, i) => (
<WorkItem
key={i}
title={item.name}
category={item.category}
image={item.image}
id={item.id}
/>
));
return (
<section id="portfolioSection" className="section">
<div className="container">
<div className="row">
<div className="col-12 col-lg-6 portfolio-main-title anim-bot">
<h1 className="section-big-title">
My selected work. <br /> Always a work in progress.
</h1>
</div>
<div className="col-12 col-lg-6 portfolio-filters anim-bot">
<nav className="nav portfolio-nav anim-bot">
{worksFilters.map((item, i) => (
<a
key={i}
className={`nav-item ${filter === item ? "active" : null}`}
onClick={() => setFilter(item)}
href="/#"
>
{item}
</a>
))}
</nav>
</div>
</div>
<div className="row works-wrapper">{displayWorks}</div>
</div>
</section>
);
}
export default Works;
|
describe('UserService', function () {
beforeEach(module('app'));
var UserService, $httpBackend;
beforeEach(inject(function ($injector){
UserService = $injector.get('UserService');
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('GET', '/rest/user').respond({
user: "Cernan Bernardo", email: "cernan@gmail.com"
});
}));
it('should make a get request', function(done){
$httpBackend.expectGET('/rest/user');
UserService
.getUser()
.then(function(res){
var data = res.data;
if (data.email === 'cernan@gmail.com' && data.user === 'Cernan Bernardo'){
done();
}
});
$httpBackend.flush();
});
it('should combine the user"s first and last name', function(){
expect(UserService.createFullName({first_name: "Cernan", last_name: "Bernardo"})).toBe('Cernan Bernardo');
});
});
|
var sectionModel = require('../model/section');
var userModel = require('../model/user');
var postModel = require('../model/post');
var reportPostModel = require('../model/reportPost');
var navbarLinkModel = require('../model/navbarLink');
module.exports.index = function (req, res) {
var results={}
Promise.all([
userModel.countDocuments().exec(),
postModel.countDocuments().exec(),
postModel.distinct('tag').exec(),
postModel.distinct('commentObject').exec(),
reportPostModel.countDocuments().exec()
]).then(function(counts) {
results['user']=counts[0];
results['post']=counts[1];
results['tag']=counts[2].length;
results['comment']=counts[3].length;
results['reportPost']=counts[4];
console.log(results);
res.render('admin/index',{layout:'admin/layout',title:'Admin',user : req.user,results:results});
});
}
module.exports.section = function (req, res) {
var page=req.query.page != undefined ? req.query.page-1 : 0;
if (req.method === 'GET') {
sectionModel.find().skip(page*10).limit(10).exec(function (err, results) {
if(err) return res.status(404).send(err);
sectionModel.countDocuments().exec(function (err, count) {
if(err) return res.status(404).send(err);
res.render('admin/table/section',{layout:'admin/layout',title:'Admin',user : req.user,results:results,count:count,page:page});
});
});
}
else{
var post = req.body;
var title = post.title.toLowerCase();
var subTitle = post.subTitle;
var name = post.name;
var icon = post.icon;
var sectionObject = new sectionModel({
title:title,
subTitle:subTitle,
name: name,
icon: icon
})
sectionObject.save(function (err,results) {
if (!err) {
res.redirect('/admin/section')
}
else {
var count=sectionModel.countDocuments().exec();
res.render('admin/index',{layout:'admin/layout',title:'Admin',user : req.user,results:results,count:count,ErrorMsg: name+" not save"});
}
})
}
}
module.exports.sectionEdit = function (req, res) {
if (req.method === 'GET') {
var id=req.params.id;
sectionModel.findById(id).exec(function (err, results) {
if(err) return res.status(404).send(err);
res.render('admin/edit/section',{layout:'admin/layout',title:'Admin',user : req.user,results:results});
});
}
else{
var post = req.body;
var id=post.id;
var title = post.title.toLowerCase();
var subTitle = post.subTitle;
var name = post.name;
var icon = post.icon;
sectionModel.findByIdAndUpdate(id, { $set:{title:title,subTitle:subTitle,name: name,icon: icon}}, { new: true },function (err,results) {
if (!err) {
sectionModel.find().exec(function (err, results) {
//console.log(results)
sectionList=results;
});
res.redirect('/admin/section')
}
else {
var count=sectionModel.countDocuments().exec();
res.render('admin/index',{layout:'admin/layout',title:'Admin',user : req.user,results:results,count:count,ErrorMsg: name+" not save"});
}
})
}
}
module.exports.user = function (req, res) {
var page=req.query.page != undefined ? req.query.page-1 : 0;
if (req.method === 'GET') {
userModel.find().skip(page*10).limit(10).exec(function (err, results) {
if(err) return res.status(404).send(err);
userModel.countDocuments().exec(function (err, count) {
if(err) return res.status(404).send(err);
res.render('admin/table/user',{layout:'admin/layout',title:'Admin',user : req.user,results:results,count:count,page:page});
});
});
}
}
module.exports.userBlock = function (req, res) {
if (req.method === 'GET') {
var id=req.params.id;
console.log(id)
userModel.findById(id).exec(function (err, results) {
if(err) return res.status(404).send(err);
if(results.block){ results.set({block:false});}
else{ results.set({block:true});}
results.save(function (err, updatedTank) {
if (err) return handleError(err);
res.redirect("/admin/user")
});
});
}
}
module.exports.userDel = function (req, res) {
if (req.method === 'GET') {
var id=req.params.id;
console.log(id)
userModel.findByIdAndRemove(id).exec(function (err) {
if (err) return handleError(err);
res.redirect("/admin/user")
});
}
}
module.exports.post = function (req, res) {
var page=req.query.page != undefined ? req.query.page-1 : 0;
if (req.method === 'GET') {
postModel.find().populate('userObject').skip(page*10).limit(10).exec(function (err, results) {
if(err) return res.status(404).send(err);
postModel.countDocuments().exec(function (err, count) {
if(err) return res.status(404).send(err);
res.render('admin/table/post',{layout:'admin/layout',title:'Post',user : req.user,results:results,count:count,page:page});
});
});
}
}
module.exports.postDel=function (req,res) {
if (req.method === 'GET') {
var id=req.params.id;
console.log(id)
postModel.findByIdAndRemove(id).exec(function (err) {
if (err) return handleError(err);
res.redirect("/admin/post")
});
}
}
module.exports.reportPost = function (req, res) {
var page=req.query.page != undefined ? req.query.page-1 : 0;
if (req.method === 'GET') {
reportPostModel.find().populate('userObject').populate({path:'postObject', populate: { path: 'userObject' }}).skip(page*10).limit(10).exec(function (err, results) {
if(err) return res.status(404).send(err);
reportPostModel.countDocuments().exec(function (err, count) {
if(err) return res.status(404).send(err);
res.render('admin/table/reportPost',{layout:'admin/layout',title:'Post',user : req.user,results:results,count:count,page:page});
});
});
}
}
module.exports.reportPostCancel=function (req,res) {
if (req.method === 'GET') {
var id=req.params.id;
console.log(id)
reportPostModel.findByIdAndRemove(id).exec(function (err) {
if(err) return res.status(404).send(err);
res.redirect("/admin/reportPost")
});
}
}
module.exports.reportPostDel=function (req,res) {
if (req.method === 'GET') {
var id=req.params.id;
console.log(id)
reportPostModel.findByIdAndRemove(id).exec(function (err,reportPost) {
if(err) return res.status(404).send(err);
postModel.findByIdAndRemove(reportPost._id).exec(function (err) {
if(err) return res.status(404).send(err);
res.redirect("/admin/reportPost")
});
});
}
}
module.exports.tag = function (req, res) {
var page=req.query.page != undefined ? req.query.page-1 : 0;
if (req.method === 'GET') {
postModel.aggregate([
{ "$project": { "tag":1 }},
{ "$unwind": "$tag" },
{ "$group": { "_id": "$tag", "count": { "$sum": 1 } }},
{ "$sort" : { "count" : -1} },
{ "$skip" : page*10 },
{ "$limit" : 10 }
]).exec(function (err, results) {
postModel.distinct('tag').exec(function (err, count) {
if(err) return res.status(404).send(err);
res.render('admin/table/tag',{layout:'admin/layout',title:'Tag',user : req.user,results:results,count:count.length,page:page});
});
});
}
}
module.exports.navbarLink = function (req, res) {
if (req.method === 'GET') {
navbarLinkModel.find().exec(function (err, results) {
if(err) return res.status(404).send(err);
res.render('admin/table/navbarLink',{layout:'admin/layout',title:'Post',user : req.user,results:results});
});
}
else{
var post = req.body;
console.log(post);
var navbarLinkObject = new navbarLinkModel({
title:post.title,
url:post.url,
state:post.state=='on'?true:false
});
navbarLinkObject.save(function (err,results) {
if (!err) {
navbarLinkModel.find().exec(function (err, results) {
navbarLinkList=results;
});
res.redirect('/admin/navbarLink')
}
else {
res.render('admin/table/navbarLink',{layout:'layout/layout',title:'Admin',user : req.user,results:results,ErrorMsg: "Link not save"});
}
})
}
}
module.exports.navbarLinkDel=function (req,res) {
if (req.method === 'GET') {
var id=req.params.id;
console.log(id)
navbarLinkModel.findByIdAndRemove(id).exec(function (err) {
if(err) return res.status(404).send(err);
navbarLinkModel.find().exec(function (err, results) {
navbarLinkList=results;
});
res.redirect("/admin/navbarLink")
});
}
}
|
function ViewState() {
this.x0G = 0 // center of viewport in game coordinates
this.y0G = 0
this.VzoomG = 32 // zoom value in view units per game unit
this.targetx0G = 0
this.targety0G = 0
this.targetVzoomG = 32
this.vG = null
this.zcenterV = null
}
ViewState.prototype = {
think: function (dt) {
var f = Math.min(1, constants.viewtargetfactor * dt)
this.x0G += (this.targetx0G - this.x0G) * f
this.y0G += (this.targety0G - this.y0G) * f
if (this.targetVzoomG != this.VzoomG) {
var Vzoom0G = this.VzoomG
this.VzoomG = Math.exp(Math.log(this.VzoomG) * (1 - f) + Math.log(this.targetVzoomG) * f)
if (this.zcenterV) {
var GfV = 1 / Vzoom0G - 1 / this.VzoomG
this.targetx0G = this.x0G += GfV * this.zcenterV[0]
this.targety0G = this.y0G += GfV * this.zcenterV[1]
}
} else {
this.zcenterV = null
}
if (this.vV) {
this.snap(this.vV[0] * dt, this.vV[1] * dt)
var f = Math.exp(-constants.flydecelfactor * dt)
this.vV[0] *= f
this.vV[1] *= f
if (Math.abs(this.vV[0]) + Math.abs(this.vV[1]) < 1) this.vV = null
}
},
clampzoom: function () {
this.targetVzoomG = clamp(this.targetVzoomG, constants.minVzoomG, constants.maxVzoomG)
this.VzoomG = clamp(this.VzoomG, constants.minVzoomG, constants.maxVzoomG)
},
scootch: function (dxV, dyV, dz, zcenterV) {
if (dxV) this.targetx0G += dxV / this.VzoomG
if (dyV) this.targety0G += dyV / this.VzoomG
if (dz) {
this.targetVzoomG *= Math.exp(dz)
this.clampzoom()
this.zcenterV = zcenterV
}
},
snap: function (dxV, dyV, dz) {
if (dxV) this.x0G = this.targetx0G += dxV / this.VzoomG
if (dyV) this.y0G = this.targety0G += dyV / this.VzoomG
if (dz) {
this.VzoomG = this.targetVzoomG *= Math.exp(dz)
this.clampzoom()
}
},
target: function (pG) {
this.targetx0G = pG[0]
this.targety0G = pG[1]
},
fly: function (vV) {
this.vV = vV
},
GconvertD: function (pD) {
var pV = playpanel.VfromcenterD(pD)
return [this.x0G + pV[0] / this.VzoomG, this.y0G + pV[1] / this.VzoomG]
}
}
|
const express = require('express');
const router = express.Router();
// const galleryItems = require('../modules/gallery.data'); // No longer needed for stretch goals
const pool = require('../modules/pool.js');
// DO NOT MODIFY THIS FILE FOR BASE MODE
// POST Route // Stretch goal
router.post('/', (req, res) => {
const imageToSend = req.body; // request info recieved from client stored in variable
console.log('POSTing new photo: ', imageToSend);
const sqlText = `INSERT INTO gallery ("path", "description")
VALUES ($1, $2);`; // sanitary database query with pg
pool.query(sqlText, [imageToSend.path, imageToSend.description]) // id and initial likes are dealt with by DB
.then((response) => {
console.log("Added photo to the database", imageToSend);
res.sendStatus(200); //Yay!
}).catch((error) => {
console.log('Error in db post', error);
res.sendStatus(500); // Uh-oh.
});
});
// PUT Route
router.put('/like/:id', (req, res) => {
console.log(req.params);
const galleryId = req.params.id; // id of row to modify sent as param
let queryText = `UPDATE gallery SET "likes" = "likes" +1 WHERE "id" = $1;`; // db query, so sanitary,
pool.query(queryText, [galleryId]) // thank you, pool, for bringing 'pg' into the picture
.then((result) => {
console.log('Photo liked!', galleryId);
res.sendStatus(200); // looks like it worked!
}).catch((error) => {
console.log('Error in like', error);
res.sendStatus(500); // "somebody fix me!"
});
}); // END PUT Route
// GET Route
router.get('/', (req, res) => {
const sqlText = `SELECT * FROM gallery ORDER BY "id" ASC;`; // db query
pool.query(sqlText) // send through pg, via pool
.then((result) => {
console.log('got these from the database', result.rows); // see what we got in the log
res.send(result.rows); // format response into rows
}).catch((error) => {
console.log('Error in gettin gallery', error);
res.sendStatus(500); // It no-go
})
}); // END GET Route
module.exports = router;
|
function runTest()
{
FBTest.openNewTab(basePath + "search/2886/issue2886.html", function(win)
{
FBTest.openFirebug(function()
{
FBTest.enableScriptPanel(function(win)
{
var tests = new FBTest.TaskList();
tests.push(doSearch, "(!(accidental-regexp))", 8, false);
tests.push(doSearch, "keyword\\s+\\d+", 10, true);
tests.run(function()
{
FBTest.testDone();
});
});
});
});
}
function doSearch(callback, searchString, lineNo, useRegExp)
{
FBTest.progress("Search for " + searchString);
FBTest.setPref("searchUseRegularExpression", useRegExp);
// Execute search.
FBTest.searchInScriptPanel(searchString, function(line)
{
FBTest.compare(lineNo, line, searchString + " found on line: " +
line + ", expected: " + lineNo);
callback();
});
}
|
import kafka from 'kafka-node';
let connectionString = null;
export function getClient(clientId) {
return new kafka.Client(connectionString, clientId);
}
export function initMessages(connection_string) {
connectionString = connection_string;
}
|
var org3Settings = {
speed: 0.8,
minSpeed: 1.2,
fluctuation: (TAU/360) * 8,
rotationSpeed: 2,
small: 65,
large: 91,
breedRange: 400,
breedEnergy: 7,
breedProximity: 30,
feedRange: 260,
feedCap: 20,
feedProximity: 26,
color: "rgba(24,76,143,0.5)",
soundAttack: 0.1,
soundRelease: 3,
soundVolume: 0.2
};
//-------------------------------------------------------------------------------------------
// INITIALISE
//-------------------------------------------------------------------------------------------
function Organism3(x1, y1, x2, y2) {
this.settings = org3Settings;
// randomise position //
this.position = new Point(tombola.range(x1, x2), tombola.range(y1, y2));
this.lastPositions = [];
// randomise angle //
this.angle = tombola.rangeFloat(0, TAU);
this.angleDest = this.angle;
// randomise other properties //
this.size = tombola.rangeFloat(this.settings.small, this.settings.large);
this.speed = tombola.rangeFloat(this.settings.minSpeed, this.settings.speed);
this.energy = tombola.rangeFloat(7,8);
}
//-------------------------------------------------------------------------------------------
// UPDATE
//-------------------------------------------------------------------------------------------
Organism3.prototype.update = function() {
// ENERGY //
this.energy -= 0.0025;
if (this.energy <= 0) {
this.kill();
}
// MOVEMENT //
// Store a memory of previous positions //
this.lastPositions.push( this.position.clone() );
if (this.lastPositions.length > this.settings.tail) {
this.lastPositions.shift();
}
// Randomly increase or decrease rotation & speed //
this.angle = normaliseAngle(this.angle);
this.angleDest += tombola.rangeFloat(-this.settings.fluctuation, this.settings.fluctuation);
if ((this.angleDest - this.angle) > (TAU/2)) {
this.angleDest -= TAU;
}
if ((this.angleDest - this.angle) < -(TAU/2)) {
this.angleDest += TAU;
}
// smoothly transition to angle //
this.angle = lerp(this.angle, this.angleDest, this.settings.rotationSpeed);
this.speed += tombola.rangeFloat(-this.settings.fluctuation, this.settings.fluctuation);
// Cap the max speed so it doesn't get out of control //
this.speedCap();
// Update the position by adding the seed to it //
this.position.x += (this.speed * Math.cos(this.angle));
this.position.y += (this.speed * Math.sin(this.angle));
// Wrap around the screen boundaries //
screenWrap(this);
};
//-------------------------------------------------------------------------------------------
// DRAW
//-------------------------------------------------------------------------------------------
Organism3.prototype.draw = function() {
// set color //
ctx.globaAlpha = this.settings.alpha;
ctx.fillStyle = this.settings.color;
ctx.strokeStyle = this.settings.color;
// set scale //
ctx.lineWidth = 4 * scale;
var s = this.size;
// body //
ctx.save();
ctx.translate(this.position.x, this.position.y);
ctx.rotate(this.angle);
ctx.beginPath();
ctx.moveTo(s/4, 0);
ctx.lineTo(((s/4)*3), 0);
ctx.quadraticCurveTo(s, 0, s, s/4);
ctx.quadraticCurveTo(s, s/2, ((s/4)*3), s/2);
ctx.lineTo(s/4, s/2);
ctx.quadraticCurveTo(0, s/2, 0, s/4);
ctx.quadraticCurveTo(0, 0, s/4, 0);
ctx.stroke();
ctx.restore();
};
//-------------------------------------------------------------------------------------------
// KILL
//-------------------------------------------------------------------------------------------
Organism3.prototype.kill = function() {
removeFromArray(this, org3);
var area = 10 * scale;
generateOrganism3(2 || 0 || 0, this.position.x - area, this.position.y - area, this.position.x + area, this.position.y + area);
generateVisual(this.position, this.size);
};
//-------------------------------------------------------------------------------------------
// SPEED CAP
//-------------------------------------------------------------------------------------------
Organism3.prototype.speedCap = function() {
this.speed = Math.min(this.speed,this.settings.speed);
this.speed = Math.max(this.speed,this.settings.minSpeed);
};
//-------------------------------------------------------------------------------------------
// WRAP
//-------------------------------------------------------------------------------------------
Organism3.prototype.wrap = function() {
this.lastPositions = [];
};
|
mainApp.lazy.controller('setPartnerController', ['$rootScope', '$scope', 'invokeServerService', 'arrayHelperFactory', 'messageFactory', 'fileUploaderService',
function ($rootScope, $scope, invokeServerService, arrayHelperFactory, messageFactory, fileUploaderService) {
$rootScope.pageTitle = 'مدیریت نماینده ها';
setup_file_input();
$scope.province = {};
$scope.city = {};
$scope.myPromise = invokeServerService.Post('/Base/GetProvince', {}).success(function (result) {
$scope.provinceDS = result;
$scope.partnerProvinceDS = result;
});
$scope.changeDropDownProvince = function (provinceId) {
invokeServerService.Post('/Base/GetCity', { provinceId: provinceId }).success(function (result) {
$scope.cityDS = result;
});
}
$scope.changeDropDownPartnerProvince = function (provinceId) {
invokeServerService.Post('/Base/GetCity', { provinceId: provinceId }).success(function (result) {
$scope.partnerCityDS = result;
});
}
$scope.changeDropDowncity = function (cityId) {
$scope.regionDS = null;
if (cityId == 159) {
invokeServerService.Post('/Base/GetRegion', { cityId: cityId }).success(function (result) {
$scope.regionDS = result;
});
}
}
$scope.newPartner = function () {
$scope.partner = null;
}
//$scope.uploadFile = function () {
//
// if ($scope.fileAttachment.size / 1024 > 200) {
// messageFactory.showAlert('حجم فایل نباید بیشتر از 1 مگابایت باشد', 'warning');
// }
// else {
// $scope.fileAttachment.partner = $scope.partner;
// $scope.myPromise = fileUploaderService.uploadFileToUrl($scope.fileAttachment, '/Partner/SavePartner')
// .then(function (result) {
// if (result.Success) {
// messageFactory.showAlert(result.Message, 'success');
// }
// else {
// messageFactory.showAlert(result.Message, 'danger');
// }
// },
// function () {
// });
// }
//};
$scope.save = function () {
debugger;
if (false/*$scope.fileAttachment.attachment.size / 1024 > 200*/) {
messageFactory.showAlert('حجم فایل نباید بیشتر از 200 کیلوبایت باشد', 'warning');
}
else {
invokeServerService.Post('/Partner/SavePartner', { fileAttachment: '', partner: $scope.partner }).success(function (result) {
if (result.Success) {
messageFactory.showAlert(result.Message, 'success');
}
else {
messageFactory.showAlert(result.Message, 'danger');
}
});
}
}
$scope.search = function () {
gridDataSource.read();
}
var gridDataSource = new kendo.data.DataSource({
transport: {
read: "/Partner/GetAgents",
parameterMap: function (data, type) {
if (type == "read") {
return {
provinceId: $scope.province.Id,
cityId: $scope.city.Id,
pageSize: data.pageSize,
page: data.page
}
}
}
},
schema: {
total: function (response) {
return response.Total;
},
data: function (response) {
return response.data;
}
},
pageSize: 5,
serverPaging: true,
serverSorting: true
});
$scope.mainGridOptions = {
dataSource: gridDataSource,
autoBind: true,
sortable: true,
pageable: true,
columns: [
{ field: "Id", hidden: true },
{
field: "Title",
title: "نماینده",
width: "60px", attributes: {
style: "text-align: right; font-size: 11px"
},
headerAttributes: {
style: "font-size: 11px; "
}
},
{
field: "ManagerName",
title: "مدیر",
width: "40px", attributes: {
style: "text-align: right; font-size: 11px"
},
headerAttributes: {
style: "font-size: 11px; "
}
},
{
field: "Phone",
title: "تلفن",
width: "40px", attributes: {
style: "text-align: right; font-size: 11px"
},
headerAttributes: {
style: "font-size: 11px; "
}
},
{
field: "Mobile",
title: "همراه",
width: "40px", attributes: {
style: "text-align: right; font-size: 11px"
},
headerAttributes: {
style: "font-size: 11px; "
}
},
{
field: "Address",
title: "آدرس",
width: "100px", attributes: {
style: "text-align: right; font-size: 11px"
},
headerAttributes: {
style: "font-size: 11px; "
}
},
{
command: {
text: "ویرایش", click: function (e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$scope.changeDropDownPartnerProvince(dataItem.Province.Id);
$scope.partner = dataItem;
$("#navPartners").removeClass("active");
$("#tabPartners").removeClass("active");
$("#navNewEdit").addClass("active");
$("#tabNewEdit").tab('show');
$scope.$apply();
}
}, title: " ", width: "30px", attributes: {
style: "text-align: right; font-size: 11px"
}
}
]
};
}]);
|
/**
* Represents the rank of a card.
* @author Rajitha Wannigama
*/
var Rank = {
/**
* @type {String}
* @private
*/
value: undefined,
/**
* Create a new rank. Must use this function over Object.create(Rank).
* @constructor
* @this {Rank}
* @param {String|Number} value '2','3','4','5','6','7','8','9','0','j','q','k','a','w','0'. Case does
* not matter.
* @returns {Rank}
* @throws {Error}
*/
create: function(value) {
// The ranks in a card deck. 'W' stands for Joker.
var ranks = Deck.ranks;
// The cards.Rank object.
var obj;
// If its a number, get the string version. If its a string, make sure its
// lower case.
if ( typeof value == 'number' ) {
value = '' + value;
}
else if ( typeof value == 'string' ) {
value = value.toLowerCase();
}
else {
// Any other type is not accepted.
throw new Error('cards.Rank.create: Invalid value for a rank. value = ' + value);
}
if ( ranks.indexOf(value) == -1 ) {
throw new Error('cards.Rank.create: Invalid value for a rank. value = ' + value);
}
obj = Object.create(this);
obj.value = value;
return obj;
},
/**
* Get the HTML code for this rank.
* @param {Object} [options]
* @returns {String|undefined} An undefined value will only be returned if this object
* was created without using the cards.Rank.create() function.
*/
html: function(options) {
return (this.value == '0') ? '10' : this.value.toUpperCase();
}
};
|
$('.sidebar-menu-item').on('click', function() {
for(let i=0; i < $('.sidebar-dropdown-container').length; i++){
if($(this).data('toggler') == $('.sidebar-dropdown-container').eq(i).data('toggle')){
if($(this).data('toggled') == false){
$(this).data('toggled', true)
$('.sidebar-dropdown-container').eq(i).css('display', 'block')
}else{
$(this).data('toggled', false)
$('.sidebar-dropdown-container').eq(i).css('display', 'none')
}
}
}
})
const check_active = () => {
for(let i=0; i < $('.sidebar-dropdown-container-item').length; i++){
if($('.sidebar-dropdown-container-item').eq(i).hasClass('active')){
for(let j=0; j < $('.sidebar-menu-item').length; j++){
if(
$('.sidebar-dropdown-container-item').eq(i).parents('.sidebar-dropdown-container').data('toggle') ==
$('.sidebar-menu-item').eq(j).data('toggler')
){
$('.sidebar-menu-item').eq(j).trigger('click')
}
}
}
}
}
check_active()
|
/**
* clapper.js - HumanInput Clapper Plugin: Adds support detecting clap events like "the clapper" (classic)
* Copyright (c) 2016, Dan McDougall
* @link https://github.com/liftoff/HumanInput/src/clapper.js
* @license Apache-2.0
*/
import HumanInput from './humaninput';
// Add ourselves to the default listen events since we won't start listening for claps unless explicitly told to do so (won't be used otherwise)
HumanInput.defaultListenEvents.push('clapper');
// Setup getUserMedia
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
const AudioContext = window.AudioContext || window.webkitAudioContext;
const throttleMS = 60; // Only process audio once every throttleMS milliseconds
const historyLength = 50; // How many samples to keep in the history buffer (50 is about 3 seconds worth)
const sum = (arr) => {
return arr.reduce((a, b) => { return a + b; });
};
const findPeaks = (arr) => {
// returns the indexes of all the peaks in *arr*
var indexes = [];
for (let i = 1; i < arr.length - 1; ++i) {
if (arr[i-1] < arr[i] && arr[i] > arr[i+1]) {
indexes.push(i);
}
}
return indexes;
};
export class ClapperPlugin {
constructor(HI) { // HI == current instance of HumanInput
this.HI = HI;
this.l = HI.l;
this.exports = {};
this.history = [];
this.rollingAvg = [];
this.calcHistoryAverage = this.calcHistoryAverage.bind(this);
this.startClapper = this.startClapper.bind(this);
this.stopClapper = this.stopClapper.bind(this);
}
init(HI) {
var state = HI.state;
this.log = new HI.Logger(HI.settings.logLevel || 'INFO', '[HI Clapper]');
HI.settings.autostartClapper = HI.settings.autostartClapper || false; // Don't autostart by default
HI.settings.clapThreshold = HI.settings.clapThreshold || 130;
HI.settings.autotoggleClapper = HI.settings.autotoggleClapper || true; // Should we stop automatically on page:hidden?
if (HI.settings.listenEvents.indexOf('clapper') != -1) {
if (AudioContext) {
if (HI.settings.autostartClapper) {
this.startClapper();
}
if (HI.settings.autotoggleClapper) {
HI.on('document:hidden', () => {
if (this._started) {
this.stopClapper();
}
});
HI.on('document:visible', () => {
if (!this._started && HI.settings.autostartClapper) {
this.startClapper();
}
});
}
} else { // Disable the clapper functions to ensure no weirdness with document:hidden
this.startClapper = HI.noop;
this.stopClapper = HI.noop;
}
}
// Exports (these will be applied to the current instance of HumanInput)
this.exports.startClapper = this.startClapper;
this.exports.stopClapper = this.stopClapper;
return this;
}
calcHistoryAverage() {
// Updates this.rollingAvg with the latest data from this.history so that each item in the array reflects the average amplitude for that chunk of the frequency spectrum
var i, j, temp = 0;
for (i=0; i < this.analyser.frequencyBinCount; i++) {
if (this.history[i]) {
for (j=0; j < this.history.length; j++) {
temp += this.history[j][i];
}
this.rollingAvg[i] = temp/this.history.length;
temp = 0;
}
}
}
startClapper() {
var handleStream = (stream) => {
var previous, detectedClap, detectedDoubleClap;
this.stream = stream;
this.scriptProcessor.connect(this.context.destination);
this.analyser.smoothingTimeConstant = 0.4;
this.analyser.fftSize = 128;
this.streamSource = this.context.createMediaStreamSource(stream);
this.streamSource.connect(this.analyser);
this.analyser.connect(this.scriptProcessor);
this.scriptProcessor.onaudioprocess = () => {
var elapsed, elapsedSinceClap, elapsedSinceDoubleClap, event, peaks, highestPeak, highestPeakIndex, amplitudeIncrease, magicRatio1, magicRatio2,
now = Date.now();
if (!previous) {
previous = now;
detectedClap = now;
}
elapsed = now - previous;
elapsedSinceClap = now - detectedClap;
elapsedSinceDoubleClap = now - detectedDoubleClap;
if (elapsed > throttleMS) {
this.freqData = new Uint8Array(this.analyser.frequencyBinCount);
this.analyser.getByteFrequencyData(this.freqData);
peaks = findPeaks(this.freqData);
highestPeakIndex = this.freqData.indexOf(Math.max.apply(null, this.freqData));
highestPeak = this.freqData[highestPeakIndex];
// Measure the amplitude increase against the rolling average not the previous data set (which can include ramping-up data which messes up our calculations)
amplitudeIncrease = this.freqData[highestPeakIndex] - this.rollingAvg[highestPeakIndex];
if (elapsedSinceClap >= (throttleMS * 4)) {
// Highest peak is right near the beginning of the spectrum for (most) claps:
if (highestPeakIndex < 8 && amplitudeIncrease > this.HI.settings.clapThreshold) {
// Sudden large volume change. Could be a clap...
magicRatio1 = sum(this.freqData.slice(0, 10))/sum(this.freqData.slice(10, 20)); // Check the magic ratio
magicRatio2 = sum(this.freqData.slice(0, 3))/sum(this.freqData.slice(3, 6)); // Check the 2nd magic ratio
// The peak check below is to prevent accidentally capturing computer-generated sounds which usually have a nice solid curve (few peaks if any)
if (magicRatio1 < 1.8 && magicRatio2 < 1.4 && peaks.length > 2) {
// Now we're clapping!
event = 'clap';
if (elapsedSinceClap < (throttleMS * 8)) {
event = 'doubleclap';
detectedDoubleClap = now;
if (elapsedSinceDoubleClap < (throttleMS * 12)) {
event = 'applause';
}
}
this.HI._addDown(event);
this.HI._handleDownEvents();
this.HI._handleSeqEvents();
this.HI._removeDown(event);
detectedClap = now;
}
}
}
previous = now;
// Only add this data set to this history if it wasn't a clap (so it doesn't poison our averages)
if (detectedClap != now) {
this.history.push(this.freqData);
if (this.history.length > historyLength) {
this.history.shift();
}
this.calcHistoryAverage();
}
}
}
};
this.context = new AudioContext();
this.scriptProcessor = this.context.createScriptProcessor(1024, 1, 1);
this.analyser = this.context.createAnalyser();
this.freqData = new Uint8Array(this.analyser.frequencyBinCount);
this.log.debug(this.l('Starting clap detection'));
this._started = true;
navigator.mediaDevices.getUserMedia({ audio: true }).then(handleStream, (e) => {
this.log.error(this.l('Could not get audio stream'), e);
});
}
stopClapper() {
this.log.debug(this.l('Stopping clap detection'));
this.stream.getAudioTracks().forEach((track) => {
track.stop();
});
this.stream.getVideoTracks().forEach((track) => {
track.stop();
});
this.streamSource.disconnect(this.analyser);
this.analyser.disconnect(this.scriptProcessor);
this.scriptProcessor.disconnect(this.context.destination);
this._started = false;
}
}
HumanInput.plugins.push(ClapperPlugin);
|
import React from 'react';
import {
BrowserRouter as Router,
// Switch,
// Route,
// Link
} from 'react-router-dom';
import './App.scss';
import Login from '../Login';
import IfSession from '../IfSession';
// import Variables from '../Variables';
import Period from '../Period';
// import AllData from '../AllData';
export default () => (
<>
<header>
<Login />
</header>
<IfSession>
<Router>
{/* <AllData /> */}
<Period />
{/* <Link to="/">Home</Link>
<Link to="/about">About</Link>
<Switch>
<Route exact path="/">
Home
</Route>
<Route path="/about">
About
</Route>
</Switch>
<Grid /> */}
</Router>
</IfSession>
{/* <Variables /> */}
</>
);
|
'use strict';
require('./config');
require('./util.js');
/*
|--------------------------------------------------------------------------
| Application Is Ready
|--------------------------------------------------------------------------
|
| When all the dependencies of the page are loaded and executed,
| the application automatically call this function. You can consider it as
| a replacer for jQuery ready function - "$( document ).ready()".
|
*/
app.ready(function() {
});
|
import React from 'react'
import ReactDOM from 'react-dom'
//使用者資訊
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">{props.user.name}</div>
</div>
);
}
//用戶圖片
function Avatar(props) {
return (
<img
className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name}
/>
);
}
//自動偵測日期
function formatDate(date) {
return date.toLocaleDateString();
}
//資訊
const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'https://placekitten.com/g/64/64',
},
};
export default class App extends React.Component {
render() {
return (
<div>
<UserInfo user={this.props.author} />
<div className="Comment-text">{this.props.text}</div>
<div className="Comment-date">
{formatDate(this.props.date)}
</div>
</div>
);
}
}
ReactDOM.render(
<App
date={comment.date}
text={comment.text}
author={comment.author}
/>,
document.getElementById('root')
);
|
const apiBaseUrl = "http://localhost:8088";
const API = {
getOnePOI(endpoint, id) {
return fetch(`${apiBaseUrl}/${endpoint}/${id}`).then(res => res.json());
},
getAllPOI(endpoint) {
return fetch(`${apiBaseUrl}/${endpoint}`).then(res => res.json());
},
postOnePOI(endpoint, interest) {
return fetch(`${apiBaseUrl}/${endpoint}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(interest)
});
},
deletePOI(endpoint, interestID) {
return fetch(`${apiBaseUrl}/${endpoint}/${interestID}`, {
method: "DELETE"
}).then(res => res.json());
},
patchPOI(endpoint, interestID, interest) {
return fetch(`${apiBaseUrl}/${endpoint}/${interestID}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(interest)
});
}
};
export default API;
|
const router = require('express').Router();
const uuidv1 = require('uuid/v1');
const axios = require('axios');
const moment = require('moment');
const connection = require('../init/setupMySql');
const notAuthMiddleware = require('../utils/notAuthMiddleware');
const scheduler = require('../scheduling/scheduler');
// get all rooms
router.get('/rooms', notAuthMiddleware, (req, res) => {
const sql = 'SELECT * FROM Rooms WHERE status="A"';
connection.query(sql, (err, result) => {
if (err) {
return result.status(500).send({ message: 'Internal server Error.' });
}
res.send(result);
});
});
// add a new room, to the rooms table.
router.post('/room', notAuthMiddleware, async (req, res) => {
const room = req.body;
let sql = 'INSERT INTO Rooms(name, seats, status, email) VALUES (?, ?, ?, ?)';
let sqlcmd = connection.format(sql, [room.name, room.seats, 'A', room.email]);
connection.query(sqlcmd, (err, addedRoom) => {
if (err) {
return res.status(500).send({ message: 'Internal server Error.' });
}
sql = 'SELECT * FROM Rooms WHERE id=?';
sqlcmd = connection.format(sql, [addedRoom.insertId]);
connection.query(sqlcmd, (err, savedRoom) => {
if (err) {
return res.status(500).send({ message: 'Internal server Error.' });
}
// savedRoom is the room that has just been added which consists of id, name, seats, and status attributes
res.send(savedRoom[0]);
});
});
});
// update the status of a room to disabled, in the rooms table
router.put('/room/:id', notAuthMiddleware, (req, res) => {
const { id } = req.params;
const sql = "UPDATE Rooms SET Status = 'D' WHERE id = ?";
const sqlcmd = connection.format(sql, [id]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server Error.' });
}
res.send(result);
});
});
// get all candidates
router.get('/candidates', notAuthMiddleware, async (req, res) => {
const sql = "SELECT * FROM Candidate WHERE status <> 'D'";
await connection.query(sql, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server Error.' });
}
res.send(result);
});
});
/**
* Get a candidate's firstname, for the candidate availabilty page.
*
* This should be the only method that can be used without authentication.
*/
router.get('/candidate/name/:uuid', (req, res) => {
const { uuid } = req.params;
const sql = 'SELECT firstName FROM Candidate WHERE uuid = ?';
const sqlcmd = connection.format(sql, [uuid]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server Error.' });
}
if (result.length === 0) {
return res.status(204).send({ message: 'No candidate' });
}
// Just send the UUID and the first name
return res.send([{ uuid, firstName: result[0].firstName }]);
});
});
// get a specific candidate
router.get('/candidate/:uuid', (req, res) => {
const { uuid } = req.params;
const sql = 'SELECT * FROM Candidate WHERE uuid = ?';
const sqlcmd = connection.format(sql, [uuid]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server error.' });
}
res.send(result);
});
});
// add a new user in either the candidates table or interview table based on the selected type
router.post('/newcandidate', notAuthMiddleware, (req, res) => {
try {
const user = req.body;
const status = 'A';
const uuid = uuidv1();
const sql = 'INSERT INTO Candidate(firstName, lastName, email, phone, status, uuid, submittedAvailability) VALUES (?, ?, ?, ?, ?, ?, "F")';
const sqlcmd = connection.format(sql, [user.firstName, user.lastName, user.email, user.phone, status, uuid]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
const addedUser = { ...user, id: result.insertId };
res.send(addedUser);
});
} catch (error) {
return res.status(error.statusCode).send({ message: error.message });
}
});
// edit the administrator or candidate user information
router.put('/edituser', notAuthMiddleware, (req, res) => {
const user = req.body;
const type = user.role;
let sql = '';
switch (type) {
case 'candidate':
sql = 'UPDATE Candidate SET firstName = ?, lastName = ?, email = ?, phone = ? WHERE id = ?';
break;
case 'administrator':
sql = 'UPDATE AdminUsers SET firstName = ?, lastName = ?, email = ?, phone = ? WHERE id = ?';
break;
default: return;
}
let sqlcmd = connection.format(sql, [user.firstName, user.lastName, user.email, user.phone, user.id]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return result.status(500).send({ message: 'Internal server Error.' });
}
switch (type) {
case 'candidate':
sql = 'SELECT * FROM Candidate WHERE id = ?';
break;
case 'administrator':
sql = 'SELECT * FROM AdminUsers WHERE id = ?';
break;
default: return;
}
sqlcmd = connection.format(sql, [user.id]);
connection.query(sqlcmd, (err, updatedUser) => {
if (err) {
return res.status(500).send({ message: 'Internal server Error.' });
}
res.send(updatedUser[0]);
});
});
});
// update the status of a candidate to disabled, in the candidate table
router.put('/candidate/delete/:id', notAuthMiddleware, (req, res) => {
const { id } = req.params;
const sql = "UPDATE Candidate SET status = 'D' WHERE id = ?";
const sqlcmd = connection.format(sql, [id]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server Error.' });
}
res.send(result);
});
});
router.post('/sendEmail', notAuthMiddleware, (req, res) => {
const { firstName, email } = req.body;
const sqlcmd = connection.format("SELECT uuid from Candidate WHERE Email = ? AND status = 'A'", [email]);
connection.query(sqlcmd, async (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server Error.' });
}
const { uuid } = result[0];
// get email template config
const sqlcmd = 'SELECT * FROM EmailConfig';
connection.query(sqlcmd, async (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
const { subject, body, signature } = result[0];
try {
// const subject = 'Availability';
const content = `Hi ${firstName},\n\nPlease fill out your availability by going here: https://optimize-prime.herokuapp.com/candidate?key=${uuid}\n\n${body}\n\n${signature}`;
const response = await axios({
method: 'post',
url: 'https://graph.microsoft.com/v1.0/me/sendMail',
headers: {
Authorization: `Bearer ${req.user.accessToken}`,
},
data: {
message: {
subject,
body: {
contentType: 'text',
content,
},
toRecipients: [
{
emailAddress: {
address: email,
},
},
],
},
},
});
res.send(response.data);
} catch (error) {
res.status(500).send({ message: 'Internal server Error.' });
}
});
});
});
router.post('/availability', (req, res) => {
try {
const { availability, uuid } = req.body;
const sqlSelect = 'SELECT * FROM Candidate WHERE uuid = ?';
const sqlSelectcmd = connection.format(sqlSelect, [uuid]);
let candidateId;
connection.query(sqlSelectcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
candidateId = result[0].id;
let sql = 'INSERT INTO candidateavailability(candidateId, startTime, endTime) VALUES ?';
const values = [availability.map((time) => [candidateId, time.startTime, time.endTime])];
let sqlcmd = connection.format(sql, values);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
sql = "UPDATE Candidate SET submittedAvailability = 'T' WHERE id = ?";
sqlcmd = connection.format(sql, [candidateId]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
});
res.send(result);
});
});
} catch (error) {
res.status(error.statusCode).send({ message: error.message });
}
});
router.post('/allmeetings', notAuthMiddleware, async (req, res) => {
const { candidate, interviews } = req.body;
const result = await scheduler.findTimes(interviews, candidate, req.user.accessToken);
res.send(result);
});
// find all the possible meeting times, given the following constraints/information:
// attendess, timeConstraints, meetingDuration, locationConstraints
router.post('/meeting', notAuthMiddleware, async (req, res) => {
const {
candidate, meetingDuration, required, optional,
} = req.body;
const sql = "SELECT * FROM Candidate c INNER JOIN CandidateAvailability a ON c.id = a.candidateID WHERE c.email = ? AND c.status = 'A' ORDER BY a.id DESC";
const getCandidateAvailabilityCmd = connection.format(sql, [candidate]);
connection.query(getCandidateAvailabilityCmd, async (candidateAvailabilityError, candidateAvailability) => {
if (candidateAvailabilityError) {
res.status(500).send(candidateAvailabilityError);
}
if (candidateAvailability.length === 0) {
res.send('No candidate availability found');
} else {
try {
const timeZone = 'Pacific Standard Time';
const timeConstraint = {
activityDomain: 'work',
timeSlots: candidateAvailability.map((time) => ({
start: {
dateTime: time.startTime,
timeZone,
},
end: {
dateTime: time.endTime,
timeZone,
},
})),
};
const requiredAttendees = required.map((interviewer) => ({
type: 'required',
emailAddress: {
address: interviewer,
},
}));
const optionalAttendees = optional.map((interviewer) => ({
type: 'optional',
emailAddress: {
address: interviewer,
},
}));
const attendees = requiredAttendees.concat(optionalAttendees);
const getRoomsCmd = 'SELECT * FROM Rooms WHERE status="A"';
connection.query(getRoomsCmd, async (availableRoomsError, availableRooms) => {
if (availableRoomsError) {
res.status(500).send(availableRoomsError);
}
let locations = [{}];
if (availableRooms.length > 0) {
locations = availableRooms.map((room) => ({
displayName: room.name,
locationEmailAddress: room.email,
}));
}
const possibleMeetings = [];
// Need to loop through each availability block because if the duration of time
// constraint blocks is equal to the specified meeting duration, only the earliest
// meeting suggestion will be returned (i.e. not the full set of solution)
const meetingSuggestionPromises = timeConstraint.timeSlots.map(async (block) => {
const formattedTimeBlock = {
activityDomain: 'work',
timeSlots: [
{
start: block.start,
end: block.end,
},
],
};
const data = {
attendees,
timeConstraint: formattedTimeBlock,
maxCandidates: 30,
meetingDuration,
locationConstraint: {
isRequired: 'true',
suggestLocation: 'false',
locations,
},
};
const response = await axios({
method: 'post',
url: 'https://graph.microsoft.com/v1.0/me/findmeetingtimes',
headers: {
Authorization: `Bearer ${req.user.accessToken}`,
Prefer: `outlook.timezone="${timeZone}"`,
},
data,
});
const meetingTimeSuggestions = (response.data && response.data.meetingTimeSuggestions) || [];
if (meetingTimeSuggestions.length > 0) {
meetingTimeSuggestions.forEach((meeting) => {
meeting.locations.forEach((room) => {
possibleMeetings.push({
start: meeting.meetingTimeSlot.start,
end: meeting.meetingTimeSlot.end,
room,
interviewers: meeting.attendeeAvailability.filter((attendee) => attendee.availability === 'free'),
});
});
});
}
});
await Promise.all(meetingSuggestionPromises);
res.send(possibleMeetings.sort((a, b) => new Date(a.start.dateTime) - new Date(b.start.dateTime)));
});
} catch (error) {
res.status(error.statusCode).send({ message: error.message });
}
}
});
});
router.post('/event', notAuthMiddleware, async (req, res) => {
try {
const {
candidate, date, required, optional, room,
} = req.body;
const subject = `Interview with ${candidate.firstName} ${candidate.lastName}`;
const content = 'Please confirm if you are available during this time.';
const timeZone = 'Pacific Standard Time';
// create candidate as an attendee
const candidateAttendee = [
{
type: 'required',
emailAddress: {
address: candidate.email,
},
},
];
// required attendees
const requiredAttendees = required.map((interviewer) => ({
type: 'required',
emailAddress: {
address: interviewer,
},
}));
// optional attendees
const optionalAttendees = optional.map((interviewer) => ({
type: 'optional',
emailAddress: {
address: interviewer,
},
}));
const roomAttendee = {
type: 'required',
emailAddress: {
address: room.email,
},
};
// combine all the attendees aswell as the candidate
const interviewerAttendees = requiredAttendees.concat(optionalAttendees);
const attendees = interviewerAttendees.concat(candidateAttendee).concat(roomAttendee);
const response = await axios({
method: 'post',
url: 'https://graph.microsoft.com/v1.0/me/events',
headers: {
Authorization: `Bearer ${req.user.accessToken}`,
Prefer: `outlook.timezone="${timeZone}"`,
},
data: {
subject,
body: {
contentType: 'HTML',
content,
},
start: date.startTime,
end: date.endTime,
location: {
displayName: room.name,
locationEmailAddress: room.email,
},
attendees,
},
});
// insert the scheduled interview in the candidate table
let sql = "SELECT * FROM Rooms WHERE name = ? AND status = 'A'";
let sqlcmd = connection.format(sql, [room.name]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server error.' });
}
// get roomId
const newRoomID = result[0].id;
const outlookID = response.data.id;
sql = 'INSERT INTO ScheduledInterview(CandidateID, StartTime, EndTime, RoomID, OutlookID) VALUES (?, STR_TO_DATE(?, ?), STR_TO_DATE(?, ?), ?, ?)';
sqlcmd = connection.format(sql, [candidate.id, moment(date.startTime.dateTime).format(), '%Y-%m-%dT%H:%i:%s-08:00', moment(date.endTime.dateTime).format(), '%Y-%m-%dT%H:%i:%s-08:00', newRoomID, outlookID]);
connection.query(sqlcmd, (err, scheduledInterview) => {
if (err) {
return res.status(500).send({ message: 'Internal server error.' });
}
sql = 'SELECT s.id, startTime, endTime, c.id AS candidateId, firstName, lastName, r.id AS roomId, name, seats FROM Candidate c INNER JOIN ScheduledInterview s ON c.id = s.candidateId INNER JOIN Rooms r ON s.roomId = r.id WHERE s.id = ?';
sqlcmd = connection.format(sql, [scheduledInterview.insertId]);
connection.query(sqlcmd, (err, newScheduledInterview) => {
if (err) {
return res.status(500).send({ message: 'Internal server error.' });
}
const {
candidateId,
firstName,
lastName,
roomId,
name,
seats,
...interviewDetails
} = newScheduledInterview[0];
const formattedInterview = {
...interviewDetails,
candidate: {
id: candidateId,
firstName,
lastName,
},
room: {
id: roomId,
name,
seats,
},
};
res.send(formattedInterview);
sql = "UPDATE Candidate SET submittedAvailability = 'F' WHERE id = ?";
sqlcmd = connection.format(sql, [candidate.id]);
connection.query(sqlcmd, (err, newScheduledInterview) => {
if (err) {
return res.status(500).send({ message: 'Internal server error.' });
}
});
sql = 'DELETE FROM Candidateavailability WHERE candidateId = ?';
sqlcmd = connection.format(sql, [candidate.id]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
});
});
});
});
} catch (error) {
res.status(error.response.status).send(error.message);
}
});
router.delete('/events/:id', notAuthMiddleware, async (req, res) => {
const { id } = req.params;
try {
const getID = 'SELECT outlookID FROM ScheduledInterview WHERE id=?';
const getIDcmd = connection.format(getID, id);
connection.query(getIDcmd, async (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
const timeZone = 'Pacific Standard Time';
try {
const response = await axios.delete(
`https://graph.microsoft.com/v1.0/me/events/${result[0].outlookID}`,
{
headers: {
Authorization: `Bearer ${req.user.accessToken}`,
Prefer: `outlook.timezone="${timeZone}"`,
},
}
);
const hasUpcomingEvents = 'SELECT * FROM ScheduledInterview s1, (SELECT candidateID FROM ScheduledInterview WHERE id=?) s2 WHERE s1.candidateID=s2.candidateID';
const hasUpcomingEventscmd = connection.format(hasUpcomingEvents, id);
connection.query(hasUpcomingEventscmd, async (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
if (result.length === 0) {
const updateStatus = "UPDATE Candidate SET submittedAvailability='F' WHERE id IN (SELECT candidateID FROM ScheduledInterview WHERE id=?)";
const updateStatuscmd = connection.format(updateStatus, id);
await connection.query(updateStatuscmd);
}
const deleteEvent = 'DELETE FROM ScheduledInterview WHERE id=?';
const deleteEventcmd = connection.format(deleteEvent, id);
connection.query(deleteEventcmd, async (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
res.status(response.status).send({ message: response.statusText });
});
});
} catch (error) {
res.status(error.statusCode).send({ message: error.message });
}
});
} catch (error) {
res.status(error.statusCode).send({ message: error.message });
}
});
router.get('/administrators', notAuthMiddleware, async (req, res) => {
try {
const sql = 'SELECT * FROM AdminUsers';
const sqlcmd = connection.format(sql);
connection.query(sqlcmd, async (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
res.send(result);
});
} catch (error) {
res.status(error.statusCode).send({ message: error.message });
}
});
// ************* Get meeting rooms from outlook *************** //
router.get('/outlook/rooms', notAuthMiddleware, async (req, res) => {
const response = await axios({
method: 'get',
url: 'https://graph.microsoft.com/beta/me/findRooms',
headers: {
Authorization: `Bearer ${req.user.accessToken}`,
},
});
res.send(response.data && response.data.value);
});
router.get('/outlook/users', notAuthMiddleware, async (req, res) => {
try {
const response = await axios({
method: 'get',
url: 'https://graph.microsoft.com/v1.0/users',
headers: {
Authorization: `Bearer ${req.user.accessToken}`,
},
});
res.send(
response.data.value
.filter((user) => user.givenName !== null)
.map((user) => ({
firstName: user.givenName,
lastName: user.surname,
email: user.mail,
})),
);
} catch (err) {
res.status(err.statusCode).send({ message: err.message });
}
});
// **************************** Get all scheduled interviews ************************************ //
// get a list of interviews
router.get('/interviews', notAuthMiddleware, (req, res) => {
const currDate = new Date();
const sql = 'SELECT s.id, startTime, endTime, c.id AS candidateId, firstName, lastName, r.id AS roomId, name, seats FROM Candidate c INNER JOIN ScheduledInterview s ON c.id = s.candidateId INNER JOIN Rooms r ON s.roomId = r.id WHERE startTime >= ? ORDER BY startTime';
const sqlcmd = connection.format(sql, [currDate]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal Server error' });
}
const formattedInterviews = result.map((interview) => {
const {
candidateId,
firstName,
lastName,
roomId,
name,
seats,
...interviewDetails
} = interview;
return {
...interviewDetails,
candidate: {
id: candidateId,
firstName,
lastName,
},
room: {
id: roomId,
name,
seats,
},
};
});
res.send(formattedInterviews);
});
});
// ************************** Admin endpoints *********************** //
router.post('/newadministrator', notAuthMiddleware, async (req, res) => {
try {
// check if user is not part of the org.
const user = req.body;
const response = await axios({
url: `https://graph.microsoft.com/v1.0/users?$filter=startswith(mail,'${user.email}')`,
headers: {
Authorization: req.user.accessToken,
},
});
if (response.data.value.length === 0) {
return res.status(400).send({ message: 'You have tried to create an admin that is not part of the organization.' });
}
const sqlQuery = 'SELECT email FROM adminUsers WHERE email= ?';
const sqlcmd = connection.format(sqlQuery, [user.email]);
await connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server error' });
}
if (result.length > 0) {
return res.status(400).send({ message: 'User is already an admin' });
}
const sql = 'INSERT INTO adminUsers(firstName, lastName, email, phone) VALUES(?, ?, ?, ?)';
const sqlcmd2 = connection.format(sql, [user.firstName, user.lastName, user.email, user.phone]);
connection.query(sqlcmd2, (error, r) => {
if (error) {
return res.status(500).send({ message: 'Internal Server error.' });
}
const addedUser = { ...user, id: r.insertId };
return res.send(addedUser);
});
});
} catch (error) {
res.status(error.statusCode).send({ message: error.message });
}
});
router.put('/administrator/delete/:id', notAuthMiddleware, async (req, res) => {
const { id } = req.params;
const sql = 'DELETE FROM adminUsers WHERE id = ?';
const sqlcmd = connection.format(sql, [id]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server error.' });
}
res.send(result);
});
});
// get email config
router.get('/emailconfig', notAuthMiddleware, (req, res) => {
const sql = 'SELECT * FROM EmailConfig';
connection.query(sql, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server error.' });
}
res.send(result);
});
});
// update email template config
router.put('/emailconfig', notAuthMiddleware, (req, res) => {
const { subject, body, signature } = req.body;
const sql = 'UPDATE EmailConfig SET subject = ?, body = ?, signature = ? WHERE id = 1';
const sqlcmd = connection.format(sql, [subject, body, signature]);
connection.query(sqlcmd, (err, result) => {
if (err) {
return res.status(500).send({ message: 'Internal server error.' });
}
res.send(result);
});
});
module.exports = router;
|
import timezones from './timezones';
export {
timezones
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.