text stringlengths 7 3.69M |
|---|
document.addEventListener('click', function(event){
let target = event.target
if(target.dataset.role !== 'tab'){return}
let itemEle = document.querySelector(`.${target.dataset.item}`)
let allItemEles = target.parentElement.children
Array.from(allItemEles).forEach(ele => {
let currentView = findCurrentView(ele)
currentView.classList.remove('active')
ele.classList.remove('active')
})
target.classList.add('active')
itemEle.classList.add('active')
})
function findCurrentView(ele){
return document.querySelector(`.${ele.dataset.item}`)
}
|
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'application\json' })
// res.write("hello");
res.write("{name:anil}");
res.end();
}).listen(8900) |
const express = require('express');
const router = express.Router();
const Celebrity = require('../models/Celebrity');
const MMovie = require('../models/MMovie');
// router.get('/:id', async (req, res, next)=>{
// try{
// let celebrity = await Celebrity.findById(req.params.id)
// let movies = await MMovie.find({celebrity: req.params.id})
// res.render('author-views/details', {author, books})
// }catch(err){
// next(err);
// }
// })
/* GET home page */
router.get('/', (req, res, next) => {
res.render('index');
});
router.get('/celebrities', (req, res, next) => {
Celebrity.find()
.then((allThecelebrities)=>{
if(req.session.currentUser){
allThecelebrities.forEach((thisCelebrity)=>{
if(req.session.currentUser.admin){
thisCelebrity.isMine = true;
}
})
}
res.render('celebrities/celebrities', {theCelebrities: allThecelebrities});
})
.catch((err)=>{
next(err);
})
});
router.get('/movies', (req, res, next) => {
MMovie.find().populate('celebrity')
.then((allThemovies)=>{
if(req.session.currentUser){
allThemovies.forEach((thisMovie)=>{
if(req.session.currentUser.admin){
thisMovie.isMine = true;
}
})
}
res.render('movies/movies', {theMovies: allThemovies});
})
.catch((err)=>{
next(err);
})
});
router.get('/add-new-celebrity', (req, res, next)=>{
res.render('celebrities/new-celebrity');
})
router.get('/add-new-movie', (req, res, next)=>{
if(!req.session.currentUser){
res.redirect('/login');
return;
}
Celebrity.find()
.then((allCelebrities)=>{
res.render('movies/new-movie', {allCelebrities});
// ^ this is the same as {allAuthors:allAuthors}
})
.catch((err)=>{
next(err)
})
})
router.post('/create-celebrity', (req, res, next)=>{
if(!req.session.currentUser){
res.json({message: 'sorry hacker, not allowed'})
return;
}
let theName = req.body.theCelebrityName;
let theOccupation = req.body.theOccupation;
let theCatchPhrase = req.body.theCatchPhrase;
Celebrity.create({
name: theName,
occupation: theOccupation,
catchPhrase: theCatchPhrase
})
.then((result)=>{
// its because you named the placeholder res
// when you name it res, you are highjacking the word res and redifining it so you no longer have access to res.redirect
res.redirect('/')
})
.catch((err)=>{
next(err)
})
})
router.post('/create-the-movie', (req, res, next)=>{
if(!req.session.currentUser){
res.json({message: 'sorry hacker, not allowed'})
return;
}
let theTitle = req.body.theNewMovieTitle;
let theGenre = req.body.theGenre;
let theImage = req.body.theImage;
let thePlot = req.body.thePlot;
let auth = req.body.theCelebrityForNewMovie;
MMovie.create({
title: theTitle,
genre: theGenre,
image: theImage,
plot: thePlot,
celebrity: auth
})
.then((result)=>{
res.redirect('/')
})
.catch((err)=>{
next(err)
})
})
router.get('/movies/:theIdOfTheMovie', (req, res, next)=>{
let id = req.params.theIdOfTheMovie;
MMovie.findById(id).populate('celebrity')
.then((theMovie)=>{
res.render('movies/single-movie', {movie: theMovie})
})
.catch((err)=>{
next(err);
})
})
router.get('/celebrities/edit/:celebritiesTheID', (req, res, next)=>{
Celebrity.findById(req.params.celebritiesTheID)
.then((theCelebrity)=>{
if(!req.session.currentUser.admin){
res.redirect('/login')
return
}
res.render('celebrities/edit', {theActualCelebrity: theCelebrity})
})
.catch((err)=>{
next(err);
})
})
router.get('/movies/edit/:moviesTheID', (req, res, next)=>{
MMovie.findById(req.params.moviesTheID)
.then((theMovie)=>{
if(!req.session.currentUser.admin){
res.redirect('/login')
return
}
res.render('movies/edit', {theActualMovie: theMovie})
})
.catch((err)=>{
next(err);
})
})
router.post('/celebrities/update/:id', (req, res, next)=>{
if(!req.session.currentUser.admin){
res.json({message: "Unauthorized Injection"})
return;
}
let id = req.params.id;
id = req.body.theID;
// i put the ID in 2 places, you can do it either way
// i dont want you to blindly copy this route because it is fancy
// take a hard look at whats happening or, just cblindly copy and paste the commented code
// Celebrity.findByIdAndUpdate(id, {
// name: req.body.name,
// occupation: req.body.occupation,
// catchPhrase: req.body.catchPhrase
// })
let update = {...req.body};
// this stupid {new:true} thing is so that after we edit the book the response we get back shows us the new info isntead of the old info, not sure why this isnt the default
Celebrity.findByIdAndUpdate(id, update, {new: true})
.then((response)=>{
console.log(response)
res.redirect('/celebrities/'+id)
})
.catch((err)=>{
next(err)
})
})
router.post('/movies/update/:id', (req, res, next)=>{
if(!req.session.currentUser.admin){
res.json({message: "Unauthorized Injection"})
return;
}
let id = req.params.id;
id = req.body.theID;
let update = {...req.body};
MMovie.findByIdAndUpdate(id, update, {new: true})
.then((response)=>{
console.log(response)
res.redirect('/movies/'+id)
})
.catch((err)=>{
next(err)
})
})
router.post('/celebrities/delete/:theID', (req, res, next)=>{
Celebrity.findByIdAndRemove(req.params.theID)
.then(()=>{
res.redirect('/');
})
.catch((err)=>{
next(err)
})
})
router.post('/movies/delete/:theID', (req, res, next)=>{
MMovie.findByIdAndRemove(req.params.theID)
.then(()=>{
res.redirect('/');
})
.catch((err)=>{
next(err)
})
})
module.exports = router;
|
const router = require('express').Router();
const user = require('./users');
router.get('/',(req,res,next)=>{
res.render('searchusers');
})
router.post('/user/search',user.search);
router.get('/user/add',user.addUserForm);
router.post('/user/add',user.addUser);
router.delete('/user/delete/:id',user.deleteUser)
// router.get('/',expense.getExpenses);
module.exports = router; |
/*
(skip :))Sort a previously defined array in a descending order and display it in the console.
Input: [ 13, 11, 15, 5, 6, 1, 8, 12 ]
Output: [ 15, 13, 12, 11, 8, 6, 5, 1 ]
*/
function descend(a) {
var sort = [];
for (var i = 0; i < a.length; i++) {
for (var j = i; j < a.length; j++) {
if (a[j] > a[i]) {
sort = a[j];
a[j] = a[i];
a[i] = sort;
}
}
}
return a;
}
console.log(descend([13, 11, 15, 5, 6, 1, 8, 12]));
//bubble sort
function bubbleSort(arr){
for(var j = 0; j < arr.length; j++){
for(var i = 0; i < arr.length; i++){
var currentElement = arr[i];
var nextElement = arr[i +1];
if(nextElement > currentElement){
arr[i] = nextElement;
arr[i + 1] = currentElement;
}
}
}
return arr;
}
console.log(bubbleSort([13, 11, 15, 5, 6, 1, 8, 12]));
|
const qs = require('querystring');
const axios = require('axios');
const {URLS} = require('./const/url');
const config = require('./config');
const {buildSignature} = require('./sign');
axios.defaults.baseURL = URLS.API_URL;
module.exports = {
get,
post,
delete: del,
};
function createHeaders(urlPath, querystring = '', body = '') {
const expiry = Math.floor(Date.now() / 1000) + 2 * 60;
const content = urlPath + querystring + expiry + body;
const signature = buildSignature(content, config.secret);
return {
'Content-Type': 'application/json',
'x-phemex-access-token': config.api_key,
'x-phemex-request-expiry': expiry,
'x-phemex-request-signature': signature,
};
}
async function get(url, {query} = {}) {
try {
const querystring = query ? qs.stringify(query) : '';
const headers = createHeaders(url, querystring);
const response = await axios({
url,
method: 'get',
headers,
params: query,
paramsSerializer() {
return querystring;
},
});
if (response.status === 200) {
const {code, msg, data, error, result} = response.data;
if (code === 0) {
return {data};
}
if (result) {
return {data: result};
}
if (error) {
return {error};
}
return {error: {code, msg}};
}
return {error: {}, response};
} catch (e) {
console.error(e);
return {error: e};
}
}
async function post(url, {query, params}) {
try {
const querystring = query ? qs.stringify(query) : '';
const body = JSON.stringify(params);
const headers = createHeaders(url, querystring, body);
const response = await axios({
url,
method: 'post',
headers: headers,
params: query,
paramsSerializer() {
return querystring;
},
data: body,
});
if (response.status === 200) {
const {code, msg, data, error, result} = response.data;
if (code === 0) {
return {data};
}
if (result) {
return {data: result};
}
if (error) {
return {error};
}
return {error: {code, msg}};
}
return {error: {}, response};
} catch (e) {
console.error(e);
return {error: e};
}
}
async function del(url, {query} = {}) {
try {
const querystring = query ? qs.stringify(query) : '';
const headers = createHeaders(url, querystring);
const response = await axios({
url,
method: 'delete',
headers,
params: query,
paramsSerializer() {
return querystring;
},
});
if (response.status === 200) {
const {code, msg, data, error, result} = response.data;
if (code === 0) {
return {data};
}
if (result) {
return {data: result};
}
if (error) {
return {error};
}
return {error: {code, msg}};
}
return {error: {}, response};
} catch (e) {
console.error(e);
return {error: e};
}
}
|
import React from 'react';
import HeroSection from '../HeroSection/HeroSection';
import Footer from '../Footer/Footer';
import BackgroundColorTwo from '../HeroSection/BackgroundColorTwo';
import BackgroundColorThree from '../HeroSection/BackgroundColorThree';
import Contact from '../NavMenu/Contact';
import BackgroundColor from '../HeroSection/BackgroundColor';
import Blog from '/Users/l/my-react-website/src/components/NavMenu/Blog.js';
function Home() {
return (
<div>
<HeroSection />
<BackgroundColorTwo />
<BackgroundColorThree />
<Footer />
</div>
)
}
export default Home
|
// window.gmap_dynamic.dynamicMap("gmap-dynamic-id-A", "gmap-dynamic-id-B", locations_a, locations_b);
locations_a = [
{ lat: 49.448333, lng: -123.2002442, title_text: "Unnecessary Mountain", can_move: false, pin_color: "red" },
{ lat: 49.4125595, lng: -123.1919322, title_text: "Mount Strachan", can_move: false, pin_color: "green" },
];
locations_b = [
{ lat: 49.4256143, lng: -123.2137832, title_text: "Saint Marks Summit", can_move: false, pin_color: "blue" },
{ lat: 49.3948431, lng: -123.2315385, title_text: "Black Mountain", can_move: false, pin_color: "yellow" },
];
|
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { StylesProvider } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/core/styles';
import { theme } from './theme';
import { Container } from '@material-ui/core';
import AppNav from './components/AppNav';
import AppFrame from './pages/AppFrame';
import SavedBooks from './pages/SavedBooks';
import Login from './pages/Login';
import './index.css';
class App extends Component {
render() {
return (
<ThemeProvider theme={theme} >
<Router>
{/*Mui StylesProvider allows our styles to override Material-UI
styles - https://material-ui.com/styles/advanced/#injectfirst*/}
<StylesProvider injectFirst>
<Container fixed maxWidth="xs" className="app-container">
<Switch>
<Route exact path='/'>
<Login />
</Route>
<Route exact path='/home'>
<AppNav />
<AppFrame />
</Route>
<Route exact path="/saved">
<AppNav />
<SavedBooks />
</Route>
</Switch>
</Container>
</StylesProvider>
</Router>
</ThemeProvider>
);
}
}
export default App;
|
'use strict';
angular.module('drupalImage', [
'drupalService'
])
.directive('drupalImageId', function factory($window, $browser, File) {
return {
restrict: 'A',
template: '<img src="{{src}}" alt="{{alt}}" title="{{title}}" />',
replace: true,
scope: {
drupalImageId: '@',
drupalImageStyle: '@'
},
link: function($scope, $rootScope, $element) {
File.query({fid: $scope.drupalImageId}).$promise.then(function(data) {
$scope.src = data.url.replace('files/', 'files/styles/' + $scope.drupalImageStyle + '/public/');
$scope.alt = data.field_file_image_alt_text;
$scope.title = data.field_file_image_title_text;
});
}
}
}) |
'use strict';
const bookModel = require('../models/book.model');
const getBooks = (request, response) => {
bookModel.find((error, booksData) => {
response.json(booksData)
});
};
module.exports = {
getBooks
} |
$(function(){
$('#addClass-btn').click(function(){
$('#addClass-p').addClass('red');
})
$('#slidetoggle-btn').click(function(){
$('#img-toggle').toggle();
})
$('#append-btn').click(function(){
$('.append-div').append('<p>New Line Added</p>');
})
$('#hide-btn').click(function(){
$('#hide-show-p').hide();
})
$('#show-btn').click(function(){
$('#hide-show-p').show();
})
$('#slide-up-btn').click(function(){
$('.sliding-div').slideUp("slow");
})
$('#slide-down-btn').click(function(){
$('.sliding-div').slideDown("slow");
})
$('#fade-in-btn').click(function(){
$('.fade-div').fadeIn("slow");
})
$('#fade-out-btn').click(function(){
$('.fade-div').fadeOut("slow");
})
$('#before-btn').click(function(){
$('.before-after-div').before('<h3>Before</h3>');
})
$('#after-btn').click(function(){
$('.before-after-div').after('<h3>After</h3>');
})
$('#html-btn').click(function(){
$( "div.html-div").html("<p>All new content. <em>You bet!</em></p>");
})
$('#input-btn').click(function(){
var text = $( this ).text();
$( "input" ).val( text );
})
$("#attr-btn").click(function(){
$("#img-attr").attr("width","100");
});
}); |
export * from './RangeInputs'
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.extractDescription = exports.extractMapValues = exports.arrayToMap = exports.validatePathName = void 0;
const validatePathName = pathName => {
const re = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$|([<>:"\/\\|?*])|(\.|\s)$/gi;
return re.test(pathName) && pathName !== ".";
};
exports.validatePathName = validatePathName;
const arrayToMap = target => {
const map = new Map(target.map((value, index) => [index, value]));
return map;
};
exports.arrayToMap = arrayToMap;
const extractMapValues = target => {
return [...target.values()];
};
exports.extractMapValues = extractMapValues;
const extractDescription = target => {
return target.map(option => option.description);
};
exports.extractDescription = extractDescription; |
export default function BasketItems(state = [{
"id": "1",
"title": "CROSSBODY BAG WITH FAUX SNAKESKIN FLAP",
"src": "https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dw42ca7ba5/images/hi-res/192/54/171725_TU_2yf.jpg?sw=679&q=100",
"gallery": [
"https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dwf5d07a3b/images/hi-res/192/54/171700_TU_1yf.jpg?sw=561",
"https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dwb7104124/images/hi-res/192/54/171700_TU_3y.jpg?sw=561",
"https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dw5d8ec663/images/hi-res/192/54/171700_TU_2y.jpg?sw=561",
"https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dw1841c39e/images/hi-res/192/54/171700_TU_6y.jpg?sw=561"
],
"price": "89.99",
"full_text": "Main Material: 100%; Polyurethane Lining: 90%Polyester, 10%Polyurethane Measurements cm: 24x18x6 (LxHxW) Belt Lenght (Min. - Max.): 89Type of Opening: Zipper",
"status": "Top"
},
{
"id": "2",
"title": "PATCHWORK CROSSBODY BAG",
"src": "https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dw9b654190/images/hi-res/192/56/171868_BK_1yf.jpg?sw=679&q=100",
"gallery": [
"https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dw42ca7ba5/images/hi-res/192/54/171725_TU_2yf.jpg?sw=679&q=100",
"https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dw0772f5a7/images/hi-res/192/56/171868_BK_2y.jpg?sw=561",
"https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dw8eda4e9d/images/hi-res/192/56/171868_BK_4y.jpg?sw=561",
"https://www.parfois.com/dw/image/v2/BBKR_PRD/on/demandware.static/-/Sites-parfois-master-catalog/default/dw3fcd1127/images/hi-res/192/56/171868_BK_5y.jpg?sw=561"
],
"price": "79.99",
"full_text": "Main Material: 100%; Polyurethane Lining: 90%Polyester, 10%Polyurethane Measurements cm: 24x18x6 (LxHxW) Belt Lenght (Min. - Max.): 89Type of Opening: Zipper",
"status": "Sale"
}], action) {
if (action.type != undefined) {
switch (action.type) {
case "ADD_TO_BASKET": {
return [...state, action.data];
}
case "DEC": {
return state - action.data;
}
default: {
return state
}
}
}
return state
} |
import React from 'react';
import {NavLink,Route,Switch,Prompt,Redirect,withRouter} from 'react-router-dom';
import * as $ from 'jquery';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import QuestionManager from '../question-manager/question-manager-container';
import ChapterManager from '../chapter-manager/container';
import TopicManager from '../topic-manager/container';
import SubjectManager from '../subject-manager/container';
import TestManager from '../test-manager/container';
import UserManager from '../user-manager/container';
import CourseManager from '../course-manager/container';
import BlogManager from '../blog-manager/container';
import StrategyManager from '../strategy-manager/container';
import SecureComponent from '../../common/secure/component';
import './style.css';
import CacheManagerComponent from '../cache-manager/component';
import StudyMatrial from '../study-matrial/container';
import MockExamManager from '../mock-exam-manager/container';
class AdminHome extends React.Component{
state={
navigationOpen:false
}
componentDidMount = ()=>{
let rootElement =$('#root');
rootElement.on('click',this.closeNavigationPanel);
}
closeNavigationPanel = ()=>{
$('#demo').addClass("d-none");
}
toggleNavigationContainer = ()=>{
$('#demo').toggleClass("d-none");
}
render(){
return (
<div className="container-fluid admin-home-container" >
<div className="row admin-navigator-container">
<div className="admin-navigator-toggler-col">
<FontAwesomeIcon
onClick={this.toggleNavigationContainer}
className="admin-navigator-toggler"
icon="bars" />
</div>
<div id="demo" className="d-none admin-navigator-items-container">
<div className=" admin-navigator-items-row">
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item"
to={`${this.props.match.url}/user-manager`} activeClassName="admin-navigator-item-active" > User Manager </NavLink>
</div>
<div className="admin-navigator-items-item" >
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/subject-manager`} activeClassName="admin-navigator-item-active"> Subject Manager </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/chapter-manager`} activeClassName="admin-navigator-item-active"> Chapter Manager </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/topic-manager`} activeClassName="admin-navigator-item-active"> Topic Manager </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/question-manager`} activeClassName="admin-navigator-item-active"> Question Manager </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/course-manager`} activeClassName="admin-navigator-item-active"> Course Manager </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/test-manager`} activeClassName="admin-navigator-item-active"> Test Manager </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/mock-exam-manager`} activeClassName="admin-navigator-item-active"> Exam Manager </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/study-matrial`} activeClassName="admin-navigator-item-active"> Study Matrial </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/blog-manager`} activeClassName="admin-navigator-item-active"> Blog Manager </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/strategy-manager`} activeClassName="admin-navigator-item-active"> Strategy Manager </NavLink>
</div>
<div className="admin-navigator-items-item">
<NavLink className="admin-navigator-item" to={`${this.props.match.url}/cache-manager`} activeClassName="admin-navigator-item-active"> Cache Manager </NavLink>
</div>
</div>
</div>
<div className="admin-editor-container" onClick={this.closeNavigationPanel}>
<Switch>
<SecureComponent path={`${this.props.match.url}/study-matrial`} component={StudyMatrial}/>
<SecureComponent path={`${this.props.match.url}/user-manager`} component={UserManager}/>
<SecureComponent path={`${this.props.match.url}/course-manager`} component={CourseManager}/>
<SecureComponent path={`${this.props.match.url}/chapter-manager`} component={ChapterManager}/>
<SecureComponent path={`${this.props.match.url}/topic-manager`} component={TopicManager}/>
<SecureComponent path={`${this.props.match.url}/subject-manager`} component={SubjectManager}/>
<SecureComponent path={`${this.props.match.url}/test-manager`} component={TestManager}/>
<SecureComponent path={`${this.props.match.url}/mock-exam-manager`} component={MockExamManager}/>
<SecureComponent path={`${this.props.match.url}/question-manager`} component={QuestionManager}/>
<SecureComponent path={`${this.props.match.url}/blog-manager`} component={BlogManager}/>
<SecureComponent path={`${this.props.match.url}/strategy-manager`} component={StrategyManager}/>
<SecureComponent path={`${this.props.match.url}/cache-manager`} component={CacheManagerComponent}/>
<Route
render={()=><Redirect to={`${this.props.match.url}/user-manager`}/>}/>
</Switch>
</div>
</div>
</div>
);
}
};
let AdminHomeComp = withRouter(AdminHome);
export default AdminHomeComp; |
// insure jslib base is loaded
if (typeof(JS_LIB_LOADED)=='boolean')
{
// these two vars below are specifically used for jslib
var JS_DATE_LOADED = true;
var JS_FILE_DATE = "date.js";
var DEFAULT_DATE_FORMAT = "d.m.Y - H:i:s";
/**
* The month- and weekdayname is to be stored
* in a dtd language dependent file.
*/
var month = new Array(
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
);
var weekday = new Array(
"Sunday",
"Monday",
"Tuesday",
"Wedensday",
"Thursday",
"Friday",
"Saturday"
);
/**
* Returns a string formatted according to the given
* format string using the given date object
*/
function jslibDate(aDateString, aDate)
{
if (arguments.length<1)
aDateString = DEFAULT_DATE_FORMAT;
var date = aDate;
if (arguments.length<2)
date = (new Date);
var datePatterns = new Array(
// Lowercase Ante meridiem and Post meridiem
new Array(new RegExp(/([^\\])a|^a()/g), addSlashes(getMeridiem(getHours(aDate)))),
// Uppercase Ante meridiem and Post meridiem
new Array(new RegExp(/([^\\])A|^A()/g),
addSlashes(getMeridiem(getHours(aDate)).toUpperCase())),
// Swatch internet time
new Array(new RegExp(/([^\\])B|^B()/g), getSwatchInternetTime(date)),
// Day of the month, 2 digits with leading zeros
new Array(new RegExp(/([^\\])d|^d()/g), insertLeadingZero(date.getDate())),
// A textual representation of a week, three letters
new Array(new RegExp(/([^\\])D|^D()/g), addSlashes(weekday[date.getDay()].substr(0,3))),
// A full textual representation of a month
new Array(new RegExp(/([^\\])F|^F()/g), addSlashes(month[date.getMonth()])),
// 12-hour format of an hour without leading zeros
new Array(new RegExp(/([^\\])g|^g()/g), twelveHour(aDate)),
// 24-hour format of an hour without leading zeros
new Array(new RegExp(/([^\\])G|^G()/g), getHours(aDate)),
// 12-hour format of an hour with leading zeros
new Array(new RegExp(/([^\\])h|^h()/g), insertLeadingZero(twelveHour(aDate))),
// 24-hour format of an hour with leading zeros
new Array(new RegExp(/([^\\])H|^H()/g), insertLeadingZero(getHours(aDate))),
// Minutes with leading zeros
new Array(new RegExp(/([^\\])i|^i()/g), insertLeadingZero(date.getMinutes())),
// Whether or not the date is in daylights savings time
new Array(new RegExp(/([^\\])I|^I()/g), ""),
// Day of the month without leading zeros
new Array(new RegExp(/([^\\])j|^j()/g), date.getDate()),
// A full textual representation of the day of the week
new Array(new RegExp(/([^\\])l|^l()/g), addSlashes(weekday[date.getDay()])),
// Whether it's a leap year
new Array(new RegExp(/([^\\])L|^L()/g), leapYear(date.getFullYear())),
// Numeric representation of a month, with leading zeros
new Array(new RegExp(/([^\\])m|^m()/g), insertLeadingZero(date.getMonth()+1)),
// A short textual representation of a month, three letters
new Array(new RegExp(/([^\\])M|^M()/g), addSlashes(month[date.getMonth()].substr(0,3))),
// Numeric representation of a month, without leading zeros
new Array(new RegExp(/([^\\])n|^n()/g), date.getMonth()+1),
// Difference to Greenwich time (GMT) in hours
new Array(new RegExp(/([^\\])O|^O()/g), getGTMDifference(date)),
// RFC 822 formatted date
new Array(new RegExp(/([^\\])r|^r()/g), getRFCDate(date)),
// Seconds, with leading zeros
new Array(new RegExp(/([^\\])s|^s()/g), insertLeadingZero(date.getSeconds())),
// English ordinal suffix for the day of the month, 2 characters
new Array(new RegExp(/([^\\])S|^S()/g), addSlashes(getDateSuffix(date.getDate()))),
// Number of days in the given month
new Array(new RegExp(/([^\\])t|^t()/g), getDaysInMonth(date)),
// Timezone setting of this machine
new Array(new RegExp(/([^\\])T|^T()/g), ""),
// Miliseconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
new Array(new RegExp(/([^\\])U|^U()/g), date.getTime()),
// Numeric representation of the day of the week
new Array(new RegExp(/([^\\])w|^w()/g), date.getDay()),
// ISO-8601 week number of year, weeks starting on Monday
new Array(new RegExp(/([^\\])W|^W()/g), getWeekNumber(date)),
// A two digit representation of a year
new Array(new RegExp(/([^\\])y|^y()/g), (""+date.getFullYear()).substr(2,2)),
// A full numeric representation of a year, 4 digits
new Array(new RegExp(/([^\\])Y|^Y()/g), date.getFullYear()),
// The day of the year
new Array(new RegExp(/([^\\])z|^z()/g), getNumberOfDays(date)),
// Timezone offset in seconds. The offset for timezones west of
// UTC is always negative, and for those east of UTC is always positive.
new Array(new RegExp(/([^\\])Z|^Z()/g), getTimezoneOffset(date)),
// Replace all backslashes followed by a letter with the letter
new Array(new RegExp(/\\([A-Za-z])/g), "")
);
var datePattern;
while ((datePattern = datePatterns.shift()))
aDateString = aDateString.replace(datePattern[0], "$1" + datePattern[1]);
return aDateString;
}
// deprecated
var date = jslibDate;
/**
* Returns the hour in a 12-hour format
*/
function twelveHour(aDate)
{
var hour;
if (aDate)
hour = aDate.getHours();
else
hour = (new Date()).getHours();
if ( getMeridiem(hour)=="pm" )
hour -= 12;
if ( hour==0 )
hour = 12;
return hour;
}
/**
* Returns lowercase am or pm based on the given 24-hour
*/
function getMeridiem(hour)
{
if ( hour>11 )
return "pm";
else
return "am";
}
/**
* Return true if year is a leap year otherwise false
*/
function leapYear(year)
{
//The Date object automatic corrigates if values is out of limit
//29 isn't out of limit if it is leap year!
var date = new Date(year, 1, 29);
if ( date.getMonth()==1 )
return 1;
else
return 0;
}
/**
* Returns the number of days from new year to current date (incl current day)
*/
function getNumberOfDays(date)
{
var currentDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var startOfYear = new Date(date.getFullYear(), 0, 1);
return ( currentDate.getTime()-startOfYear.getTime() )/86400000 +1;
}
/**
* Returns the number of days in the current month of the date object
*/
function getDaysInMonth(date)
{
var currentDate = new Date(date.getFullYear(), date.getMonth()+1, 0);
var startOfYear = new Date(date.getFullYear(), date.getMonth(), 1);
return ( currentDate.getTime()-startOfYear.getTime() )/86400000 +1;
}
/**
* Returns the english ordinal suffix for the day of the month, 2 characters
*/
function getDateSuffix(dayOfMonth)
{
var rv = null;
if ( dayOfMonth>3 && dayOfMonth<21 ) {
rv = "th";
} else {
switch( dayOfMonth%10 ) {
case 1:
rv = "st";
break;
case 2:
rv = "nd";
break;
case 3:
rv = "rd";
break;
default:
rv = "th";
break;
}
}
return rv;
}
function daylightSavingsTime(date)
{
return 0;
}
/**
* Timezone offset in seconds
* -43200 through 43200
*/
function getTimezoneOffset(date)
{
return date.getTimezoneOffset()*(-60);
}
/**
* This function isn't implemented yet, but here is an idea of how it might look
* Before thins function can be made the function daylightSavingsTime() have
* to be written
* http://www.timeanddate.com/time/abbreviations.html
* http://setiathome.ssl.berkeley.edu/utc.html
*/
function getTimezone(date)
{
if ( daylightSavingsTime(date)==1 ) {
switch(getTimezoneOffset(date)/3600) {
case -11:
return "";
break;
//..........
case 0:
return "";
break;
case 1:
return "WEST";
break;
case 2:
return "CEST";
break;
case 3:
return "EEST";
break;
//............
case 12:
return "";
break;
default:
return "";
break;
}
}
else {
switch(getTimezoneOffset(date)/3600) {
case -11:
return "";
break;
//..........
case 0:
return "";
break;
case 1:
return "WET";
break;
case 2:
return "CET";
break;
case 3:
return "EET";
break;
//............
case 12:
return "";
break;
default:
return "";
break;
}
}
return "";
}
/**
* Difference to Greenwich time (GMT) in hours
*/
function getGTMDifference(date)
{
var offset = getTimezoneOffset(date)/3600;
if (offset>0) //adding leading zeros and gives the offset a positive prefix
return "+" + insertLeadingZero(offset) + "00";
else //if negative, make the offset positive before adding leading zeros and give the number a negative prefix
return "-" + insertLeadingZero(offset*(-1)) + "00";
}
/**
* In [ISO8601], the week number is defined by:
* - weeks start on a monday
* - week 1 of a given year is the one that includes the first
* Thursday of that year.
* (or, equivalently, week 1 is the week that includes 4 January.)
* Weeknumbers can be a number between 1 - 53 (53 is not common)
*/
function getWeekNumber(date)
{
var weekday = date.getDay();
if (weekday==0)
weekday = 7;
//currentDate is on the fist monday in the same week of date (could be the same date)
var currentDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()-(weekday-1));
var startOfYear = new Date(currentDate.getFullYear(), 0, 1);
var firstWeekday = startOfYear.getDay();
var extraDays;
if ( 5>firstWeekday )
extraDays = firstWeekday-1;
else
extraDays = firstWeekday-8;
//var numberOfDays = ( ( currentDate.getTime()-startOfYear.getTime() )/86400000 ) + extraDays;
//var weekNumber = numberOfDays/7 +1;
return ( ( ( currentDate.getTime()-startOfYear.getTime() )/86400000 ) + extraDays )/7 +1;
}
/**
* RFC 822 formatted
* http://www.freesoft.org/CIE/RFC/822/39.htm
*/
function getRFCDate(aDate)
{
var dayRFC = addSlashes(weekday[aDate.getDay()].substr(0,3));
var dateRFC = aDate.getDate() + " " + addSlashes(month[aDate.getMonth()].substr(0,3))
+ " " + (""+aDate.getFullYear()).substr(2,2);
var timeRFC = insertLeadingZero(aDate.getHours()) + ":"
+ insertLeadingZero(aDate.getMinutes()) + ":"
+ insertLeadingZero(aDate.getSeconds()) + " " + getGTMDifference(aDate);
return dayRFC + ", " + dateRFC + " " + timeRFC;
}
/**
* 1min 26.4sek = 1 Swatch beat
* (60sek + 26.4sek)*1000milliseconds/second = 86400miliseconds = 1 Swatch beat
*/
function getSwatchInternetTime(aDate)
{
// A day in Internet Time begins at midnight BMT (@000 Swatch Beats)
// (Central European Wintertime) (+0100 from GTM)
// This line makes the Date object corrigate if the hour is 23 then it
// will be set to 0 and the date will be incremented
var h = aDate.getUTCHours();
var nDate = new Date(aDate);
nDate.setUTCHours(h+1);
var milliseconds = Date.UTC(1970, 0, 1,
nDate.getUTCHours(),
nDate.getUTCMinutes(),
nDate.getUTCSeconds());
return "@" + ( milliseconds-( milliseconds%86400 ) )/86400;
}
/**
* Some of the numbers needs leading zeros
* and this function returns the number with a leading zero
* if the number is smaller than 10
*/
function insertLeadingZero(number)
{
if (number < 10)
number = "0" + number;
return number;
}
/**
* This function is used to make every second character a backslash
* so the insterted charaters isn't converted to hours, dates and so on.
*/
function addSlashes(string)
{
var stringTemp = "";
for(var x=0; x<string.length; x++) {
stringTemp += "\\";
stringTemp += string.substr(x, 1);
}
return stringTemp;
}
function getHours (aDate)
{
var rv;
if (aDate)
rv = aDate.getHours();
else
rv = (new Date()).getHours();
return rv;
}
jslibLoadMsg(JS_FILE_DATE);
} else { dump("Load Failure: date.js\n"); }
|
const express = require("express");
const path = require("path");
const router = express.Router();
/** CUSTOM IMPORTS */
const rootDir = require("../utils/path");
const producsController = require("../controllers/products");
router.get('/add-product',producsController.getAddProduct);
// will accept only incoming POST requests
router.post('/add-product', producsController.postAddProduct);
module.exports = router;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const network_1 = require("./network");
const engine_1 = require("./engine");
const textureArea_1 = require("./textureArea");
const CubicModelAsset_1 = require("../../data/CubicModelAsset");
const TreeView = require("dnd-tree-view");
const ResizeHandle = require("resize-handle");
const THREE = SupEngine.THREE;
const ui = {};
exports.default = ui;
// Hotkeys
document.addEventListener("keydown", (event) => {
if (document.querySelector(".dialog") != null)
return;
let activeElement = document.activeElement;
while (activeElement != null) {
if (activeElement === ui.canvasElt || activeElement === ui.treeViewElt)
break;
activeElement = activeElement.parentElement;
}
if (activeElement == null)
return;
if (event.keyCode === 78 && (event.ctrlKey || event.metaKey)) { // Ctrl+N
event.preventDefault();
onNewNodeClick();
}
if (event.keyCode === 113) { // F2
event.preventDefault();
onRenameNodeClick();
}
if (event.keyCode === 68 && (event.ctrlKey || event.metaKey)) { // Ctrl+D
event.preventDefault();
onDuplicateNodeClick();
}
if (event.keyCode === 46) { // Delete
event.preventDefault();
onDeleteNodeClick();
}
});
ui.canvasElt = document.querySelector("canvas");
// Setup resizable panes
new ResizeHandle(document.querySelector(".texture-container"), "bottom");
new ResizeHandle(document.querySelector(".sidebar"), "right");
new ResizeHandle(document.querySelector(".nodes-tree-view"), "top");
// Grid
ui.gridSize = 20;
ui.gridStep = 1;
document.getElementById("grid-step").addEventListener("input", onGridStepInput);
document.getElementById("grid-visible").addEventListener("change", onGridVisibleChange);
function onGridStepInput(event) {
const target = event.target;
let value = parseFloat(target.value);
if (value !== 0 && value < 0.0001) {
value = 0;
target.value = "0";
}
if (isNaN(value) || value <= 0) {
target.reportValidity();
return;
}
ui.gridStep = value;
engine_1.default.gridHelperComponent.setup(ui.gridSize, ui.gridStep);
}
function onGridVisibleChange(event) {
engine_1.default.gridHelperComponent.setVisible(event.target.checked);
}
// Unit ratio
ui.pixelsPerUnitInput = document.querySelector("input.property-pixelsPerUnit");
ui.pixelsPerUnitInput.addEventListener("change", onChangePixelsPerUnit);
function onChangePixelsPerUnit(event) { network_1.data.projectClient.editAsset(SupClient.query.asset, "setProperty", "pixelsPerUnit", parseFloat(event.target.value)); }
// Texture download
document.querySelector("button.download").addEventListener("click", (event) => {
function triggerDownload(name) {
const anchor = document.createElement("a");
document.body.appendChild(anchor);
anchor.style.display = "none";
anchor.href = network_1.data.cubicModelUpdater.cubicModelAsset.clientTextureDatas["map"].ctx.canvas.toDataURL();
// Not yet supported in IE and Safari (http://caniuse.com/#feat=download)
anchor.download = `${name}.png`;
anchor.click();
document.body.removeChild(anchor);
}
const options = {
initialValue: SupClient.i18n.t("cubicModelEditor:sidebar.settings.cubicModel.download.defaultName"),
validationLabel: SupClient.i18n.t("common:actions.download")
};
if (SupApp != null) {
triggerDownload(options.initialValue);
}
else {
new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("cubicModelEditor:sidebar.settings.cubicModel.download.prompt"), options, (name) => {
if (name == null)
return;
triggerDownload(name);
});
}
});
// Texture size
ui.textureWidthSelect = document.querySelector("select.property-texture-width");
ui.textureHeightSelect = document.querySelector("select.property-texture-height");
const addOption = (parent, value) => {
const optionElt = document.createElement("option");
optionElt.textContent = value.toString();
optionElt.value = value.toString();
parent.appendChild(optionElt);
};
for (const size of CubicModelAsset_1.default.validTextureSizes) {
addOption(ui.textureWidthSelect, size);
addOption(ui.textureHeightSelect, size);
}
ui.textureWidthSelect.addEventListener("input", (event) => { network_1.data.projectClient.editAsset(SupClient.query.asset, "changeTextureWidth", parseInt(event.target.value, 10)); });
ui.textureHeightSelect.addEventListener("input", (event) => { network_1.data.projectClient.editAsset(SupClient.query.asset, "changeTextureHeight", parseInt(event.target.value, 10)); });
// Setup tree view
ui.treeViewElt = document.querySelector(".nodes-tree-view");
ui.nodesTreeView = new TreeView(ui.treeViewElt, { dragStartCallback: () => true, dropCallback: onNodesTreeViewDrop });
ui.nodesTreeView.on("activate", onNodeActivate);
ui.nodesTreeView.on("selectionChange", () => { setupSelectedNode(); });
function createNodeElement(node) {
const liElt = document.createElement("li");
liElt.dataset["id"] = node.id;
const nameSpan = document.createElement("span");
nameSpan.classList.add("name");
nameSpan.textContent = node.name;
liElt.appendChild(nameSpan);
const visibleButton = document.createElement("button");
visibleButton.textContent = SupClient.i18n.t("cubicModelEditor:sidebar.nodes.hide");
visibleButton.classList.add("show");
visibleButton.addEventListener("click", (event) => {
event.stopPropagation();
const { shape } = network_1.data.cubicModelUpdater.cubicModelRenderer.byNodeId[event.target.parentElement.dataset["id"]];
shape.visible = !shape.visible;
visibleButton.textContent = SupClient.i18n.t(`cubicModelEditor:sidebar.nodes.${(shape.visible) ? "hide" : "show"}`);
if (shape.visible)
visibleButton.classList.add("show");
else
visibleButton.classList.remove("show");
});
liElt.appendChild(visibleButton);
return liElt;
}
exports.createNodeElement = createNodeElement;
function onNodesTreeViewDrop(event, dropLocation, orderedNodes) {
const dropPoint = SupClient.getTreeViewDropPoint(dropLocation, network_1.data.cubicModelUpdater.cubicModelAsset.nodes);
const nodeIds = [];
for (const node of orderedNodes)
nodeIds.push(node.dataset["id"]);
const sourceParentNode = network_1.data.cubicModelUpdater.cubicModelAsset.nodes.parentNodesById[nodeIds[0]];
const sourceChildren = (sourceParentNode != null && sourceParentNode.children != null) ? sourceParentNode.children : network_1.data.cubicModelUpdater.cubicModelAsset.nodes.pub;
const sameParent = (sourceParentNode != null && dropPoint.parentId === sourceParentNode.id);
let i = 0;
for (const id of nodeIds) {
network_1.data.projectClient.editAsset(SupClient.query.asset, "moveNode", id, dropPoint.parentId, dropPoint.index + i);
if (!sameParent || sourceChildren.indexOf(network_1.data.cubicModelUpdater.cubicModelAsset.nodes.byId[id]) >= dropPoint.index)
i++;
}
return false;
}
function onNodeActivate() { ui.nodesTreeView.selectedNodes[0].classList.toggle("collapsed"); }
function setupSelectedNode() {
engine_1.setupHelpers();
// Setup texture area
const nodeIds = [];
for (const node of ui.nodesTreeView.selectedNodes)
nodeIds.push(node.dataset["id"]);
textureArea_1.setSelectedNode(nodeIds);
// Setup transform
const nodeElt = ui.nodesTreeView.selectedNodes[0];
if (nodeElt == null || ui.nodesTreeView.selectedNodes.length !== 1) {
ui.inspectorElt.hidden = true;
ui.renameNodeButton.disabled = true;
ui.duplicateNodeButton.disabled = true;
ui.deleteNodeButton.disabled = true;
return;
}
ui.inspectorElt.hidden = false;
const node = network_1.data.cubicModelUpdater.cubicModelAsset.nodes.byId[nodeElt.dataset["id"]];
setInspectorPosition(node.position);
setInspectorOrientation(node.orientation);
// Setup shape editor
ui.inspectorFields.shape.type.value = node.shape.type;
setInspectorShapeOffset(node.shape.offset);
ui.shapeTbodyElt.hidden = node.shape.type !== "box";
if (!ui.shapeTbodyElt.hidden) {
const boxSettings = node.shape.settings;
setInspectorBoxSize(boxSettings.size);
setInspectorBoxStretch(boxSettings.stretch);
}
// Enable buttons
ui.renameNodeButton.disabled = false;
ui.duplicateNodeButton.disabled = false;
ui.deleteNodeButton.disabled = false;
}
exports.setupSelectedNode = setupSelectedNode;
function roundForInspector(number) { return parseFloat(number.toFixed(3)); }
function setInspectorPosition(position) {
const values = [
roundForInspector(position.x).toString(),
roundForInspector(position.y).toString(),
roundForInspector(position.z).toString()
];
for (let i = 0; i < 3; i++) {
// NOTE: This helps avoid clearing selection when possible
if (ui.inspectorFields.position[i].value !== values[i]) {
ui.inspectorFields.position[i].value = values[i];
}
}
}
exports.setInspectorPosition = setInspectorPosition;
function setInspectorOrientation(orientation) {
const euler = new THREE.Euler().setFromQuaternion(orientation);
const values = [
roundForInspector(THREE.Math.radToDeg(euler.x)).toString(),
roundForInspector(THREE.Math.radToDeg(euler.y)).toString(),
roundForInspector(THREE.Math.radToDeg(euler.z)).toString()
];
// Work around weird conversion from quaternion to euler conversion
if (values[1] === "180" && values[2] === "180") {
values[0] = roundForInspector(180 - THREE.Math.radToDeg(euler.x)).toString();
values[1] = "0";
values[2] = "0";
}
for (let i = 0; i < 3; i++) {
// NOTE: This helps avoid clearing selection when possible
if (ui.inspectorFields.orientation[i].value !== values[i]) {
ui.inspectorFields.orientation[i].value = values[i];
}
}
}
exports.setInspectorOrientation = setInspectorOrientation;
function setInspectorShapeOffset(offset) {
const values = [
roundForInspector(offset.x).toString(),
roundForInspector(offset.y).toString(),
roundForInspector(offset.z).toString()
];
for (let i = 0; i < 3; i++) {
// NOTE: This helps avoid clearing selection when possible
if (ui.inspectorFields.shape.offset[i].value !== values[i]) {
ui.inspectorFields.shape.offset[i].value = values[i];
}
}
}
exports.setInspectorShapeOffset = setInspectorShapeOffset;
function setInspectorBoxSize(size) {
const values = [size.x.toString(), size.y.toString(), size.z.toString()];
for (let i = 0; i < 3; i++) {
// NOTE: This helps avoid clearing selection when possible
if (ui.inspectorFields.shape.box.size[i].value !== values[i]) {
ui.inspectorFields.shape.box.size[i].value = values[i];
}
}
}
exports.setInspectorBoxSize = setInspectorBoxSize;
function setInspectorBoxStretch(stretch) {
const values = [
roundForInspector(stretch.x).toString(),
roundForInspector(stretch.y).toString(),
roundForInspector(stretch.z).toString()
];
for (let i = 0; i < 3; i++) {
// NOTE: This helps avoid clearing selection when possible
if (ui.inspectorFields.shape.box.stretch[i].value !== values[i]) {
ui.inspectorFields.shape.box.stretch[i].value = values[i];
}
}
}
exports.setInspectorBoxStretch = setInspectorBoxStretch;
// Transform mode
ui.translateMode = "all";
document.querySelector(".main .controls .transform-mode").addEventListener("click", onTransformModeClick);
document.querySelector(".main .controls .transform-settings").addEventListener("click", onTransformSettingsClick);
function onTransformModeClick(event) {
const target = event.target;
if (target.tagName !== "INPUT")
return;
if (target.id === "transform-space") {
engine_1.default.transformHandleComponent.setSpace(target.checked ? "local" : "world");
}
else {
const transformSpaceCheckbox = document.getElementById("transform-space");
transformSpaceCheckbox.disabled = target.value === "scale";
engine_1.default.transformHandleComponent.setMode(target.value);
if (target.value === "translate") {
ui.translateMode = target.dataset["target"];
const linkShapeToPivot = document.getElementById("translate-pivot-shape").checked;
if (ui.translateMode === "pivot" && linkShapeToPivot)
ui.translateMode = "all";
}
}
engine_1.setupHelpers();
}
function onTransformSettingsClick(event) {
const target = event.target;
if (target.tagName !== "INPUT")
return;
if (target.id === "transform-space") {
engine_1.default.transformHandleComponent.setSpace(target.checked ? "local" : "world");
}
else if (target.id === "translate-pivot-shape") {
const linkShapeToPivot = document.getElementById("translate-pivot-shape").checked;
if (ui.translateMode === "pivot" && linkShapeToPivot)
ui.translateMode = "all";
else if (ui.translateMode === "all" && !linkShapeToPivot)
ui.translateMode = "pivot";
}
}
// Node buttons
ui.newNodeButton = document.querySelector("button.new-node");
ui.newNodeButton.addEventListener("click", onNewNodeClick);
ui.renameNodeButton = document.querySelector("button.rename-node");
ui.renameNodeButton.addEventListener("click", onRenameNodeClick);
ui.duplicateNodeButton = document.querySelector("button.duplicate-node");
ui.duplicateNodeButton.addEventListener("click", onDuplicateNodeClick);
ui.deleteNodeButton = document.querySelector("button.delete-node");
ui.deleteNodeButton.addEventListener("click", onDeleteNodeClick);
// Inspector
ui.inspectorElt = document.querySelector(".inspector");
ui.shapeTbodyElt = ui.inspectorElt.querySelector(".box-shape");
ui.inspectorFields = {
position: ui.inspectorElt.querySelectorAll(".transform .position input"),
orientation: ui.inspectorElt.querySelectorAll(".transform .orientation input"),
shape: {
type: ui.inspectorElt.querySelector(".shape .type select"),
offset: ui.inspectorElt.querySelectorAll(".shape .offset input"),
box: {
size: ui.inspectorElt.querySelectorAll(".box-shape .size input"),
stretch: ui.inspectorElt.querySelectorAll(".box-shape .stretch input")
}
}
};
for (const input of ui.inspectorFields.position)
input.addEventListener("change", onInspectorInputChange);
for (const input of ui.inspectorFields.orientation)
input.addEventListener("change", onInspectorInputChange);
for (const input of ui.inspectorFields.shape.offset)
input.addEventListener("change", onInspectorInputChange);
for (const input of ui.inspectorFields.shape.box.size)
input.addEventListener("change", onInspectorInputChange);
for (const input of ui.inspectorFields.shape.box.stretch)
input.addEventListener("change", onInspectorInputChange);
function onNewNodeClick() {
// TODO: Allow choosing shape and default texture color
const options = {
initialValue: "Node",
validationLabel: SupClient.i18n.t("common:actions.create")
};
new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("cubicModelEditor:sidebar.nodes.newNode.prompt"), options, (name) => {
if (name == null)
return;
const options = SupClient.getTreeViewInsertionPoint(ui.nodesTreeView);
const quaternion = new THREE.Quaternion();
engine_1.default.cameraActor.getGlobalOrientation(quaternion);
const offset = new THREE.Vector3(0, 0, -10).applyQuaternion(quaternion);
const position = new THREE.Vector3();
engine_1.default.cameraActor.getGlobalPosition(position).add(offset);
const pixelsPerunit = network_1.data.cubicModelUpdater.cubicModelAsset.pub.pixelsPerUnit;
if (options.parentId != null) {
const inverseParentMatrix = new THREE.Matrix4().getInverse(network_1.data.cubicModelUpdater.cubicModelRenderer.byNodeId[options.parentId].pivot.matrixWorld);
position.applyMatrix4(inverseParentMatrix);
}
else {
position.multiplyScalar(pixelsPerunit);
}
options.transform = { position };
options.shape = {
type: "box",
offset: { x: 0, y: 0, z: 0 },
settings: {
size: { x: pixelsPerunit, y: pixelsPerunit, z: pixelsPerunit },
stretch: { x: 1, y: 1, z: 1 }
}
};
network_1.data.projectClient.editAsset(SupClient.query.asset, "addNode", name, options, (nodeId) => {
ui.nodesTreeView.clearSelection();
ui.nodesTreeView.addToSelection(ui.nodesTreeView.treeRoot.querySelector(`li[data-id='${nodeId}']`));
setupSelectedNode();
});
});
}
function onRenameNodeClick() {
if (ui.nodesTreeView.selectedNodes.length !== 1)
return;
const selectedNode = ui.nodesTreeView.selectedNodes[0];
const node = network_1.data.cubicModelUpdater.cubicModelAsset.nodes.byId[selectedNode.dataset["id"]];
const options = {
initialValue: node.name,
validationLabel: SupClient.i18n.t("common:actions.rename")
};
new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("cubicModelEditor:sidebar.nodes.renamePrompt"), options, (newName) => {
if (newName == null)
return;
network_1.data.projectClient.editAsset(SupClient.query.asset, "setNodeProperty", node.id, "name", newName);
});
}
function onDuplicateNodeClick() {
if (ui.nodesTreeView.selectedNodes.length !== 1)
return;
const selectedNode = ui.nodesTreeView.selectedNodes[0];
const node = network_1.data.cubicModelUpdater.cubicModelAsset.nodes.byId[selectedNode.dataset["id"]];
const options = {
initialValue: node.name,
validationLabel: SupClient.i18n.t("common:actions.duplicate")
};
new SupClient.Dialogs.PromptDialog(SupClient.i18n.t("cubicModelEditor:sidebar.nodes.duplicatePrompt"), options, (newName) => {
if (newName == null)
return;
const options = SupClient.getTreeViewInsertionPoint(ui.nodesTreeView);
network_1.data.projectClient.editAsset(SupClient.query.asset, "duplicateNode", newName, node.id, options.index, (nodeId) => {
ui.nodesTreeView.clearSelection();
ui.nodesTreeView.addToSelection(ui.nodesTreeView.treeRoot.querySelector(`li[data-id='${nodeId}']`));
setupSelectedNode();
});
});
}
function onDeleteNodeClick() {
if (ui.nodesTreeView.selectedNodes.length === 0)
return;
const confirmLabel = SupClient.i18n.t("cubicModelEditor:sidebar.nodes.deleteConfirm");
const validationLabel = SupClient.i18n.t("common:actions.delete");
new SupClient.Dialogs.ConfirmDialog(confirmLabel, { validationLabel }, (confirm) => {
if (!confirm)
return;
for (const selectedNode of ui.nodesTreeView.selectedNodes) {
network_1.data.projectClient.editAsset(SupClient.query.asset, "removeNode", selectedNode.dataset["id"]);
}
});
}
function onInspectorInputChange(event) {
if (ui.nodesTreeView.selectedNodes.length !== 1)
return;
const nodeId = ui.nodesTreeView.selectedNodes[0].dataset["id"];
// transform, shape or box-shape
const context = event.target.parentElement.parentElement.parentElement.parentElement.className;
let path;
let uiFields;
if (context === "transform") {
path = "";
uiFields = ui.inspectorFields;
}
else if (context === "shape") {
path = "shape.";
uiFields = ui.inspectorFields.shape;
}
else if (context === "box-shape") {
path = "shape.settings.";
uiFields = ui.inspectorFields.shape.box;
}
else
throw new Error("Unsupported inspector input context");
const propertyType = event.target.parentElement.parentElement.parentElement.className;
let value;
if (context === "shape" && propertyType === "type") {
// Single value
value = uiFields[propertyType].value;
}
else {
// Multiple values
const inputs = uiFields[propertyType];
value = {
x: parseFloat(inputs[0].value),
y: parseFloat(inputs[1].value),
z: parseFloat(inputs[2].value),
};
if (propertyType === "orientation") {
const euler = new THREE.Euler(THREE.Math.degToRad(value.x), THREE.Math.degToRad(value.y), THREE.Math.degToRad(value.z));
const quaternion = new THREE.Quaternion().setFromEuler(euler);
value = { x: quaternion.x, y: quaternion.y, z: quaternion.z, w: quaternion.w };
}
}
if (propertyType !== "position" || ui.translateMode !== "pivot")
network_1.data.projectClient.editAsset(SupClient.query.asset, "setNodeProperty", nodeId, `${path}${propertyType}`, value);
else
network_1.data.projectClient.editAsset(SupClient.query.asset, "moveNodePivot", nodeId, value);
}
|
import React from 'react';
import Wrapper from './Wrapper';
import PropTypes from 'prop-types';
import {Button} from 'reactstrap';
// Stateless component
const TableRow = (props) => {
var row = props.row;
return (
<tr>
<td>{row.category}</td>
<td>{row.description}</td>
<td>{row.priority}</td>
<td>{row.status}</td>
<td><Button color="danger"onClick={() => {
props.onclick(props.index);
}}>Change Status</Button></td>
</tr>
)
}
// defaultProps available in es6
TableRow.defaultProps = {
row : {
category: 'General',
description: 'Default Description',
priority: 0,
status: 'Open'
},
index: 0
}
// using prop-types package
TableRow.propTypes = {
row: PropTypes.object,
index: PropTypes.number
}
export default TableRow; |
/**
@author Chris Humboldt
**/
// Extend Rocket
Rocket.defaults.require = {
errors: true,
rootPath: './node_modules/'
};
// Load main file (if provided)
function RockMod_RequireLoadMain() {
var loadMainScript = document.querySelector('script[data-main]');
if (loadMainScript) {
var mainFile = loadMainScript.getAttribute('data-main');
if (Rocket.is.string(mainFile) && mainFile.length > 0) {
var customPath = (mainFile.substring(0, 2) === '~/') ? Rocket.defaults.rootPath : './';
RockMod_Require.load(mainFile, false, customPath);
}
}
}
;
// Rocket module
var RockMod_Module;
(function (RockMod_Module) {
// Variables
var listModules = {};
// Functions
/*
All module related methods go here. Makes it easier to manage,
especially within Typescript.
*/
var moduleMethods = {
add: function (obj) {
// Catch
if (!Rocket.is.object(obj)) {
return false;
}
// Continue
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (validate.module(key, obj[key])) {
listModules[key] = {
loaded: false,
loading: false
};
if (Rocket.is.string(obj[key].css) || Rocket.is.array(obj[key].css)) {
listModules[key].css = moduleMethods.sanitisePaths(obj[key].css);
}
if (Rocket.is.string(obj[key].js) || Rocket.is.array(obj[key].js)) {
listModules[key].js = moduleMethods.sanitisePaths(obj[key].js);
}
if (Rocket.is.array(obj[key].requires)) {
listModules[key].requires = obj[key].requires;
}
}
}
}
},
dependencies: function (name) {
// Catch
if (!Rocket.is.string(name)) {
return false;
}
// Continue
var dependencies = [];
// Functions
function checkModule(name) {
if (moduleMethods.exists(name)) {
dependencies.push(name);
var thisModule = listModules[name];
if (Rocket.is.array(thisModule.requires)) {
for (var _i = 0, _a = thisModule.requires; _i < _a.length; _i++) {
var moduleName = _a[_i];
if (dependencies.indexOf(moduleName) > -1) {
if (Rocket.defaults.require.errors) {
throw new Error('ROCKET REQUIRE: You have a dependency loop with module: ' + name);
}
else {
return false;
}
}
checkModule(moduleName);
}
}
}
}
;
// Execute
checkModule(name);
return dependencies;
},
exists: function (name) {
// Catch
if (!Rocket.is.string(name)) {
return false;
}
// Continue
return Rocket.exists(listModules[name]);
},
get: function (name) {
// Catch
if (!Rocket.is.string(name)) {
return false;
}
// Continue
return listModules[name];
},
isLoaded: function (name) {
// Catch
if (!Rocket.is.string(name)) {
return false;
}
// Continue
var thisModule = listModules[name];
return (Rocket.is.object(thisModule)) ? thisModule.loaded : false;
},
isLoading: function (name) {
// Catch
if (!Rocket.is.string(name)) {
return false;
}
// Continue
var thisModule = listModules[name];
return (Rocket.is.object(thisModule)) ? thisModule.loading : false;
},
listLoaded: function () {
var listLoaded = [];
for (var key in listModules) {
if (listModules.hasOwnProperty(key) && listModules[key].loaded) {
listLoaded.push(key);
}
}
return listLoaded;
},
remove: function (name) {
// Catch
if (!Rocket.is.string(name) || !Rocket.exists(listModules[name])) {
return false;
}
// Continue
delete listModules[name];
},
sanitisePaths: function (paths) {
// Convert string to array
if (Rocket.is.string(paths)) {
paths = [paths];
}
// Set the root url if need be
for (var len = paths.length, i = 0; i < len; i++) {
paths[i] = paths[i].replace(/~\//g, Rocket.defaults.require.rootPath);
}
return paths;
}
};
var validate = {
module: function (name, obj) {
var hasCSS = false;
var hasJS = false;
var hasRequires = false;
if (!Rocket.is.string(name)) {
return false;
}
if (!Rocket.is.object(obj)) {
return false;
}
if (!Rocket.exists(obj.css) && !Rocket.exists(obj.js) && !Rocket.exists(obj.requires)) {
return false;
}
if ((Rocket.is.string(obj.css) || Rocket.is.array(obj.css) && obj.css.length > 0)) {
hasCSS = true;
}
if ((Rocket.is.string(obj.js) || Rocket.is.array(obj.js) && obj.js.length > 0)) {
hasJS = true;
}
if (Rocket.is.array(obj.requires) && obj.requires.length > 0) {
hasRequires = true;
}
if (!hasCSS && !hasJS && !hasRequires) {
return false;
}
return true;
}
};
// Exports
RockMod_Module.add = moduleMethods.add;
RockMod_Module.exists = moduleMethods.exists;
RockMod_Module.get = moduleMethods.get;
RockMod_Module.isLoaded = moduleMethods.isLoaded;
RockMod_Module.isLoading = moduleMethods.isLoading;
RockMod_Module.dependencies = moduleMethods.dependencies;
RockMod_Module.list = listModules;
RockMod_Module.loaded = moduleMethods.listLoaded;
RockMod_Module.remove = moduleMethods.remove;
})(RockMod_Module || (RockMod_Module = {}));
// Rocket require
var RockMod_Require;
(function (RockMod_Require) {
var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
// Functions
function loadFile(file, callback, customRootPath) {
var theInclude;
var type;
var rootUrl = (Rocket.is.string(customRootPath)) ? customRootPath : '';
var filePath = (Rocket.is.url(file)) ? file : rootUrl + file;
var ext = Rocket.get.extension(file);
// Create include element
switch (ext) {
case 'css':
if (isFirefox) {
/*
Date: 18 July 2017
Its a bit of a hack but an elegant one regardless. All CSS loads are hacks anyway ;)
Author: stoyanstefanov
Reference URL: http://www.phpied.com/when-is-a-stylesheet-really-loaded/
*/
theInclude = document.createElement('style');
theInclude.textContent = '@import "' + filePath + '"';
var poll_1 = setInterval(function () {
try {
theInclude.sheet.cssRules;
clearInterval(poll_1);
setTimeout(function () {
return callback(true);
});
}
catch (ev) { }
}, 10);
onReady(function () {
Rocket.dom.head.appendChild(theInclude);
});
}
else {
theInclude = document.createElement('link');
theInclude.rel = 'stylesheet';
theInclude.href = filePath;
// Functions
function loadCallback() {
Rocket.event.remove(theInclude, 'load', loadCallback);
if (Rocket.is.function(callback)) {
setTimeout(function () {
return callback(true);
});
}
}
function loadError() {
theInclude.onerror = function () {
if (Rocket.is.function(callback)) {
return callback(false);
}
};
}
function loadIE() {
theInclude.onreadystatechange = function () {
if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
this.onreadystatechange = null;
if (Rocket.is.function(callback)) {
return callback(true);
}
}
};
}
// Execute
Rocket.event.add(theInclude, 'load', loadCallback);
loadIE();
loadError();
onReady(function () {
Rocket.dom.head.appendChild(theInclude);
});
}
break;
case 'js':
theInclude = document.createElement('script');
theInclude.setAttribute('async', true);
theInclude.src = filePath;
// Complete callback
theInclude.onload = function () {
if (Rocket.is.function(callback)) {
return callback(true);
}
};
theInclude.onreadystatechange = function () {
if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
this.onreadystatechange = null;
if (Rocket.is.function(callback)) {
return callback(false);
}
}
};
theInclude.onerror = function () {
if (Rocket.is.function(callback)) {
return callback(false);
}
};
// Add the script
Rocket.dom.head.appendChild(theInclude);
break;
}
}
function onReady(callback) {
if (document.body) {
return callback();
}
setTimeout(function () {
onReady(callback);
});
}
// Load module files
function loadModuleFiles(thisModule, callback) {
var count = 0;
var files = [];
// CSS
if (Rocket.is.string(thisModule.css)) {
files.push(thisModule.css);
}
else if (Rocket.is.array(thisModule.css) && thisModule.css.length > 0) {
files = files.concat(thisModule.css);
}
// JS
if (Rocket.is.string(thisModule.js)) {
files.push(thisModule.js);
}
else if (Rocket.is.array(thisModule.js) && thisModule.js.length > 0) {
files = files.concat(thisModule.js);
}
// Count
count = files.length;
// Execute
// Catch
if (count < 1) {
return callback();
}
// Continue
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
var file = files_1[_i];
loadFile(file, function (resp) {
count--;
if (count === 0) {
thisModule.loaded = true;
return callback();
}
}, false);
}
}
// Require instance
/*
Self contain the require so that each instance has its own scope.
*/
var Require = (function () {
function Require() {
this.modules = [];
}
// Functions
Require.prototype.add = function (name) {
// Check
if (!Rocket.is.string(name)
|| !Rocket.module.exists(name)
|| Rocket.module.isLoaded(name)
|| this.modules.indexOf(name) > -1) {
return false;
}
// Continue
this.modules = this.modules.concat(Rocket.module.dependencies(name));
this.modules = Rocket.array.unique(this.modules);
};
/*
The load function will take the newly created require instance and execute
the loading of each module in the various dependency stacks.
*/
Require.prototype.load = function (callback) {
// Variables
var self = this;
// Functions
function loadExecute() {
loadModules(self.modules, function () {
self.modules = [];
if (Rocket.is.function(callback)) {
return callback();
}
});
}
function loadModule(name, callback) {
/*
Check to see if the module exists. Rocket require is explicit and will
hard fail should a module not be found. This is to protect against lazy
module management.
*/
if (!Rocket.module.exists(name)) {
if (Rocket.defaults.require.errors) {
throw new Error('ROCKET REQUIRE: You are missing a required module: ' + name);
}
}
else {
var thisModule_1 = Rocket.module.get(name);
/*
Here we find that the module is already loaded or loading.
Return the callback and move on as needed.
*/
if (thisModule_1.loaded || thisModule_1.loading) {
if (thisModule_1.loaded) {
return callback();
}
else {
// Poll the variable once loaded
var modIntervalCheck_1 = setInterval(function () {
if (thisModule_1.loaded) {
clearInterval(modIntervalCheck_1);
return callback();
}
}, 10);
}
}
else {
var dependencies = (Rocket.is.array(thisModule_1.requires) && thisModule_1.requires.length > 0) ? thisModule_1.requires : false;
// Change state to loading
thisModule_1.loading = true;
// Check dependency
if (!dependencies) {
return loadModuleFiles(thisModule_1, callback);
}
else {
loadModules(dependencies, function () {
return loadModuleFiles(thisModule_1, callback);
});
}
}
}
}
function loadModules(modules, callback) {
var count = modules.length;
for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
var thisModule = modules_1[_i];
loadModule(thisModule, function () {
count--;
if (count === 0) {
setTimeout(function () {
return callback();
}, 10);
}
});
}
}
// Execute
loadExecute();
};
return Require;
}());
RockMod_Require.newRequire = Require;
RockMod_Require.load = loadFile;
})(RockMod_Require || (RockMod_Require = {}));
// Bind to the Rocket object
Rocket.module = RockMod_Module;
Rocket.require = function () {
return new RockMod_Require.newRequire;
};
// Load main file
RockMod_RequireLoadMain();
|
jQuery(document).foundation();
function handleScroll() {
var previousScroll = pageYOffset;
jQuery(window).scroll(function(){
var currentScroll = jQuery(this).scrollTop();
if (currentScroll > previousScroll){
} else {
}
previousScroll = currentScroll;
if ( pageYOffset < 100 ) {
jQuery('.breadcrumbs-bar').removeClass('scrolled');
} else {
jQuery('.breadcrumbs-bar').addClass('scrolled');
}
});
}
function getArchiveMap() {
if ( undefined === Exchange
|| undefined === Exchange.PluginExtensions
|| undefined === Exchange.PluginExtensions.LMP
|| undefined === Exchange.PluginExtensions.LMP.maps ) {
return;
}
for ( var hashedMap in Exchange.PluginExtensions.LMP.maps ) {
if ( Exchange.PluginExtensions.LMP.maps.hasOwnProperty( hashedMap ) ) {
var archiveMap = Exchange.PluginExtensions.LMP.maps[hashedMap];
archiveMap.hash = hashedMap.slice( 4 );
break;
}
}
if ( archiveMap ) {
return archiveMap;
}
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function getFocusTranslate( img_placeholder, img ) {
img_data = img_placeholder.parentNode.dataset;
if ( ! img_data ) {
return false;
}
var h = img.clientHeight,
container_h = img_placeholder.offsetHeight,
px_translate = ( img_data.focus_h * h ) - ( container_h / 2 ),
max_translate = ( ( h - container_h ) / h ) * 100,
translate = ( px_translate / h ) * 100;
//If the center of the container is below the focus point, don't move.
//Or: if the translation is downwards, don't move (we're working from top).
if ( px_translate < 0 || translate < 0 ) {
return false;
}
if ( translate > max_translate ) {
return max_translate;
} else {
return translate;
}
}
function doFocusTranslate( img ) {
var img_placeholder = img.parentNode;
translate = getFocusTranslate( img_placeholder, img );
// Keep the negative, add minus if necessary
if ( translate ) {
var translateNeg = translate > 0 ? -1 * translate : translate,
transform = 'transform: translateY(' + translateNeg + '%);';
img.setAttribute( 'style', transform );
}
}
var masonryOptions = {
"percentPosition": true,
"columnWidth": ".masonry__grid-sizer",
"gutter": ".masonry__gutter-sizer",
"itemSelector": ".archive__grid__griditem"
};
var masonryIsActive = false;
(function($){
$(document).ready(function() {
if ( $grid == undefined ) {
var $grid = $('.archive__grid__masonry');
}
if ( $('.featuredgrid__masonry').length === 1 ) {
var $grid = $('.featuredgrid__masonry');
masonryOptions.itemSelector = ".featuredgrid__griditem";
}
// if ('object' == typeof FWP) {
// wp.hooks.addFilter('facetwp/template_html', function(resp, params) {
// if (FWP.is_load_more) {
// FWP.is_load_more = false;
// $('.facetwp-template').append(params.html);
// return true;
// }
// return resp;
// });
// } else {
// console.log( 'FWP is not defined yet' );
// }
$('.focus').each(function() {
var img = $(this).find('.image--main');
img.on('load', function(e){
doFocusTranslate(e.target);
});
})
var floated_elements = document.querySelectorAll('.floated');
for (var ii = 0; ii < floated_elements.length; ii++ ) {
var equal_element = floated_elements[ii].nextElementSibling,
h = floated_elements[ii].offsetHeight,
equal_h = equal_element.offsetHeight;
if ( h > equal_h ) {
equal_element.style.height = h + 'px';
}
}
$( 'a[data-open=story__modal--gallery]' ).on( 'click', function( e ) {
e.preventDefault();
var id = $(this).data('img_id'),
targetjQ = $('#story__modal--gallery').find('#' + id);
$('.orbit').foundation( 'changeSlide', true, targetjQ );
})
$( '#token-form__submit' ).on( 'click', function( e ) {
e.preventDefault();
$(this).prop('disabled',true);
var selection = $( '.token-form__collab-select option:selected' ),
grid = $('.grid--form-options'),
prToken = getUrlVars()['pr'];
if ( undefined !== selection ) {
var data = {
action: 'exchange_token_form',
update_id : selection.val(),
prid : selection.data('programme-round'),
token : prToken,
security : $( '.token-form__nonce' ).val()
};
$('.loader-pointer').remove();
$('.loader-wrapper').addClass('go');
grid.html('');
$.ajax( {
'url': exchange_ajax.ajax_url,
'method': 'POST',
'data': data
} ).done( function ( response ) {
grid.html( response );
$('.loader-wrapper').removeClass('go');
$(this).removeProp('disabled');
} );
};
} );
$('.translatedparagraph--has_translations').each( function() {
var select = $( this ).find('.translation-select');
select.on('change', function() {
var lang = 'paragraph--' + this.value;
function doLanguageSwitch( lang ) {
return function( index, element) {
$( this ).removeClass('show');
if ( $( this ).hasClass( lang ) ) {
$( this ).addClass('show');
}
}
};
var wrapper = $( this ).parent().parent('.translatedparagraph--has_translations');
paragraphs = wrapper.children('.translatedparagraph__paragraph');
paragraphs.each( doLanguageSwitch( lang ) );
});
});
if ( $('body').hasClass('single') || $('body').hasClass('page-child') ) {
$('#main').on('scrollme.zf.trigger', handleScroll);
}
if ( $('body').hasClass( 'archive' )
|| $('body').hasClass( 'page-template-archive')
|| $('body').hasClass( 'search')
|| $('.featuredgrid__masonry').length === 1 ) {
if ( $('body').hasClass( 'post-type-archive-participant') ) {
if ( archiveMap === undefined ) {
var archiveMap = getArchiveMap();
}
if ( archiveMap ) {
archiveMap.map.fitBounds( archiveMap.clusterLayer.getBounds() );
}
}
if ( $grid !== undefined ) {
$grid.masonry( masonryOptions ); // re-initialize
masonryIsActive = true;
}
}
// $('#facet-tabs').on('change.zf.tabs', function() {
// if ( archiveMap === undefined ) {
// var archiveMap = getArchiveMap();
// }
// if ( archiveMap.map !== undefined ) {
// archiveMap.map.invalidateSize().fitBounds( archiveMap.clusterLayer.getBounds() );
// }
// if ( $grid !== undefined ) {
// $grid.masonry( masonryOptions ); // re-initialize
// masonryIsActive = true;
// }
// })
$('.archive__facets__type__reset').on('click', function() {
// Reset all facets to their default state
if ( undefined != FWP ) {
FWP.reset();
}
})
$('#facet-switch').on('click', function() {
('#main').foundation('toggle');
})
// Remove empty P tags created by WP inside of Accordion and Orbit
$('.accordion p:empty, .orbit p:empty').remove();
// Makes sure last grid item floats left
$('.archive__grid .columns', 'relatedgrid .columns').last().addClass( 'end' );
// Adds Flex Video to YouTube and Vimeo Embeds
$('iframe[src*="youtube.com"], iframe[src*="vimeo.com"]').each(function() {
if ( $(this).innerWidth() / $(this).innerHeight() > 1.5 ) {
$(this).wrap("<div class='widescreen flex-video'/>");
} else {
$(this).wrap("<div class='flex-video'/>");
}
});
})
$(document).on('click', '.fwp-load-more', function() {
$('.fwp-load-more').html('Loading...');
FWP.is_load_more = true;
FWP.paged = parseInt(FWP.settings.pager.page) + 1;
FWP.soft_refresh = true;
FWP.refresh();
});
$(document).on('facetwp-loaded', function() {
var $grid = $('.archive__grid__masonry');
if ( masonryIsActive ) {
$grid.masonry('destroy'); // destroy
}
$grid.masonry( masonryOptions ); // re-initialize
masonryIsActive = true;
var archiveMap = getArchiveMap();
if ( archiveMap === undefined ) {
return;
}
var allObjects = window['leaflet_objects_' + archiveMap.hash];
if ( allObjects === undefined
|| allObjects.map_markers.length == 0
|| FWP.settings.matches.length == 0 ) {
return;
}
if ( allObjects.map_markers.length > 0 && FWP.settings.matches.length > 0 ) {
var matchedMarkers = allObjects.map_markers.filter( function( p ) {
for ( var i = 0; FWP.settings.matches.length > i; i++ )
if ( FWP.settings.matches[i] === p.id ) {
return true;
}
});
if ( matchedMarkers.length > 0 ) {
var refreshObjects = {
map_markers : matchedMarkers
};
archiveMap.renderObjects( refreshObjects );
}
}
if (FWP.settings.pager.page < FWP.settings.pager.total_pages) {
if (! FWP.loaded && 1 > $('.fwp-load-more').length) {
$('.facetwp-template').after('<button style="clear: both;" class="fwp-load-more">Load more</button>');
}
else {
$('.fwp-load-more').html('Load more').show();
}
}
else {
$('.fwp-load-more').hide();
}
if ( FWP.settings.pager.page > 1 ) {
$('html, body').animate({
scrollTop: $('.archive__grid__masonry').offset().bottom
}, 1000);
}
})
$(document).on('facetwp-refresh', function() {
if (! FWP.loaded) {
FWP.paged = 1;
}
if ( $('body').hasClass( 'page-template-archive' ) ) {
if ( FWP !== undefined && FWP.template === 'archive_filtered' ) {
var archiveHeader = 'Results for: ';
for ( var tax in FWP.facets ) {
if ( FWP.facets.hasOwnProperty( tax ) ) {
for ( var i = 0; i < FWP.facets[tax].length; i++ ) {
archiveHeader += FWP.facets[tax][i].replace(/-/g," ");
}
}
}
$('.archive__title-wrapper').html('<h1>' + archiveHeader + '</h1>' );
}
console.log( archiveHeader );
}
});
})(jQuery);
|
import React from 'react';
import { connect } from 'react-redux';
import d3 from 'd3';
import '../../public/stylesheets/c3.min.css';
import _ from 'lodash'
// title, id, array of [label , query]
class C3Donut extends React.Component {
componentWillReceiveProps(nextProps) {
if (this.checkChange(this.props.queries, nextProps)) {
let updatedColumns = this.props.queries.map(x => [x[0], nextProps.latest[0][x[1]]]);
this.chart.load({
columns: updatedColumns
})
}
}
checkChange (arr, nextProps) {
for (let item of arr){
if (parseInt(this.props.latest[item[1]])
!== parseInt(nextProps.latest[0][item[1]])){
return true;
}
}
return false;
}
componentDidMount() {
let startColumns = this.props.queries.map(x => [x[0], this.props.latest[0][x[1]]]);
if (window === undefined) {
return null;
} else {
const c3 = require('c3');
var self = this;
self.chart = c3.generate({
bindto: `#${this.props.id}`,
data: {
columns: startColumns,
type: 'donut'
},
donut: {
title: this.props.title
}
});
}
}
render() {
return (
<div id={this.props.id} />
)
}
}
function mapStateToProps(state) {
return {
latest: state.graph.latest,
}
}
export default connect(mapStateToProps, null)(C3Donut); |
const handler = {
async exec({ args, client, m, messageFrom }) {
let chat = await client.getChatById(m.from);
if (chat.isGroup) {
if (m.mentionedIds.length >= 1) {
if (chat.groupMetadata.participants.filter(e => e.id._serialized === messageFrom)[0].isAdmin || messageFrom === global.ownerId) {
let isBotAdmin = chat.groupMetadata.participants.filter(e => e.id._serialized === global.botId)[0].isAdmin;
if (isBotAdmin) {
if (m.mentionedIds.includes(global.ownerId)) m.reply('Itu ownerku, gak boleh dikick!')
else if (m.mentionedIds.includes(global.botId)) m.reply('Itu nomorku, gak boleh dikick!')
else chat.removeParticipants(m.mentionedIds)
} else {
m.reply('Jadikan bot sebagai admin!')
}
} else {
m.reply('Kamu siapa? perintah ini khusus *ADMIN Group*')
}
} else {
m.reply('Tag orangnya!')
}
} else {
m.reply('Hanya bisa digunakan digroup!')
}
},
commands: ['kick', '-', 'usir', 'remove'],
tag: 'Group',
help: ['kick', '-', 'usir', 'remove'].map(v => v + ' <Tag>')
}
module.exports = handler
|
function Needle (opts) {
this.a = opts.a || createVector(random(width * 0.1, width * 0.9), random(height * 0.1, height * 0.9))
this.r = random(TWO_PI)
this.l = opts.l || (opts.a && opts.b ? p5.Vector.dist(opts.a, opts.b) : random(5, 50))
this.b = opts.b || createVector(this.l * cos(this.r) + this.a.x, this.l * sin(this.r) + this.a.y)
this.padding = opts.padding || 2
this.time = 0.0001
this.increment = 0.01
this.strokeWeight = opts.strokeWeight || 1
this.needles = opts.needles || []
var sub = p5.Vector.sub(this.a,this.b)
sub.setMag(this.padding)
var a1 = p5.Vector.add(this.a, sub)
var b1 = p5.Vector.sub(this.b, sub)
var r1 = atan2(this.b.x - this.a.x, this.b.y - this.a.y) * -1
var x1 = this.padding * cos(r1) + b1.x
var y1 = this.padding * sin(r1) + b1.y
var x2 = -this.padding * cos(r1) + b1.x
var y2 = -this.padding * sin(r1) + b1.y
var x3 = this.padding * cos(r1) + a1.x
var y3 = this.padding * sin(r1) + a1.y
var x4 = -this.padding * cos(r1) + a1.x
var y4 = -this.padding * sin(r1) + a1.y
this.boundingBox = [
{x: x1, y: y1},
{x: x2, y: y2},
{x: x4, y: y4},
{x: x3, y: y3}
]
this.highlight = function () {
push()
stroke(0, 255, 0)
strokeWeight(4)
line(this.a.x, this.a.y, this.b.x, this.b.y)
pop()
}
this.showBoundingBox = function () {
push()
strokeWeight(1)
stroke(255, 0, 0, 100)
beginShape()
vertex(this.boundingBox[0].x, this.boundingBox[0].y)
vertex(this.boundingBox[1].x, this.boundingBox[1].y)
vertex(this.boundingBox[2].x, this.boundingBox[2].y)
vertex(this.boundingBox[3].x, this.boundingBox[3].y)
endShape(CLOSE)
pop()
}
this.draw = function () {
this.time += this.increment;
this.time = this.time > 1 ? 1 : this.time < 0 ? 0 : this.time
var t = constrain(this.time, 0, 1)
noFill()
strokeCap(SQUARE)
strokeWeight(this.strokeWeight)
stroke(0, map(t, 0, 1, 50, 100))
if (this.increment > 0) {
line(this.a.x, this.a.y, lerp(this.a.x, this.b.x, easeOutExpo(t)), lerp(this.a.y, this.b.y, easeOutExpo(t)))
}else if (t > 0.2) {
line(this.b.x, this.b.y, lerp(this.b.x, this.a.x, easeInExpo(t)), lerp(this.b.y, this.a.y, easeInExpo(t)))
}
if (t <= 0) {
var index = this.needles.indexOf(this)
if (index > -1) {
needles.splice(index, 1);
}
}
}
this.remove = function () {
this.increment = -0.01
}
this.isAnimating = function () {
return this.time != 1
}
}
|
import View from './login.view';
import enhancer from './login.enhancer';
export default enhancer(View);
|
const locations = require('./locations');
const locationItems = require('./locationItems');
module.exports = {
locations,
locationItems,
};
|
import 'core-js';
import React from 'react';
import ReactDOM from 'react-dom';
// Comment the line below and Promise.finally works
import ExcelJS from 'exceljs';
let color = 'green';
let result = '# Promise.finally works!';
let error = '';
try {
Promise.resolve(42).finally(() => {
console.log(result);
});
} catch (e) {
color = 'red';
result = '# Promise.finally fails :-(';
error = 'Error: ' + e.message;
console.log(e);
}
ReactDOM.render(
<div>
<h1>Promise.finally fails in Firefox 66-68</h1>
<p style={{ color }}>
{result}
<br />
{error}
</p>
</div>,
document.getElementById('root'),
);
|
const style = {
font: '8px pixel-operator-mono8',
cellWidth: 8,
cellHeight: 10,
}
|
(function ($, root) {
// 依赖页面跳转模块
// 依赖音频
var pageControler = new root.pageControler,
audioControler = null;
var prevListenTime = 0,
listenTime = 0,
duration = 0,
frameId = null,
interval = null,
currentIndex = null,
dataList = null;
root.timeControler = function (audioControl) {
audioControler = audioControl;
this.start = function (time) {
if (time) {
audioControler.playTo(time);
audioControler.play();
} else {
audioControler.play();
}
var startTime = new Date().getTime();
interval = function () {
var currentTime = new Date().getTime();
listenTime = prevListenTime ? prevListenTime + currentTime - startTime : currentTime - startTime;
if (listenTime >= duration) {
toEnd();
} else {
update(listenTime);
frameId = requestAnimationFrame(interval)
}
}
frameId = requestAnimationFrame(interval)
}
this.stop = function () {
audioControler.pause();
cancelAnimationFrame(frameId);
prevListenTime = listenTime;
listenTime = 0;
}
this.reset = function (index, data) {
cancelAnimationFrame(frameId);
currentIndex = index;
dataList = data;
duration = data[index]["duration"] * 1000;
prevListenTime = 0;
listenTime = 0;
update(0);
}
// 拖动进度条
this.drag = function () {
var startPosition = null, //开始位置
dist = null, //拖动距离
percent = null, //拖动距离所占百分比
width = $(".line-wrapper").width(), //拖动条长度
totalListenTime = null; //拖动点所在位置表示的时间
$(".circle").on("touchstart", function (e) {
cancelAnimationFrame(frameId);
startPosition = e.changedTouches[0].clientX;
})
.on("touchmove", function (e) {
dist = e.changedTouches[0].clientX - startPosition;
percent = dist / width;
//因为先播放再暂停后listenTime会被暂停函数清零,因此下面做了一个容错
totalListenTime = duration * percent + (listenTime ? listenTime : prevListenTime);
if (totalListenTime <= 0) {
totalListenTime = 0;
} else if (totalListenTime >= duration) {
totalListenTime = duration;
}
update(totalListenTime);
})
.on("touchend", () => {
prevListenTime = totalListenTime;
listenTime = 0;
this.start(prevListenTime);
})
}
}
function update (time) {
var percent = 100 - time / duration * 100;
time = getTime(Math.round(time / 1000));
$(".current-time").html(time);
$(".line-top").css("transform", `translateX(-${percent}%)`)
}
function getTime (time) {
var seconds = null,
minutes = null;
seconds = time % 60;
seconds = seconds < 10 ? "0" + seconds : seconds;
minutes = (time - seconds) / 60;
minutes = minutes < 10 ? "0" + minutes : minutes;
return minutes + " : " + seconds;
}
function toEnd () {
cancelAnimationFrame(frameId);
currentIndex = pageControler.prevOrNext(+1, currentIndex, dataList);
$(".btn-play").trigger("playchange", currentIndex);
}
})(window.Zepto, window.player)
|
import React from 'react';
export class GltfLight extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log('light found');
}
render() {
return (
<pointLight
position={props.pos}
intensity={props.strength} />
);
}
}
|
import express from 'express';
import * as skillCtrl from '../controllers/skill.controller';
import isAuthenticated from '../middlewares/authenticate';
import validate from '../config/joi.validate';
import schema from '../utils/validator';
const router = express.Router();
/**
* @swagger
* tags:
* - name: skill
* description: Skill operations
*/
router.route('/get')
/**
* @swagger
* /skill/get_first/{id}:
* get:
* tags:
* - skill
* summary: Get Doctor by first level project id
* operationId: getById
* consumes:
* - application/json
* produces:
* - application/json
* parameters:
* - name: id
* in: path
* description: id of first level project that needs to be fetched
* required: true
* type: integer
* responses:
* 200:
* description: OK
* schema:
* $ref: "#/definitions/Doctor"
* 404:
* description: Doctor not found
* schema:
* $ref: '#/definitions/Error'
*/
.get(validate(schema.CheckSkill), (req, res) => {
skillCtrl.GetDoctor(req, res);
});
export default router; |
var BNAccessSensorPointController = function($scope, BNAccessJSONService, $log,$routeParams) {
console.log($routeParams.sensorPoint);
$scope.sensorName=$routeParams.sensorPoint;
$scope.title = "BNAccess Sensor Points Page";
$scope.homeScreeMessage = "SensorPoints are a holding container for sensor Devices in the system. "
+ "All data from a sensor Device is assigned to the SensorPoint containing it.";
$scope.sensors = [ "Sensor 1", "Sensor 2", "Sensor 3", "Sensor 4",
"Sensor 5" ];
$scope.sensorSelected = $scope.sensorName;
$log.info($scope.sensorSelected);
$scope.temperatureJSON = BNAccessJSONService.getJson();
// console.log($scope.temperatureJSON);
//$log.info($scope.temperatureJSON);
$scope.dataSource = {
chart : {
caption : "Temperature Time Graph",
subCaption : $scope.sensorSelected,
xAxisName : "Time",
yAxisName : "Temperature",
numberSuffix : "F",
showValues : "0",
theme : "fint"
},
data : [ {
label : "4:00 PM",
value : "30"
}, {
label : "5:00 PM",
value : "50"
}, {
label : "6:00 PM",
value : "25"
}, {
label : "7:00 PM",
value : "20"
} ]
};
}
BNAccessHome.controller("BNAccessSensorPointController",BNAccessSensorPointController); |
function Arm( x, y, dir ){
this.x = x;
this.y = y;
this.length = length;
this.dir = dir+180;
this.centerx = x + sin(radians(this.dir))*this.length;
this.centery = y + cos(radians(this.dir))*this.length;
this.offset = 0;
this.radius = 100;
this.speed = 2;
this.color = 0;
this.update = function(){
var x = this.centerx + sin(radians(this.offset+this.dir))*this.radius;
var y = this.centery + cos(radians(this.offset+this.dir))*this.radius;
this.offset += this.speed;
this.color += 0.2;
if( this.color > 100 ) this.color = 0;
strokeWeight(7);
stroke(this.color, 100, 70);
point( x, y );
strokeWeight(1);
line( this.x, this.y, x, y );
stroke(80, 100, 40 );
strokeWeight(7);
point( this.x, this.y );
}
this.setCenter = function( dir ){
this.centerx = x + sin(radians(this.dir+dir))*this.length;
this.centery = y + cos(radians(this.dir+dir))*this.length;
}
}
var arms = [];
var corners = 5;
var dir = 0;
function setup(){
createCanvas( window.innerWidth, window.innerHeight );
var size = min( width, height )/2;
colorMode(HSB, 100);
var centerx = width/2;
var centery = height/2;
for( var i=0; i<360; i+=360/30 ){
var s = sin(radians(i))*size/2;
var c = cos(radians(i))*size/2;
var arm = new Arm( centerx+s, centery+c, i );
arm.length = size/5.7;
arm.radius = size/20;
arm.offset = -i*corners;
arm.color = -arm.offset/corners/3.6 % 100;
arms.push( arm );
}
background(50);
}
function draw(){
background(20);
arms.forEach( (arm)=>{
arm.update();
arm.setCenter( sin(radians(dir/2))*30 );
});
dir += 1;
}
|
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import styled from 'styled-components';
const Header = styled.header`
display: flex;
align-items: center;
margin: 10px 10px 20px;
`;
const Title = styled.a`
text-decoration: none;
font-size: 25px;
margin-right: 15px;
color: #2c3e50;
`;
const List = styled.ul`
display: flex;
list-style: none;
padding-left: 0px;
margin: 5px;
`;
const Item = styled.li`
font-size: 17px;
font-weight: bolder;
margin: 5px;
padding: 5px;
`;
const SLink = styled(Link)`
text-decoration: none;
color: ${props => (props.current === 'true' ? '#6c5ce7' : '#2c3e50')};
`;
export default withRouter(({ location: { pathname } }) => (
<Header>
<div>
<Title href='/'>BOOKFLIX</Title>
</div>
<nav>
<List>
<Item >
<SLink to='/' current={pathname === '/' ? 'true' : 'false'}>베스트셀러</SLink>
</Item>
<Item>
<SLink to='/newBook' current={pathname === '/newBook' ? 'true' : 'false'}>신간도서</SLink>
</Item>
<Item>
<SLink to='/recommend' current={pathname === '/recommend' ? 'true' : 'false'}>추천도서</SLink>
</Item>
<Item>
<SLink to='/search' current={pathname === '/search' ? 'true' : 'false'}>도서검색</SLink>
</Item>
</List>
</nav>
</Header>
));
|
/**
* Created by cwh on 16-2-13.
*/
//
//function docDownload() {
// if (this.id == "doc0") {
//
// }
//}
//
//window.onload = function(){
// var docBtns = document.getElementsByTagName("button");
// var i =docBtns.length;
// for (;i--;) {
// console.log(i);
// docBtns[i].onclick = docDownload;
// }
//};
function changeFileName(elem) {
var file_path_splits = elem.value.split("\\");
elem.nextElementSibling.value = file_path_splits[file_path_splits.length - 1];
elem.nextSibling.data = file_path_splits[file_path_splits.length - 1];
console.log("test");
}
function validateRemove(doc_id) {
var r = confirm("真的要删除吗?");
if (r) {
location.href = "../../" + doc_id + "/rm_doc";
}
}
function checkUpload() {
if (document.getElementById("upload_file").value != "") {
return true;
} else {
return false;
}
return
} |
require('dotenv').config();
const fetch = require('node-fetch');
const express = require('express');
const MAP_QUEST_API_KEY = process.env.MAP_QUEST_API_KEY;
const STREETMAPS_WEBSITE = 'https://www.mapquestapi.com/geocoding/v1/reverse';
const PORT = process.env.PORT || 3000;
const GRIDID_PREFIX = 'AQUARIUS GRID ';
const app = express();
async function gridIDForLocation(lat, long) {
const query = `?key=${MAP_QUEST_API_KEY}&location=${lat},${long}`;
const url = STREETMAPS_WEBSITE + query;
console.log('Retrieving grid for', lat, long);
console.log('The overall url is', url);
let gridID;
await fetch(url)
.then(function(response) {
if (response.status !== 200) {
console.log('Error, resource unable to be retreived. Status Code:' + response.status);
return;
}
return response.json();
})
.then(function(data) {
gridID = data['results'][0]['locations'][0]['postalCode'].substring(0, 2);
return gridID;
})
.catch(function(err) {
console.error('Fetch Error:', err);
});
return Promise.resolve(gridID);
}
app.get('/grid/id/:lat/:long', (req, res) => {
const { lat, long } = req.params;
const gridID = gridIDForLocation(lat, long).then((gridID) => {
res.set('Content-Type', 'application/json');
res.send({ lat, long, grid_id: GRIDID_PREFIX + gridID });
});
});
app.listen(PORT, () => console.log(`Grid server listening on port ${PORT}`));
|
var Q = require('q');
var Options = require('../utils/options');
var ES5Class = require('es5class');
var _ = require('lodash');
var EventEmitter = require('events').EventEmitter;
var sprintf = require('sprintf').sprintf;
var mongoose = require('mongoose');
var WithSearchFields = ES5Class.$define('WithSearchField', {
withSearchString: function (field, term) {
if (!term) {
term = field;
}
this.on('req', function (req, query) {
query[term] = req.params[field];
});
this._route += sprintf("/:%s", field);
return this;
},
withSearchNumber: function (field) {
this.on('req', function (req, query) {
query[field] = parseInt(req.params[field], 10);
});
this._route += sprintf("/:%s", field);
return this;
}
});
var ServiceDsl = ES5Class.$define('ServiceDsl', {
construct: function (options) {
options = Options.for(options);
this._route = options.expect('route');
this._name = options.expect('name');
this.setProvider(options.default('name') || options.expect('provider'));
this.setFind(options.default('find', 'find'));
},
model: function () {
return this._provider(this._name);
},
route: function () {
return this._route;
},
justOne: function () {
this.setFind('findOne');
return this;
},
setProvider: function (provider) {
if (_.isString(provider)) {
this._provider = function () {
return mongoose.model(provider);
};
} else if (_.isFunction(provider)) {
this._provider = provider;
}
},
setFind: function (find) {
if (_.isString(find)) {
this._find = function (model, query) {
return model[find].call(model, query).exec();
};
} else if (_.isFunction(find)) {
this._find = find;
}
},
installTo: function (app) {
var operations = {
find: function(req, res) {
var query = {};
this.emit('req', req, query);
var model = this.model();
return Q(this._find(model, query))
.then(function (all) {
res.json(all);
})
.fail(function (err) {
res.send(err);
})
.finally(function () {
});
}.bind(this),
create: function (req, res) {
var data = req.body;
var model = this.model();
var defer = Q.defer();
model.create(data, function (err, data) {
if (err) {
defer.reject(err);
} else {
defer.resolve(data);
}
});
return defer.promise.then(function (all) {
res.json(all);
})
.fail(function (err) {
res.send(err);
})
.finally(function () {
});
}.bind(this),
update: function (req, res) {
operations.find(req, res)
.then(function () {
var model = this.model();
_(model).extend(req.body);
Q(model.save().exec())
.then(function (resp) {
res.json(model);
})
.fail(function (err) {
res.send(err);
})
.finally(function () {
});
}.bind(this));
}.bind(this)
};
var route = function (app, method, endpoint) {
app.route(this.route())[method](endpoint);
}.bind(this);
route(app, 'get', operations.find);
route(app, 'post', operations.create)
route(app, 'put', operations.update);
return this;
}
})
.$implement(EventEmitter)
.$implement(WithSearchFields);
exports.service = function (options) {
var dsl = ServiceDsl.$create(options);
return dsl;
}
|
/**
* Created by hridya on 2/16/16.
*/
(function()
{
angular
.module("FormBuilderApp")
.controller("FormController", formController);
function formController($scope, FormService, $location, $rootScope)
{
$scope.addForm = addForm;
$scope.removeForm = removeForm;
$scope.selectForm = selectForm;
$scope.updateForm = updateForm;
$scope.message = null;
$scope.newForm = {};
function updateForm(form)
{
if ($scope.selectedFormIndex == null) {
$scope.message = "Form needs to be selected before editing.";
return;
}
console.log(form);
var updatedForm = FormService.updateFormById(form._id, form);
//console.log(updatedForm);
if (!updatedForm) {
$scope.message = "Could not update the form.";
return;
}
$scope.message = null;
$scope.forms[$scope.selectedFormIndex].title = updatedForm.title;
}
function selectForm(index)
{
$scope.selectedFormIndex = index;
$scope.newForm = {
title: $scope.forms[index].title
};
}
function removeForm(form)
{
var index = $scope.forms.indexOf(form);
$scope.forms.splice(index, 1);
FormService.deleteFormById(form._id);
}
function addForm(form)
{
if (form == null) {
$scope.message = "Please provide a title for the form.";
return;
}
var newForm = FormService.createFormForUser($scope.currentUser.userId, form);
$scope.forms.push(newForm);
}
var forms = FormService.findAllFormsForUser($scope.currentUser._id);
$scope.forms = forms;
}
})();
|
/**
* Created by Administrator on 2016/6/30.
*/
$(function () {
});
|
import React from 'react';
import PropTypes from 'prop-types';
import Dialog from 'material-ui/Dialog';
import IconButton from 'material-ui/IconButton';
import SvgIcon from 'material-ui/SvgIcon';
import FlatButton from 'material-ui/FlatButton';
import { deleteDish } from 'actions/RestaurantActions';
const propTypes = {
dispatch: PropTypes.func.isRequired,
dish: PropTypes.object.isRequired,
};
const DeleteSVG = (props) => (
<SvgIcon color="#f44336" hoverColor="#e57373" {...props}>
<path d="M10,0 C4.47,0 0,4.47 0,10 C0,15.53 4.47,20 10,20 C15.53,20 20,15.53 20,10 C20,4.47 15.53,0 10,0 Z"></path>
<polygon id="Path" fill="#FFFFFF" points="15 13.59 13.59 15 10 11.41 6.41 15 5 13.59 8.59 10 5 6.41 6.41 5 10 8.59 13.59 5 15 6.41 11.41 10"></polygon>
</SvgIcon>
);
class DishDeleteButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
modalIsOpen: false,
};
this.closeModal = this.closeModal.bind(this);
this.openModal = this.openModal.bind(this);
this.deleteDish = this.deleteDish.bind(this);
}
openModal(e) {
e.stopPropagation();
this.setState({
modalIsOpen: true,
});
}
closeModal() {
this.setState({
modalIsOpen: false,
});
}
deleteDish(e) {
const { dispatch, dish } = this.props;
e.preventDefault();
dispatch(deleteDish(dish));
this.closeModal();
}
render() {
const { dish } = this.props;
const actions = [
<FlatButton
label="Cancel"
primary
onTouchTap={this.closeModal}
/>,
<FlatButton
label="Confirm"
secondary
onTouchTap={this.deleteDish}
/>,
];
return (
<div>
<IconButton style={{ position: 'absolute', top: -22, right: -25 }} onTouchTap={this.openModal}>
<DeleteSVG />
</IconButton>
<Dialog
title={`Delete Dish: ${dish.name}`}
actions={actions}
modal
open={this.state.modalIsOpen}
onRequestClose={this.closeModal}
>
Are you sure you wanna delete the dish {dish.name}
</Dialog>
</div>
);
}
}
DishDeleteButton.propTypes = propTypes;
export default DishDeleteButton;
|
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('The bot is ready and fired up for use!!')
})
client.on('ready', () => {
client.user.setStatus('available')
client.user.setPresence({
game: {
name: 'with my code',
type: "PLAYING",
url: "https://www.twitch.tv/MutedOreo"
}
});
});
client.on('message', async message => {
if(message.member.hasPermission(["MANAGE_NICKNAMES"])){
if(message.content.startsWith(`${prefix}nickset`)){
member.displayName.replace(message.content.replace`${prefix}nickset`, ''.trim());
}
}
if(message.member.hasPermission(["SEND_MESSAGES"])){
if(message.content.startsWith(`${prefix}sobble`)){
message.channel.send('More information about who made the bot is soon to follow.');
}
}
//Moderation & Fun Commands
if(message.member.hasPermission(["SEND_MESSAGES"])){
//if(message.content.startsWith(`${prefix}cat`)){
//message.channel.send('https://img.purch.com/w/660/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzEwNC84MTkvb3JpZ2luYWwvY3V0ZS1raXR0ZW4uanBn');
//}
if(message.content.startsWith(`${prefix}help`)){
message.channel.send('This is currently being worked on at this very moment.');
message.channel.send('But these are the current commands: e!sub [subreddit], e!invite, e!github, e!say [insert text], e!hidesay [insert text], e!kick [@ member], e!ban [@ member] & e!sobble.')
}
if(message.content.startsWith(`${prefix}sub`)){
message.channel.send('Have fun on this subreddit! https://www.reddit.com/r/' + message.content.replace(`${[prefix]}sub`, '').trim());
}
if(message.content.startsWith(`${prefix}invite`)){
message.channel.send('You can invite me to other servers using this link: https://bit.ly/2F2R4VP');
}
if(message.content.startsWith(`${prefix}github`)){
message.channel.send('This is the github repo: https://github.com/Spyrincho/BeanHammerDiscordBot ');
}
if(message.content.startsWith(`${prefix}say`)){
message.channel.sendMessage(`<@`+message.author.id+`>` + " said: " + '"' + message.content.replace(`${prefix}say`,'').trim() + '"');
}
if(message.content.startsWith(`${prefix}hidesay`)){
message.delete();
message.channel.sendMessage(`Anonymous` + " said: " + '"' + message.content.replace(`${prefix}hidesay`,'').trim() + '"');
}
}
//Kick & Ban Function
if(message.member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS'])) {
//console.log(message.content);
if(message.content.startsWith(`${prefix}kick`)) {
//message.channel.send("kick")
let member = message.mentions.members.first();
member.kick().then((member) => {
message.channel.send(":wave: " + member.displayName + " has been yeeted out of the fucking universe!")
})
}
if(message.content.startsWith(`${prefix}ban`)) {
//message.channel.send("ban")
let member = message.mentions.members.first();
member.ban().then((member) => {
message.channel.send(":wave: " + member.displayName + " has been yeeted out of the fucking universe and will never return!")
})
}
}
})
client.login(token);
|
//// six anchor char, ^ $ \b \B (?=p) (?!p)
//// ES6 also has (?<=p) (?<!p)
//// 位置只是一个空字符,而不是获取某个位置上操作字符串的值
//// 例如: "hello".match(/(?=ell)/),仅仅是获取`e`前的位置,而不是字符`h`
// test position feature
// can be seen as null char, but can't only for thier own place
// 可以视作空字符,但是只有在他们自己的位置上才可。
// 例如,把 ^ & 加到正则表达式中间,则其不为空字符
var pat = /^^^^hello$$/
console.log(pat.test("hello")) //=>true
pat = /^he^^ll$o$$/
console.log(pat.test("he^^ll$o")) //=>false
pat = /^hello/g
console.log("hello123".match(pat))
pat = /^^^hello/g
console.log("hello123".match(pat))
pat = /hello$/g
console.log("123hello".match(pat))
var result = "hello".replace(/^|$/g, '#');
console.log(result);
// 位置的含义
pat = /(?=ell)/
console.log("hello".match(pat))
console.log("hello".replace(pat, '#'))
pat = /(?=he)^^he(?=\w)llo$\b\b$/g
console.log("hello".match(pat))
// 数字分段
var s = "123456789"
// 先尝试
console.log(s.match(/\d{3}/g)) // => [ '123', '456', '789' ]
console.log(s.match(/(\d{3})+$/g)) // => [ '123456789' ]
console.log(s.match(/(\d{3})+/g)) // => [ '123456789' ]
console.log(s.match(/(?=(\d{3}))/g)) // => [ '', '', '', '', '', '', '' ]
// console.log(s.replace(/(?=(\d{3}))/g, "#"))
console.log(s.match(/(?=(\d{3})+)/g)) // => [ '', '', '', '', '', '', '' ]
console.log(s.match(/(?=(\d{3})+$)/g)) // => [ '', '', '' ]
// 综上可知, 正常情况下 /(\d{3})+/会进行贪婪匹配
// 但是 锚字符 使得其进行懒惰匹配。为什么会获取到7个位置? 因为默认从`7`开始获取每个字符串前的位置,`789`正好匹配,接着是`678`,......
// 当设置了开始匹配的起点时,就只获取到了3个位置。这是因为`?=`后正则表达式的意义有所变化,`(\d{3})+)`和 `(\d{3})+$)`意义明显不同
pat = /(?!^)(?=(\d{3})+$)/g
// 获取3个数字之前的一个位置,该位置前还有一个位置,且其不在 字符串开头(^)之前。
console.log(s.replace(pat, ",")) // => 123,456,789
// 我们还可以添加
// 获取3个数字之前的一个位置,该位置前还有一个位置,且其不在4之前, 在该位置之前还有一个位置, 且其不在 字符串开头(^)之前。
// 其实,三个位置后面的值是同一个。 例如 "234", 在2和3之间可以有无数个位置。
pat = /(?!^)(?!4)(?=(\d{3})+$)/g
console.log(s.replace(pat, ",")) // => 123456,789
// 考虑位置字符和其他正则表达式组合
var p_pat_1 = /^[0-9A-Za-z]{6,12}$/
console.log(p_pat_1.test("aAaaabz")) // => true
console.log(p_pat_1.test("123233Az,")) // => false
// 考虑以下两种方式的区别
// p_pat_2 表示 开头位置之前,还有一个位置,该位置后面紧跟了一个数字
// p_pat_3 表示 开头位置之前,还有一个位置,该位置后面紧跟了一个字符串,其中包含一个数字
var p_pat_2 = /(?=[0-9])(^[0-9A-Za-z]{6,12}$)/g
var p_pat_3 = /(?=.*[0-9])(^[0-9A-Za-z]{6,12}$)/g
console.log(p_pat_2.test("aA2aaabz")) // => false
console.log(p_pat_3.test("aA3aaabz")) // => true
// 默认为模糊匹配
// 精确匹配需要使用^和$搭配
var h_pat = /\d/
console.log(h_pat.test("2")) // =>true
console.log(h_pat.test("2345")) // =>true
console.log(h_pat.test("hello 2 world")) // =>true. 匹配到了2
// 多个分组的关系
// 先匹配前一个分组,从操作字符串匹配完第一个分组的位置后,继续匹配下一个分组
var group_pat_1 = /^[A-Za-z0-9]{6,8}$/
var group_pat_2 = /^\w{6,8}$/
var group_pat = /(^[A-Za-z0-9]{6,8}$)(^\w{6,8}$)/
var group_pat_normal = /([A-Za-z0-9]{6,8})(\w{6,8})/
console.log(group_pat_1.test("Asd1234"))
console.log(group_pat_2.test("Asd1234"))
console.log(group_pat.test("Asd1234")) // =>false
console.log(group_pat_normal.test("Asd1234")) // =>false
// 我们来写一下密码的正则表达式吧
// 使用 (?=p)
var p_pat = /(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])^[0-9a-zA-Z]{6,12}$/
console.log(p_pat.test("aaabbb")) // 只包含小写字母 false
console.log(p_pat.test("AAABBB")) // 只包含大写字母 false
console.log(p_pat.test("112233")) // 只包含数字 false
console.log(p_pat.test("123Abc")) // 同时包含 true
// 使用 (?!p)
p_pat = /(?!^[0-9]{6,12}$)(?!^[a-z]{6,12}$)(?!^[A-Z]{6,12}$)^[0-9A-Za-z]{6,12}$/
|
//react built-int components
import React, { Component } from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
//authentication handling
import * as actions from './store/actions/auth';
//libraries
import 'antd/dist/antd.css';
import { connect } from 'react-redux';
//components
import BaseRouter from './BaseRouter';
import CustomLayout from './components/CustomLayout';
//developer mode (set to false when building)
const development_mode = false;
class App extends Component {
componentDidMount() {
this.props.onTryAutoSignin();
}
render() {
return (
<div>
<Router>
<CustomLayout {...this.props}>
<BaseRouter />
</CustomLayout>
</Router>
</div>
);
}
}
const mapStateToProps = state => {
if (development_mode){
return {
isAuthenticated: true
}
}
return {
isAuthenticated: state.token !== null
}
}
const mapDispatchToProps = dispatch => {
return {
onTryAutoSignin: () => dispatch(actions.authCheckState())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
// Copyright (c) 2016-2018, BuckyCloud, Inc. and other BDT contributors.
// The BDT project is supported by the GeekChain Foundation.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the BDT nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'use strict';
const Base = require('../base/base.js');
const {Config, HashDistance, TOTAL_KEY} = require('./util.js');
const BaseUtil = require('../base/util.js');
const TimeHelper = BaseUtil.TimeHelper;
const LOG_INFO = Base.BX_INFO;
const LOG_WARN = Base.BX_WARN;
const LOG_DEBUG = Base.BX_DEBUG;
const LOG_CHECK = Base.BX_CHECK;
const LOG_ASSERT = Base.BX_ASSERT;
const LOG_ERROR = Base.BX_ERROR;
const ValueTableConfig = Config.ValueTable;
const HashConfig = Config.Hash;
class DistributedValueTableMgr {
constructor({ appid = 0,
TABLE_COUNT = ValueTableConfig.TableCount,
TABLE_SIZE = ValueTableConfig.TableSize,
TIMEOUT_MS = ValueTableConfig.ValueTimeoutMS } = {}) {
this.TABLE_COUNT = TABLE_COUNT;
this.TABLE_SIZE = TABLE_SIZE;
this.TIMEOUT_MS = TIMEOUT_MS;
// <tableName, table>
this.m_tables = new Map();
this.m_earlyUpdateTime = 0;
this.m_appid = appid;
}
updateValue(tableName, keyName, value) {
let table = this.m_tables.get(tableName);
if (!table) {
table = new DistributedValueTable(this);
this.m_tables.set(tableName, table);
}
table.updateValue(keyName, value);
}
clearOuttimeValues() {
let now = TimeHelper.uptimeMS();
if (now - this.m_earlyUpdateTime <= this.TIMEOUT_MS) {
return;
}
this.m_earlyUpdateTime = now;
if (this.m_tables.size > this.TABLE_COUNT) {
let outtimeTableList = [];
this.m_tables.forEach((table, tableName) => {
if (now - table.lastUpdateTime > this.TIMEOUT_MS) {
outtimeTableList.push(tableName);
}
});
outtimeTableList.forEach(tableName => this.m_tables.delete(tableName));
}
this.m_tables.forEach((table) => {
if (now - table.earlyUpdateTime > this.TIMEOUT_MS) {
table.knockOut(this.TABLE_SIZE, this.TIMEOUT_MS);
}
if (table.earlyUpdateTime < this.m_earlyUpdateTime) {
this.m_earlyUpdateTime = table.earlyUpdateTime;
}
});
}
get tableCount() {
return this.m_tables.size;
}
get valueCount() {
let count = 0;
this.m_tables.forEach(table => count += table.valueCount);
return count;
}
findValue(tableName, keyName) {
let table = this.m_tables.get(tableName);
if (table) {
return table.findValue(keyName);
}
return null;
}
findClosestValues(tableName, keyName, {count = ValueTableConfig.FindCloseKeyCount, maxDistance = HashDistance.MAX_HASH} = {}) {
let table = this.m_tables.get(tableName);
if (table) {
return table.findClosestValues(keyName, {count, maxDistance});
}
return null;
}
findLatestValues(tableName, keyName, {count = ValueTableConfig.FindCloseKeyCount, maxDistance = HashDistance.MAX_HASH} = {}) {
let table = this.m_tables.get(tableName);
if (table) {
return table.findLatestValues(keyName, {count, maxDistance});
}
return null;
}
forEachValue(valueProcess) {
for (let [tableName, table] of this.m_tables) {
for (let [keyName, valueObj] of table.values) {
valueProcess(tableName, keyName, valueObj);
}
}
}
log() {
for (let [tableName, table] of this.m_tables) {
LOG_DEBUG(`[DHT${this.m_appid}] Table(${tableName}) count(${table.values.size}):`);
for (let [keyName, valueObj] of table.values) {
LOG_DEBUG(`\t${keyName}\t${valueObj.value}`);
}
}
}
}
class DistributedValueTable {
constructor(owner) {
this.m_values = new Map();
this.m_earlyUpdateTime = 0;
this.m_lastUpdateTime = 0;
this.m_owner = owner;
}
get values() {
return this.m_values;
}
get valueCount() {
return this.m_values.size;
}
get earlyUpdateTime() {
if (this.m_earlyUpdateTime === 0) {
let now = TimeHelper.uptimeMS();
this.m_earlyUpdateTime = now;
this.m_values.forEach((valueObj, keyName) => {
if (valueObj.updateTime < this.m_earlyUpdateTime) {
this.m_earlyUpdateTime = valueObj.updateTime;
}
});
}
return this.m_earlyUpdateTime;
}
get lastUpdateTime() {
return this.m_lastUpdateTime;
}
updateValue(keyName, value) {
let now = TimeHelper.uptimeMS();
let valueObj = this.m_values.get(keyName);
if (!valueObj) {
valueObj = {
value: value,
keyHash: HashDistance.checkHash(keyName),
updateTime: now,
};
this.m_values.set(keyName, valueObj);
} else {
if (this.m_earlyUpdateTime === valueObj.updateTime) {
this.m_earlyUpdateTime = this.earlyUpdateTime;
}
valueObj.value = value;
valueObj.updateTime = now;
}
this.m_lastUpdateTime = now;
}
knockOut(timeoutMS) {
let now = TimeHelper.uptimeMS();
this.m_earlyUpdateTime = now;
// timeout
let outtimeKeyList = [];
this.m_values.forEach((valueObj, keyName) => {
if (now - valueObj.updateTime > timeoutMS) {
outtimeKeyList.push(keyName);
} else if (valueObj.updateTime < this.m_earlyUpdateTime) {
this.m_earlyUpdateTime = valueObj.updateTime;
}
});
outtimeKeyList.forEach(keyName => this.m_values.delete(keyName));
}
findValue(keyName) {
if (keyName === TOTAL_KEY) {
let keyValues = new Map();
this.m_values.forEach((valueObj, key) => keyValues.set(key, valueObj.value));
return keyValues;
}
let valueObj = this.m_values.get(keyName);
if (valueObj) {
return new Map([[keyName, valueObj.value]]);
}
return null;
}
findClosestValues(keyName, {count = ValueTableConfig.FindCloseKeyCount, maxDistance = HashDistance.MAX_HASH} = {}) {
LOG_ASSERT(count >= 0, `[DHT${this.m_owner.m_appid}] Try find negative(${count}) values.`);
if (count < 0) {
return new Map();
}
let hash = HashDistance.checkHash(keyName);
let foundValueList = [];
for (let [key, valueObj] of this.m_values) {
let curValueDistance = HashDistance.calcDistanceByHash(valueObj.keyHash, hash);
if (HashDistance.compareHash(curValueDistance, maxDistance) > 0) {
continue;
}
let farthestValue = foundValueList.length > 0? foundValueList[foundValueList.length - 1] : null;
if (foundValueList.length < count
|| HashDistance.compareHash(curValueDistance, HashDistance.calcDistanceByHash(farthestValue.valueObj.keyHash, hash)) < 0) {
let done = false;
for (let j = 0; j < foundValueList.length; j++) {
if (HashDistance.compareHash(curValueDistance, HashDistance.calcDistanceByHash(foundValueList[j].valueObj.keyHash, hash)) < 0) {
foundValueList.splice(j, 0, {valueObj, key});
done = true;
if (foundValueList.length > count) {
foundValueList.pop();
}
break;
}
}
if (!done) {
foundValueList.push({valueObj, key});
}
}
}
let foundValueTable = new Map();
foundValueList.forEach(item => foundValueTable.set(item.key, item.valueObj.value));
return foundValueTable;
}
findLatestValues(keyName, {count = ValueTableConfig.FindCloseKeyCount, maxDistance = HashDistance.MAX_HASH} = {}) {
LOG_ASSERT(count >= 0, `[DHT${this.m_appid}] Try find negative(${count}) values.`);
if (count < 0) {
return new Map();
}
let hash = HashDistance.checkHash(keyName);
let foundValueList = [];
for (let [key, valueObj] of this.m_values) {
let curValueDistance = HashDistance.calcDistanceByHash(valueObj.keyHash, hash);
if (HashDistance.compareHash(curValueDistance, maxDistance) > 0) {
continue;
}
let latestValue = foundValueList.length > 0? foundValueList[foundValueList.length - 1] : null;
if (foundValueList.length < count
|| valueObj.updateTime < latestValue.valueObj.updateTime) {
let done = false;
for (let j = 0; j < foundValueList.length; j++) {
if (valueObj.updateTime < foundValueList[j].valueObj.updateTime) {
foundValueList.splice(j, 0, {valueObj, key});
done = true;
if (foundValueList.length > count) {
foundValueList.pop();
}
break;
}
}
if (!done) {
foundValueList.push({valueObj, key});
}
}
}
let foundValueTable = new Map();
foundValueList.forEach(item => foundValueTable.set(item.key, item.valueObj.value));
return foundValueTable;
}}
module.exports = DistributedValueTableMgr; |
import React from 'react'
import beer from '../../images/paintings/beer.jpg'
import PaintingsComponent from "../../components/paintings_component";
const Beer = () => (
<PaintingsComponent image={beer} title={'Beer'}>
<p>Lithographic print</p>
</PaintingsComponent>
)
export default Beer
|
// GLOBALS
var renderer, scene, camera, controls, cameraControl, stats, rotation; // common 3js stuff
var controls, gui, camReset; // gui controller
var context, sourceNode, analyser, analyser2; // common webAudio API stuff
var waveHolder, boxW, boxH, boxAspect, canvas, getDist, drawW; // html template elts
// vars specific to this sketch
var waveShape, waveGeom, waveMat, waveMesh;
var leftEdge, rightEdge, topEdge, bottomEdge; // outer limits of projection matrix
var pause = false;
function initLPCMesh() {
$('#lpcMesh').addClass('select');
window.addEventListener('resize', handleResize, false);
//$('header').on('click', pauseUpdate);
// get DOM ele & dimensions for canvas
waveHolder = document.getElementById("waveHolder");
boxW = waveHolder.clientWidth;
boxH = waveHolder.clientHeight;
boxAspect = boxW / boxH;
console.log("boxW: " + boxW+", boxH: "+ boxH);
// weird but it works (in other words it gives me Processing-style coords)
var zCamScale = 2.55;
leftEdge = boxW/-zCamScale;
rightEdge = boxW/zCamScale;
topEdge = boxH/zCamScale;
bottomEdge = boxH/-zCamScale;
// CREATE SCENE & CAM OBJ
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(45, boxAspect, 1, 1000);
camera.position.set(0, 0, 500);
camera.lookAt(scene.position);
//tried to view a flat plane with 0,0 in the center. it didn't work.
//camera = new THREE.OrthographicCamera(boxW/-2, boxW/2, boxH/-2, boxH/2, 1, 1000);
// RENDERER
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xc5f3ff, 1.0);
renderer.setSize(boxW, boxH);
// Add the output of the renderer to the html
canvas = renderer.domElement; // create an ele to hold the renderer
canvas.id = "lpc-canvas"; // just in case
waveHolder.appendChild(canvas);
// SHAPES (see particle maker)
// Graphics are data-driven, in other words they are drawn in the update and render loops. There is no geometry to establish here. */
// debugger plane to check my orientation
/*
var planeGeometry = new THREE.PlaneGeometry(boxW, 500);
var planeMaterial = new THREE.MeshLambertMaterial({color: 0x018B9D }); //{color: 0x53C8E9 }
var plane = new THREE.Mesh(planeGeometry, planeMaterial);
//plane.rotation.x = -0.5 * Math.PI; // this makes the plane lie flat
plane.position.set(0,0,-500);
//plane.position.z = -500; this is the farthest back it can go (cam is at +500, and there is only a 1000 range)
scene.add(plane);
*/
// LIGTHING (n/a)
var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(0, 100, 300);
scene.add(directionalLight);
directionalLight.castShadow = true;
// subtle ambient light
var ambientLight = new THREE.AmbientLight(0xFFFFFF, 0.35);
scene.add(ambientLight);
// BACKGROUND SCENE (n/a)
// GUI, STATS, & DEBUGGERS
initAxes();
initStatsObject();
initGUIctrl();
// AUDIO (n/a)
// EFFECTS COMPOSER (n/a)
// RENDER
render();
//console.log('initLPC says hello!');
} // end initLPC()
// GUI CONTROLLER ===================================================
function initStatsObject() {
stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '10px';
stats.domElement.style.top = '10px'; // 0px places it after the canvas.
waveHolder.appendChild(stats.domElement);
}
function initGUIctrl() {
controls = new function () {
this.cameraX =0;
this.cameraY =0;
this.cameraZ =0;
this.cameraReset = function() {
this.cameraX =0;
this.cameraY =0;
this.cameraZ =0;
camera.lookAt(scene.position);
}
this.pauseWave = function() { //
if(pause === false) {
pause = true;
console.log('wave is paused. c is ' + c);
} else {
pause = false;
console.log('wave is running');
}
}
}
var gui = new dat.GUI();
gui.add(controls, 'cameraX', -0.5,0.5); //.step(0.01);
gui.add(controls, 'cameraY', -0.5,0.5); //.step(0.001);
gui.add(controls, 'cameraZ', -0.5,0.5);
gui.add(controls, 'cameraReset').listen();
gui.add(controls, 'pauseWave').listen();
}
function initAxes() {
// axes: x = red, y = green , z = blue
var axes = new THREE.AxisHelper(100);
scene.add(axes);
}
// MATERIAL MAKERS ===================================================
var waveMat = new THREE.MeshBasicMaterial({ color: 0x53C8E9 });
var peakMat = new THREE.LineBasicMaterial({ color: 0x018B9D });
// SHAPE MAKER ===========================================
var peaks, points, frequencyScaling; // prop/arrays in audio data msg obj
var line, peakSegments; // THREE graphic elements
// recieves dummmy data from getDummyLPCCoefficients()
function lpcCoefficientCallback(msg) {
points = msg.coefficients;
peaks = msg.freqPeaks;
frequencyScaling = msg.freqScale;
simples = msg.simple;
//console.log(simples);
var shapeArr = [];
shapeArr.length = points.length + 4; //
//shapeArr.length = simples.length + 4;
// constant drawing positions
var drawW = Math.abs(leftEdge-rightEdge); // drawing width
var pointSteps = drawW/(points.length + 1); // spacing b/t pts
//var pointSteps = drawW/(simples.length + 1); // spacing b/t pts
//Note: For some reason moveTo & lineTo won't take Vector3s
var shapeStart = new THREE.Vector2(leftEdge, bottomEdge); // start shape
var waveStart = new THREE.Vector2(leftEdge, 0); //start wave
var waveEnd = new THREE.Vector2(rightEdge, 0); //end wave
var shapeEnd = new THREE.Vector2(rightEdge, bottomEdge); // close shape
// make vertices (vertices arr is necessary for verticesNeedUpdate util)
shapeArr[0] = shapeStart;
shapeArr[1] = waveStart;
for (var i=0; i<shapeArr.length-4; i++) {
//var point = simples[i] * 1000;
var point = points[i] * 1000;
//var px = linScale(i*frequencyScaling, 0, points.length-1, boxW/-2, boxW/2); //#q check w/ sam
var px = leftEdge + ((i+1) * pointSteps);
shapeArr[2 + i] = new THREE.Vector3(px, point);
}
shapeArr[shapeArr.length - 2] = waveEnd;
shapeArr[shapeArr.length - 1] = shapeEnd;
// draw wave shape
waveShape = new THREE.Shape();
//give wave shape a name //#hc
for(var i=0; i<shapeArr.length; i++) {
if (i == 0) {
waveShape.moveTo(shapeArr[i].x, shapeArr[i].y);
} else {
waveShape.lineTo(shapeArr[i].x, shapeArr[i].y);
}
};
if (waveGeom === undefined) {
waveGeom = new THREE.ShapeGeometry(waveShape);
} else {
waveGeom = null;
waveGeom = new THREE.ShapeGeometry(waveShape);
//console.log(waveGeom);
}
var mesh = scene.getObjectByName('wave');
if (mesh === undefined) {
waveMesh = new THREE.Mesh(waveGeom, waveMat);
//console.log(waveMesh.geometry.vertices);
//addBallVertices(waveMesh);
waveMesh.name = "wave";
waveMesh.geometry.dynamic = true;
waveMesh.geometry.verticesNeedUpdate = true;
scene.add( waveMesh );
} else {
scene.remove(scene.getObjectByName("wave"));
//scene.remove(scene.getObjectByName("balls"));
waveMesh = new THREE.Mesh(waveGeom, waveMat);
waveMesh.name = "wave";
//addBallVertices(waveMesh);
scene.add( waveMesh );
/* why why why why doesn't this work
for (i=0; i < mesh.geometry.vertices.length; i++) {
mesh.geometry.vertices[i].y = shapeArr[i].y;
}
mesh.geometry.vertices.forEach(function (vertices) {
//mesh.geometry.vertices[i].y = shapeArr[i].y;
});
*/
}
/* Sam's Code
if (line === undefined) {
var material = new THREE.LineBasicMaterial({
color: 0x53C8E9 //0x0000ff //#hc
});
var geometry = new THREE.Geometry();
// this makes a line of points w/ x vals that go from -357 to 1213
for (var i=0; i<points.length; i++) {
var point = points[i];
var px = linScale(i*frequencyScaling, 0, points.length-1, boxW/-2, boxW/2); //music math stuff i guess
geometry.vertices.push(new THREE.Vector3(px, 0, 0)); //just an xpos
//geometry.vertices.push(new THREE.Vector3(0, px, 0)); // #st why doesn't this work
}
line = new THREE.Line(geometry, material);
line.geometry.dynamic = true; // this means that the line geom can recieve an update
scene.add(line);
}
*/
//var mesh = scene.getObjectByName('wave');
if (peakSegments === undefined) {
var geometry = new THREE.Geometry();
//console.log(peaks);
peakSegments = new THREE.LineSegments(geometry, peakMat);
peakSegments.geometry.verticesNeedUpdate = true;
scene.add(peakSegments);
} else {
var geometry = new THREE.Geometry();
var shapePeaks = shapeArr.slice(2, shapeArr.length - 2);
//console.log(shapePeaks.length);
for (var i=0; i<peaks.length; i++) {
if (peaks[i] === 1) {
var v1 = new THREE.Vector3(shapePeaks[i].x, bottomEdge, 1); //base
var v2 = new THREE.Vector3(shapePeaks[i].x, (shapePeaks[i].y-2), 1); //top
geometry.vertices.push(v1);
geometry.vertices.push(v2);
}
peakSegments.geometry = geometry;
peakSegments.geometry.verticesNeedUpdate = true;
}
}
} // end lpcCoefficientCallback()
// DONT DO THIS. unless you also remove 'em all
function addBallVertices(mesh) {
var vertices = mesh.geometry.vertices;
var vertexMaterial = new THREE.MeshLambertMaterial({color:0x00ffff});
// put a sphere on ea. vertex
for (i=0; i<vertices.length; i++) {
var vertex = vertices[i];
var vertexSphere = new THREE.SphereGeometry(3);
var vertexMesh = new THREE.Mesh(vertexSphere, vertexMaterial);
vertexMesh.position.set(vertex.x, vertex.y, vertex.z);
vertexMesh.name = "balls";
scene.add(vertexMesh);
}
}
// AUDIO SETUP ============================================================
/* These just generate new lpc data. It is called at every render cycle and passes the data to lpcCoefficientCallback(), which maps the audio data to THREE geometry. */
var dummyPointCount = 256;
var dummyPoints = [];
for (var i=0; i<dummyPointCount; i++)
dummyPoints.push(0);
var dummyNoisiness = 0.05
// #hc
var simplePointCount = 10;
var simplePoints = [];
for (var i=0; i<simplePointCount; i++) {
simplePoints.push(0);
}
function linScale(v, inlow, inhigh, outlow, outhigh) {
var range = outhigh - outlow;
var domain = inhigh - inlow;
var ov = (v - inlow) / domain;
ov = (ov * range) + outlow;
return ov;
}
function getDummyLPCCoefficients(cb) {
var msg = {};
msg.coefficients = [];
msg.freqPeaks = [];
msg.simple = simplePoints;//#hc
var pointCount = simplePointCount; //#hc
// clean it out
for (var i=0; i<pointCount; i++) {
simplePoints[i] = 0;
}
// fill it up
for (var i=0; i<pointCount; i++) {
if (i==0 || i==(pointCount-1))
simplePoints[i] = 0;
else {
var p = (Math.random() - 0.5) * dummyNoisiness;
simplePoints[i] = simplePoints[i] + p;
}
}
var pointCount = dummyPointCount;
for (var i=0; i<pointCount; i++) {
dummyPoints[i] = 0;
}
for (var i=0; i<pointCount; i++) {
if (i==0 || i==(pointCount-1))
dummyPoints[i] = 0;
else {
var p = (Math.random() - 0.5) * dummyNoisiness;
dummyPoints[i] = dummyPoints[i] + p;
}
}
for (var i=0; i<pointCount; i++) {
if (i==0 || i==(pointCount-1))
msg.coefficients.push(dummyPoints[i])
else {
var vrg = dummyPoints[i-1] + dummyPoints[i] + dummyPoints[i+1]
msg.coefficients.push(vrg/3);
}
}
for (var i=0; i<pointCount; i++) {
if (i>0 && i<(pointCount-1)) {
if (dummyPoints[i-1] > dummyPoints[i] && dummyPoints[i] < dummyPoints[i+1]) {
/* msg.freqPeaks.push({
X: linScale(i, 0, pointCount-1, -1, 1),
Y: msg.coefficients[i]
}); */
msg.freqPeaks[i] = 1;
} else {
msg.freqPeaks[i] = 0;
}
}
}
msg.freqScale = 2.2;
if (cb)
cb(msg);
}
// UPDATE =================================================================
/* Update() draws the waves at each render cycle
*/
function updateWaves() {
/*
var WIDTH = renderer.getSize().width;
var HEIGHT = renderer.getSize().height;
if (line !== undefined) {
for (var i=0; i<points.length; i++) {
var px = linScale(i*frequencyScaling, 0, points.length-1, WIDTH/-2, WIDTH/2);
var py = linScale(points[i], 1, -1, HEIGHT/-2, HEIGHT/2);
line.geometry.vertices[i].set(px, py, 0);
}
line.geometry.verticesNeedUpdate = true;
}
if (peaks !== undefined) {
var geometry = new THREE.Geometry();
for (var i=0; i<peaks.length; i++) {
var peak = peaks[i];
var px = linScale(peak.X, -1, 1, 0, frequencyScaling);
px = linScale(px, 0, 1, WIDTH/-2, WIDTH/2);
var py = linScale(peak.Y, 1, -1, HEIGHT/-2, HEIGHT/2);
var v1 = new THREE.Vector3(px, py, 1);
var v2 = new THREE.Vector3(px, HEIGHT/2, 1);
geometry.vertices.push(v1);
geometry.vertices.push(v2);
}
peakSegments.geometry = geometry;
peakSegments.geometry.verticesNeedUpdate = true;
}
*/
};
// RENDER ======================================================
var c = 0; // cycle
var x = 0; // unpause counter
function render() {
// render vars (n/a)
// object motion (n/a)
// camera motion (n/a)
scene.rotation.x = controls.cameraX * Math.PI;
scene.rotation.y = controls.cameraY * Math.PI;
scene.rotation.z = controls.cameraZ * Math.PI;
// data updates
stats.update();
//getDummyLPCCoefficients(lpcCoefficientCallback);
// if pause is false, let it run for 5 cycles
//if(pause === false && x < 5) {
if(pause === false) {
//console.log('running. c= ' + c);
getDummyLPCCoefficients(lpcCoefficientCallback);
//updateWaves();
};
x++;
if (x == 5) {
//pause = true;
x = 0;
};
c++;
// render the scene
renderer.render(scene, camera);
requestAnimationFrame(render);
//}
}
// MISC UTILS ======================================================
function handleResize() {
waveHolder = document.getElementById("waveHolder");
boxW = waveHolder.clientWidth;
boxH = waveHolder.clientHeight;
boxAspect = boxW / boxH;
renderer.setSize(boxW, boxH);
camera.aspect = boxAspect; // this only works for perspective cam
//camera.left = -boxW/2; //ortho cam
//camera.right = boxW/2; //ortho cam
//camera.top = -boxH/2; //ortho cam
//camera.bottom = boxH/2; //ortho cam
camera.updateProjectionMatrix();
}
function pauseUpdate() {
if(pause === false) {
pause = true;
console.log('wave is paused. c is ' + c);
} else {
pause = false;
console.log('wave is running');
}
}
function getDist(leftEdge, rightEdge) {
return Math.abs(leftEdge-rightEdge);
}
|
import React from 'react';
import ProductDetailContainer from '@/web-client/components/ShopProductDetail';
import Link from '@/web-client/components/Link';
import styles from '@/web-client/components/ShopProductDetailPage/ShopProductDetailPage.css';
const ShopProductDetailPage = ({productId}) => (
<div className={styles.container}>
<h1 className={styles.heading}>Product Detail</h1>
<nav className={styles.navigation}>
<ol className={styles.navigationList}>
<li className={styles.navigationListItem}>
<Link
className={styles.navigationLink}
href='/products'>
Products
</Link>
</li>
<li className={styles.navigationListItem}>Product Detail</li>
</ol>
</nav>
<div className={styles.detailContainer}>
<ProductDetailContainer productId={productId}/>
</div>
</div>
);
export default ShopProductDetailPage; |
import { Utils } from '../core/Utils.js';
import { KeyFlag } from './KeyFlag.js';
export class KeyAudio extends KeyFlag {
constructor( f, name ) {
super( f, name )
this.totalFrame = 0;
this.buffer = null;
this.source = null;
this.key.style.borderLeft = '1px solid ' + this.co[0];
this.key.style.borderRight = '1px solid ' + this.co[0];
this.cct = 'borderColor';
this.key.style.background = 'none';
this.flagName.onChange( function(v){ this.value = v; Utils.loadSound(this.value, this) }.bind(this) );
if( this.value ) Utils.loadSound( this.value, this );
}
play( f ) {
if(f>=this.frame && f<this.frame+this.totalFrame && this.source === null ) this.connect( f );
}
stop() {
if( this.source === null ) return
this.source.stop(0);
this.source = null;
}
connect( f ) {
if(!this.buffer) return;
// if( single ) this.stop();
this.source = Utils.Sound.createBufferSource();
this.source.buffer = this.buffer;
this.source.connect( Utils.Sound.destination );
let start = this.frame * this.parent.parent.frameTime;
let begin = ( f - this.frame ) * this.parent.parent.frameTime;
//source.start( start, bigin, NEO.frameTime );
//if( single ) source.start( start, begin, NEO.frameTime );
//else
this.source.start( start, begin );
}
clear(){
this.flagName.clear();
super.clear()
}
reSize( w ){
super.reSize( w )
this.flagName.c[0].style.left = this.sx + 'px';
let max = ~~(this.w * this.totalFrame);
this.key.style.width = (max+2) + 'px';
}
} |
/**
* Created by benben on 17/3/3.
*/
const getProvincelist = (province): Action => (dispatch) => {
dispatch({
type: 'ADDRESS',
province: province
})
}
const getcitylist = (city) => ({
type: 'ADDRESSCITY',
city: city
})
const getdiqulist = (diqu) => ({
type: 'ADDRESSDIQU',
diqu: diqu
})
const selPro = (province): Action => (dispatch) => {
dispatch({
type: 'PROVINCE',
selpro: province
})
}
const selcity = (city): Action => (dispatch) => {
dispatch({
type: 'CITY',
selcity: city
})
}
const seldiqu = (city): Action => (dispatch) => {
dispatch({
type: 'DIQU',
seldiqu: city
})
}
export {
getProvincelist,
selPro,
getcitylist,
selcity,
getdiqulist,
seldiqu
} |
const program = require('commander');
const util = require('./util');
program
.description('Get SmartContract Object from storage', {
key: 'Path (key) of the object to get'
})
.arguments('<key>')
.option('-c, --smartContractId [smartContractId]', '(required if not running in a smart contract) Which contract heap to get from')
.option('-v, --verbose', '(optional) Enable STDOUT logger in your Dragonchain SDK')
.option('-i, --dragonchainId [dragonchainID]', '(optional) Override the default dragonchain ID for this command')
.parse(process.argv);
util.wrapper(program, async client => {
const [key] = program.args;
if (!key) throw new Error('Parameter "key" is required.');
const { smartContractId } = program;
const params = util.removeUndefined({ key, smartContractId });
console.log(JSON.stringify(await client.getSmartContractObject(params), null, 2));
});
|
var searchData=
[
['loglevel',['LogLevel',['../logging_8h.html#aca1fd1d8935433e6ba2e3918214e07f9',1,'logging.h']]],
['lookuptype',['LookupType',['../mutt_2charset_8h.html#a677743e89f8cc2c57a0e6e91a47bdc4a',1,'charset.h']]]
];
|
class HelpCommand extends Command {
constructor() {
super("help", "Show the help messages.");
}
onExecute(arg) {
const value = [
`Prefix ${c.match(":")} to execute command (:help, etc)`,
`Prefix ${c.match("!")} to search packages exclusively`,
];
return this.wrap(value);
}
} |
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// schema for a Report
const schema = new Schema({
patientInitials: {
type: String,
required: true
},
visitDate: {
type: String
},
arrivalTime: {
type: String
},
departureTime: {
type: String
},
visitTimeLength: {
type: String
}
});
module.exports = mongoose.model('Report', schema);
|
/*
Pedir um número ao usuário e verificar se é maior ou menor que 100, informar na tela a resposta.
*/
var numero = parseInt(prompt("Digite um numero"));
if (numero > 100) {
document.write("Este numero e maior que 100!");
} else {
document.write("Este numero e menor que 100!");
} |
import Link from "next/link";
export function PageButton({ src, children }) {
return (
<button className="mx-2 border rounded-full border-gray-600 px-4 py-1 hover:bg-gray-600 hover:text-white">
<Link href={src}>
<a>{children}</a>
</Link>
</button>
);
}
|
var fs = require('fs');
fs.readFile('ionic-sample.json', 'utf8', function(err, data){
if(err){
return console.log(err);
}
// Turn string from file to an Array
dataArray = JSON.parse(data);
for(var index in dataArray){
for(var attr in dataArray[index]){
if(dataArray[index].hasOwnProperty(attr)){
switch (attr) {
// It depends on your JSON structure, you should replace details with something else
case 'details':
// Append emails to a list
fs.appendFileSync('emails-list.txt', dataArray[index]['details']['email'] + "\n");
break;
default:
}
}
}
}
})
|
/* ------------------------------------------------------------------------------
*
* # Styled checkboxes, radios and file input
*
* Specific JS code additions for form_checkboxes_radios.html page
*
* Version: 1.0
* Latest update: Aug 1, 2015
*
* ---------------------------------------------------------------------------- */
$(function() {
// Initialize lightbox
$('[data-popup="lightbox"]').fancybox({
padding: 3
});
// Select2 selects
$('.select').select2({
//minimumResultsForSearch: Infinity
});
// Display color formats
$(".colorpicker-show-input").spectrum({
showInput: true
});
// Checkboxes/radios (Uniform)
// ------------------------------
// Default initialization
$(".styled, .multiselect-container input").uniform({
radioClass: 'choice'
});
// File input
$(".file-styled").uniform({
fileButtonClass: 'action btn bg-pink-400'
});
//
// Contextual colors
//
// Primary
$(".control-primary").uniform({
radioClass: 'choice',
wrapperClass: 'border-primary-600 text-primary-800'
});
// Danger
$(".control-danger").uniform({
radioClass: 'choice',
wrapperClass: 'border-danger-600 text-danger-800'
});
// Success
$(".control-success").uniform({
radioClass: 'choice',
wrapperClass: 'border-success-600 text-success-800'
});
// Warning
$(".control-warning").uniform({
radioClass: 'choice',
wrapperClass: 'border-warning-600 text-warning-800'
});
// Info
$(".control-info").uniform({
radioClass: 'choice',
wrapperClass: 'border-info-600 text-info-800'
});
// Custom color
$(".control-custom").uniform({
radioClass: 'choice',
wrapperClass: 'border-indigo-600 text-indigo-800'
});
// Bootstrap switch
// ------------------------------
$(".switch").bootstrapSwitch();
// pickadate Accessibility labels
$('.pickadate-accessibility').pickadate({
labelMonthNext: 'Go to the next month',
labelMonthPrev: 'Go to the previous month',
labelMonthSelect: 'Pick a month from the dropdown',
labelYearSelect: 'Pick a year from the dropdown',
selectMonths: true,
selectYears: true
});
// Default cropper initialization
// Demo cropper
// ------------------------------
// Define variables
var $cropper = $(".cropper"),
$image = $('#ad-img'),
$download = $('#download'),
$dataX = $('#dataX'),
$dataY = $('#dataY'),
$dataHeight = $('#dataHeight'),
$dataWidth = $('#dataWidth'),
options = {
//aspectRatio: 1,
viewMode:2,
//preview: '.preview',
data:{
x:parseInt($dataX.val()),
y:parseInt($dataY.val()),
height:parseInt($dataHeight.val()),
width:parseInt($dataWidth.val()),
},
crop: function (e) {
$dataX.val(Math.round(e.x));
$dataY.val(Math.round(e.y));
$dataHeight.val(Math.round(e.height));
$dataWidth.val(Math.round(e.width));
}
};
// Initialize cropper with options
$cropper.cropper(options);
//
// Toolbar
//
$('.cropper-toolbar').on('click', '[data-method]', function () {
var $this = $(this),
data = $this.data(),
$target,
result;
if ($image.data('cropper') && data.method) {
data = $.extend({}, data);
if (typeof data.target !== 'undefined') {
$target = $(data.target);
if (typeof data.option === 'undefined') {
data.option = JSON.parse($target.val());
}
}
result = $image.cropper(data.method, data.option, data.secondOption);
switch (data.method) {
case 'scaleX':
case 'scaleY':
$(this).data('option', -data.option);
break;
case 'getCroppedCanvas':
if (result) {
// Init modal
$('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
// Download image
$download.attr('href', result.toDataURL('image/jpeg'));
}
break;
case 'chooseFile':
$(data.option).click();
break;
}
}
return false;
});
$('#imageInputFile').on('change',function(){
var selectedFile = this.files[0];
//var img_id=$('#logo-file-input').data('img-id');
//var ou_id=$('#logo-file-input').data('ou-id');
selectedFile.convertToBase64(function(base64){
if($image.length==0){
$image= $('<img id="ad-img" class="cropper">');
$image.appendTo('.image-cropper-container');
}
$image.attr('src', base64);
$image.cropper('destroy').cropper(options);
});
});
File.prototype.convertToBase64 = function(callback){
var FR= new FileReader();
FR.onload = function(e) {
callback(e.target.result)
};
FR.readAsDataURL(this);
}
$('.btn-search-download').click(function(){
var url= $(this).attr('href')+'?'+$(this).closest('form').serialize();
//console.log(url);
window.location.href = url;
return false;
})
});
|
import React from 'react'
const ProseSection = ({children}) => {
return (
<div className="prose dark:prose-dark sm:dark:prose-lg-dark dark:prose-a:text-blue-300 prose-a:text-blue-500 sm:prose-lg max-w-none">
{children}
</div>
)
}
export default ProseSection
|
import React from 'react';
import './BookingItem.scss';
export default function BookingItem(props) {
const { bookingHistory } = props;
console.log(bookingHistory.danhSachGhe);
const { danhSachGhe, maVe, ngayDat, tenPhim } = bookingHistory;
const { tenRap, tenHeThongRap, tenGhe } = danhSachGhe[0];
return (
<div>
<li className="media text-left mt-2 mx-2 mx-sm-4 mx-md-5 mx-lg-2 mx-xl-3">
{/* <img src="..." className="mr-3" alt="..." /> */}
<div className="media-body p-2">
<h5 className="header mt-0 mb-1">{tenPhim}</h5>
<p>
Booking ref: <span className="text-highlight">{maVe}</span>
{' - '}
Booking date: <span className="text-highlight">{new Date(ngayDat).toLocaleDateString()}</span>
</p>
<p>
At <span className="text-highlight">{tenHeThongRap}</span>
{' - '}
Cinema <span className="text-highlight">{tenRap}</span>
{' - '}
Seat <span className="text-highlight">{tenGhe}</span>
</p>
</div>
</li>
</div>
)
}
|
/*
* @Description: 常规路线路由
* @Author: 彭善智
* @LastEditors: 彭善智
* @Date: 2019-04-24 01:31:07
* @LastEditTime: 2019-05-06 17:41:45
*/
const ruleRouter = {
path: '/rule',
component: ()=> import( '@/views/rule/ruleHome'),
redirect: '/rule/rule',
name: "ruleHome",
children: [
{
path:"rule",
component: ()=> import( '@/views/rule/ruleIndex'),
name: "ruleIndex",
meta: { title: "常规路线", requireAuth: false}
},
{
path:"ruleInfo/:id(\\d+)",
component: ()=> import('@/views/rule/ruleInfo'),
name: "ruleInfo",
meta: { title: "常规路线详情", requireAuth: false}
},
{
path:"ruleSure",
component: ()=> import('@/views/rule/ruleSure'),
name: "ruleSure",
meta: { title: "常规路线订单确定", requireAuth: true}
},
{
path:"rulePay",
component: ()=> import('@/views/rule/rulePay'),
name: "rulePay",
meta: { title: "常规路线订单支付", requireAuth: true}
},
{
path:"ruleSuccess",
component: ()=> import('@/views/rule/ruleSuccess'),
name: "ruleSuccess",
meta: { title: "常规路线订单支付成功", requireAuth: true}
},
]
}
export default ruleRouter
|
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
// 引入全部组件
import Mint from 'mint-ui'
import 'mint-ui/lib/style.css'
import '../theme/index.styl'
Vue.use(Mint)
Vue.config.productionTip = false
Object.assign(Vue.prototype, Mint)
// 监听路由
router.beforeEach(async (to, from, next) => {
if (!store.getters.goodsList) {
// 获取用户信息数据
// await store.dispatch('getGoodsList', params)
}
// 判断是否显示下面的nav
store.commit('IS_SHOW_NAV', to.meta.isShowNav)
next()
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: {App},
store
})
|
#!/usr/bin/env node
'use strict';
var common = require("./common.js");
var help = "Usage: app-frame create [App type]\n\nExample: \n\tapp-frame create electron"
var argv = process.argv;
if (argv.length !== 4 || argv[2] !== 'create') {
console.log(help);
return;
}
if (argv[3] === 'electron') {
common.createElectronApp();
}
|
/**
* @jest-environment jsdom
*/
/* eslint-env jest */
import { copyToClipboard } from '../share-certificate.js'
describe('when a browser supports copying and permissions are granted', () => {
Object.assign(navigator, {
clipboard: {
writeText: jest.fn()
},
permissions: {
query: jest.fn()
}
})
beforeAll(() => {
navigator.clipboard.writeText.mockResolvedValue(undefined)
navigator.permissions.query.mockResolvedValue({ name: 'clipboard-write', state: 'granted' })
copyToClipboard()
})
it('should call clipboard.writeText', () => {
expect(navigator.clipboard.writeText).toHaveBeenCalled()
})
})
describe('when a browser supports copying and permissions are prompted', () => {
Object.assign(navigator, {
clipboard: {
writeText: jest.fn()
},
permissions: {
query: jest.fn()
}
})
beforeAll(() => {
navigator.clipboard.writeText.mockResolvedValue(undefined)
navigator.permissions.query.mockResolvedValue({ name: 'clipboard-write', state: 'prompt' })
copyToClipboard()
})
it('should call clipboard.writeText', () => {
expect(navigator.clipboard.writeText).toHaveBeenCalled()
})
})
describe('when a browser recognises the clipboard-write permission but it is not granted', () => {
Object.assign(navigator, {
permissions: {
query: jest.fn()
}
})
Object.assign(document, {
execCommand: jest.fn()
})
beforeAll(() => {
navigator.permissions.query.mockResolvedValue({ name: 'clipboard-write', state: 'denied' })
copyToClipboard()
})
it('should call document.execCommand with copy', () => {
expect(document.execCommand).toHaveBeenCalledWith('copy')
})
})
describe('when a browser does not recognise the clipboard-write permission', () => {
Object.assign(navigator, {
permissions: {
query: jest.fn()
}
})
Object.assign(document, {
execCommand: jest.fn()
})
beforeAll(() => {
navigator.permissions.query.mockRejectedValue(new TypeError("'clipboard-write' (value of 'name' member of PermissionDescriptor) is not a valid value for enumeration PermissionName."))
copyToClipboard()
})
it('should call document.execCommand with copy', () => {
expect(document.execCommand).toHaveBeenCalledWith('copy')
})
})
|
/**
* @module instance-model
*/
const config = require( './config-model' ).server;
const TError = require( '../lib/custom-error' ).TranslatedError;
const utils = require( '../lib/utils' );
const client = require( 'redis' ).createClient( config.redis.main.port, config.redis.main.host, {
auth_pass: config.redis.main.password
} );
// var debug = require( 'debug' )( 'instance-model' );
// in test environment, switch to different db
if ( process.env.NODE_ENV === 'test' ) {
client.select( 15 );
}
/**
* @static
* @name set
* @function
* @param {module:survey-model~SurveyObject} survey
* @param {boolean} [protect] - whether to refuse if record is currently pending (to avoid editing conflicts)
*/
function _cacheInstance( survey, protect = true ) {
return new Promise( ( resolve, reject ) => {
let error;
if ( !survey || !survey.openRosaId || !survey.openRosaServer || !survey.instanceId || !survey.instance ) {
error = new Error( 'Bad request. Survey information not complete or invalid' );
error.status = 400;
reject( error );
} else {
const instanceKey = `in:${survey.instanceId}`;
const openRosaKey = utils.getOpenRosaKey( survey );
const instanceAttachments = survey.instanceAttachments || {};
// first check if record exists (i.e. if it is being edited or viewed)
client.hgetall( `in:${survey.instanceId}`, ( err, obj ) => {
if ( err ) {
reject( err );
} else if ( obj && protect ) {
error = new Error( 'Not allowed. Record is already being edited' );
error.status = 405;
reject( error );
} else {
client.hmset( instanceKey, {
returnUrl: survey.returnUrl || '',
instance: survey.instance,
openRosaKey,
instanceAttachments: JSON.stringify( instanceAttachments )
}, error => {
if ( error ) {
reject( error );
} else {
// expire, no need to wait for result
client.expire( instanceKey, config[ 'expiry for record cache' ] / 1000 );
resolve( survey );
}
} );
}
} );
}
} );
}
/**
* @static
* @name get
* @function
* @param {module:survey-model~SurveyObject} survey
*/
function _getInstance( survey ) {
return new Promise( ( resolve, reject ) => {
let error;
if ( !survey || !survey.instanceId ) {
error = new Error( 'Bad Request. Survey information not complete or invalid' );
error.status = 400;
reject( error );
} else {
client.hgetall( `in:${survey.instanceId}`, ( err, obj ) => {
if ( err ) {
reject( err );
} else if ( !obj ) {
error = new TError( 'error.instancenotfound' );
error.status = 404;
reject( error );
} else {
survey.instance = obj.instance;
survey.returnUrl = obj.returnUrl;
survey.openRosaKey = obj.openRosaKey;
survey.instanceAttachments = JSON.parse( obj.instanceAttachments );
resolve( survey );
}
} );
}
} );
}
/**
* @static
* @name remove
* @function
* @param {module:survey-model~SurveyObject} survey
*/
function _removeInstance( survey ) {
return new Promise( ( resolve, reject ) => {
if ( !survey || !survey.instanceId ) {
const error = new Error( 'Bad request. Survey information not complete or invalid' );
error.status = 400;
reject( error );
} else {
client.del( `in:${survey.instanceId}`, err => {
if ( err ) {
reject( err );
} else {
resolve( survey.instanceId );
}
} );
}
} );
}
module.exports = {
get: _getInstance,
set: _cacheInstance,
remove: _removeInstance
};
|
class DomainError extends Error {
constructor(error) {
super(error);
this.code = error.name || '';
this.msg = error.msg || '';
}
}
module.exports = DomainError;
|
// Try creating one of each type of comment.
/*
Try creating one of each type of comment.
*/
|
const app = (() => {
let privateData;
let hasFlash = false;
const content = document.getElementById("content");
let element;
try {
hasFlash = Boolean(new ActiveXObject('ShockwaveFlash.ShockwaveFlash'));
} catch(exception) {
hasFlash = ('undefined' != typeof navigator.mimeTypes['application/x-shockwave-flash']);
}
const getAppData = (async () => {
let response = await (fetch('assets/data/data.json')
.then(response => response.json())
.then(data => privateData = data)
.then(data => app.resume())
.catch(error => console.log('error: ', error.message))
)
})();
return {
currentPage: "Resume",
darkMode: false,
navigation: () => privateData.navigation.selections,
resume: () => {
app.currentPage = "Resume";
app.analytics('/resume');
app.insertNav();
privateData.resume.content.forEach((eachLine, i) => content.innerHTML += eachLine.line);
},
mobile: () => {
app.currentPage = "Mobile";
let ua = navigator.userAgent.toLowerCase();
app.analytics('/mobile');
app.insertNav();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
app.getImages("mobileImage", "assets/mobile/", privateData.mobile.images, 0);
app.getLazy(".mobileImage");
} else {
app.getImagesSafari("mobileImage", "assets/mobile/", privateData.mobile.images, 0);
}
} else {
app.getImages("mobileImage", "assets/mobile/", privateData.mobile.images, 0);
app.getLazy(".mobileImage");
}
},
interactive: () => {
app.currentPage = "Marketing";
let ua = navigator.userAgent.toLowerCase();
app.analytics('/web');
app.insertNav();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
app.getImages("interactive", "assets/290/", privateData.interactive.images, 0);
app.getLazy(".interactive");
} else {
app.getImagesSafari("interactive", "assets/290/", privateData.interactive.images, 0);
}
} else {
app.getImages("interactive", "assets/290/", privateData.interactive.images, 0);
app.getLazy(".interactive");
}
},
advertising: () => {
app.currentPage = "Advertising";
app.analytics('/advertising');
app.insertNav();
if (hasFlash) { app.banners() } else { app.videos() }
},
banners: () => {
app.currentPage = "Banners";
privateData.advertising.banners.forEach((banner, i) => {
element = document.createElement("object");
element.id="banner"+i;
element.style.width=banner.width+"px";
element.style.height=banner.height+"px";
element.data="assets/banners/" + banner.file;
if (banner.height < banner.width) { element.className = "ad" }
content.appendChild(element);
})
},
videos: () => {
app.currentPage = "Videos";
let videoElement;
privateData.advertising.videos.forEach((video, i) => {
content.innerHTML += "<video id='vid" + i +
"' class='ad' loop preload='none' width='" + video.width +
"' height='" + video.height + "' poster='assets/banners/"+video.poster+"'>"+
"<source src='assets/banners/" + video.file + "' type='video/mp4'>" +
"Your browser does not support the video tag." +
"</video>" +
"<button id='button" + i +
"' type='button' class='btn btn-default btn-lg videoButton play' onclick='app.playPause(this, " +
i +")'>" +
"</button>";
})
},
insertNav: () => {
let slider = "<input type='checkbox' checked onclick='app.toggleBackground()'>";
const fontIncreaser = "<div id='fontIncreaser' onclick='app.increaseFontSize()'>+</div>";
const fontDecreaser = "<div id='fontDecreaser' onclick='app.decreaseFontSize()'>-</div>";
let fontSizeInterface = fontIncreaser + fontDecreaser;
if (app.darkMode) { slider = "<input type='checkbox' onclick='app.toggleBackground()'>" }
if (app.currentPage !== "Resume") {
fontSizeInterface = "";
}
if (!document.getElementById("navSpacer")) {
content.innerHTML += "<div class='nav mb-3'><div id='navSpacer'></div>"+
// "<div id='backgroundToggler' onclick='app.toggleBackground()'>*</div>"+
fontSizeInterface +
//"<img id='moon' class='lightIcon' onclick='app.toggleBackground()' src='./assets/moonBlack.png' alt='light' height='15' width='15' />"+
"<div id='darkModeToggle' class='ml-20'>"+
"<label class='switch'>"+
slider+
"<span class='slider round'></span>"+
"</label>"+
"</div>"+
//"<img id='sun' class='lightIcon' src='./assets/sunBlack.png' onclick='app.toggleBackground()' alt='light' height='15' width='15' />"+
"</div>";
}
},
padding: 0,
fontSize: 12,
line_height: 25,
addFontSize: () => app.fontSize = app.fontSize+2,
minusFontSize: () => app.fontSize = app.fontSize-2,
addLineHeight: () => app.line_height = app.line_height+2,
minusLineHeight: () => app.line_height = app.line_height-2,
addPadding: () => app.padding = app.padding+1,
minusPadding: () => app.padding = app.padding-1,
increaseFontSize: () => {
if ((window.innerWidth >= 400 && app.fontSize < 42) || (window.innerWidth < 500 && app.fontSize < 20)) {
app.addFontSize();
app.addPadding();
app.addLineHeight();
app.updateFontSize();
}
},
decreaseFontSize: () => {
if (app.fontSize > 10) {
app.minusFontSize();
app.minusPadding();
app.minusLineHeight();
app.updateFontSize();
}
},
toggleBackground: () => {
const root = document.documentElement;
//const sun = document.getElementById("sun");
//const moon = document.getElementById("moon");
const content = document.body;
let color = content.style.color;
const light = "rgb(250, 250, 250)";
const dark = "rgb(0, 0, 0)";
color = (color === light) ? dark : light;
let background = content.style.backgroundColor;
background = (background === dark) ? light : dark;
app.darkMode = (background === dark) ? true : false;
//moon.src = (background === dark) ? './assets/moonWhite.png' : './assets/moonBlack.png';
//sun.src = (background === dark) ? './assets/sunWhite.png' : './assets/sunBlack.png';
content.style.color = color;
content.style.backgroundColor = background;
root.style.setProperty('--videoButtonBackground', background);
root.style.setProperty('--videoButtonColor', color);
root.style.setProperty('--play', (background == "rgb(0, 0, 0)") ? 'url(/portfolio/assets/icons/playInvert.png)' : 'url(/portfolio/assets/icons/play.png)');
root.style.setProperty('--pause', (background == "rgb(0, 0, 0)") ? 'url(/portfolio/assets/icons/pauseInvert.png)' : 'url(/portfolio/assets/icons/pause.png)');
},
updateFontSize: () => {
document.getElementById("content").style.fontSize = app.fontSize + 'px';
document.getElementById("content").style.lineHeight = app.line_height + 'px';
document.getElementById("darkModeToggle").style.paddingTop = app.padding + 'px';
},
playPause: (btn, id) => {
let all = document.getElementsByTagName("video");
let buttons = document.getElementsByTagName("button");
let playButton;
let myVideo = document.getElementById("vid" + id);
if (myVideo.paused) {
// app.analytics('/advertising/'+id);
Array.prototype.forEach.call(all, function (video) {
video.pause();
})
Array.prototype.forEach.call(buttons, function (button) {
button.className = button.className.replace("pause", "play");
})
btn.className = btn.className.replace("play", "pause");
if (content.offsetWidth < 700) { myVideo.style.height = "auto" }
myVideo.play();
} else {
myVideo.pause();
btn.className = btn.className.replace("pause", "play");
}
btn.blur();
},
eCommerce: () => {
app.currentPage = "eCommerce";
app.analytics('/ecommerce');
app.insertNav();
let ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
app.getImages("interactive", "portfolio/", privateData.eCommerce.images, 0);
app.getLazy(".interactive");
} else {
app.getImagesSafari("interactive", "portfolio/", privateData.eCommerce.images, 0);
}
} else {
app.getImages("interactive", "portfolio/", privateData.eCommerce.images, 0);
app.getLazy(".interactive");
}
},
html5: () => {
app.currentPage = "HTML5";
app.analytics('/applications');
app.insertNav();
let ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
app.getImages("mobileImage", "portfolio/", privateData.html5.images, 0);
app.getLazy(".mobileImage");
} else {
app.getImagesSafari("mobileImage", "portfolio/", privateData.html5.images, 0);
}
} else {
app.getImages("mobileImage", "portfolio/", privateData.html5.images, 0);
app.getLazy(".mobileImage");
}
},
clearContent: () => {
content.innerHTML = "";
content.style.opacity = 1;
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
content.scrollTop = 0;
content.className += " mobile";
},
toggleNav: () => {
const navigation = document.getElementsByTagName('nav')[0];
const menuClose = document.getElementById('menuClose');
const menu = document.getElementById('menu');
if (navigation.className == 'animate display') {
navigation.className = 'animate';
navigation.innerHTML = "";
menuClose.className = "animate hide";
menu.className = "animate show";
document.body.className = document.body.className.replace("noscroll", "");
} else {
navigation.className = 'animate display';
app.navigation().forEach((eachPage, i) => {
navigation.innerHTML +=
"<button type='button' class='btn btn-default btn-lg' onclick='" +
eachPage.function + "'>"+
eachPage.page +
"</button><br>";
})
document.body.className += "noscroll";
menu.className = "animate hide";
menuClose.className = "animate show";
}
},
getImages: (css, path, imgArray, index) => {
imgArray.forEach((eachItem, i) => {
let url = path + eachItem.image;
let imgElement = document.createElement("img");
imgElement.style.opacity = 0;
imgElement.setAttribute("class", "js-lazy-image, " + css);
imgElement.setAttribute("data-src", url);
content.appendChild(imgElement);
})
},
getImagesSafari: (css, path, imgArray, index) => {
/*
imgArray.forEach((eachItem, i) => {
let url = path + eachItem.image;
let imgElement = document.createElement("img");
imgElement.setAttribute("class", css);
imgElement.src = url;
content.appendChild(imgElement);
})
*/
getImage(css, path, imgArray, index);
async function getImage(css, path, imgArray, index) {
let image = await loadImage(css, path, imgArray, index);
if (index<(imgArray.length-1)){getImage(css, path, imgArray, (index+1))}
}
function loadImage(css, path, imgArray, index) {
let url = path + imgArray[index].image;
return new Promise((resolve,reject) => {
let image = new Image();
image.onload = () => resolve(image);
image.onerror = () => { reject(new Error('Could not load image at ' + url)) };
image.src = url;
let imgElement = document.createElement("img");
imgElement.setAttribute("class", css);
imgElement.src = url;
content.appendChild(imgElement);
});
}
},
getLazy: (css) => {
const images = document.querySelectorAll(css);
// If the image gets within 50px in the Y axis, start the download.
const config = { rootMargin: '50px 0px', threshold: 0.01 };
let imageCount = images.length;
let observer;
if (!('IntersectionObserver' in window)) {
// loadImagesImmediately(images);
} else {
observer = new IntersectionObserver(onIntersection, config);
images.forEach((eachImage, i) => {
if (!eachImage.classList.contains('js-lazy-image--handled')) {
observer.observe(eachImage);
}
})
}
let fetchImage = (url) => {
return new Promise((resolve, reject) => {
const image = new Image();
image.src = url;
image.onload = resolve;
image.onerror = reject;
});
}
//Preloads the image @param {object} image
let preloadImage = (image) => {
const src = image.dataset.src;
if (!src) { return }
return fetchImage(src).then(() => { applyImage(image, src) });
}
//Load all of the images immediately @param {NodeListOf<Element>} images
let loadImagesImmediately = (images) => {
images.forEach((eachImage, i) => { preloadImage(eachImage) })
}
//Disconnect the observer
let disconnect = () => {
if (!observer) { return }
observer.disconnect();
}
//On intersection @param {array} entries
function onIntersection(entries) {
// Disconnect if we've already loaded all of the images
if (imageCount === 0) { observer.disconnect() }
entries.forEach((eachEntry, i) => {
// Are we in viewport?
if (eachEntry.intersectionRatio > 0) {
imageCount--;
// Stop watching and load the image
observer.unobserve(eachEntry.target);
preloadImage(eachEntry.target);
}
})
}
//Apply the image @param {object} img @param {string} src
let applyImage = (img, src) => {
img.classList.add('js-lazy-image--handled');
img.src = src;
img.style.opacity = 1;
}
},
analytics: (tag) => {
content.style.opacity = 0;
ga('set', 'page', tag);
ga('send', 'pageview');
app.clearContent();
if (tag == '/resume') { content.className = "resume animate";
} else { content.className += " mobile"; }
content.style.opacity = 1;
},
data: () => privateData
};
})();
document.getElementById('menuClose').className = "hide";
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import AmCharts from '@amcharts/amcharts3-react';
import 'ammap3/ammap/ammap.js';
import 'ammap3/ammap/maps/js/worldLow.js';
import './WorldMap.css';
class WorldMap extends Component {
citySVG = "M9,0C4.029,0,0,4.029,0,9s4.029,9,9,9s9-4.029,9-9S13.971,0,9,0z M9,15.93 c-3.83,0-6.93-3.1-6.93-6.93S5.17,2.07,9,2.07s6.93,3.1,6.93,6.93S12.83,15.93,9,15.93 M12.5,9c0,1.933-1.567,3.5-3.5,3.5S5.5,10.933,5.5,9S7.067,5.5,9,5.5 S12.5,7.067,12.5,9z";
render() {
var citiesOnMap = this.props.cities
.filter(city => city.latitude && city.longitude)
.map(city => {
return {
svgPath: this.citySVG,
title: city.name,
latitude: city.latitude,
longitude: city.longitude
}
});
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
var countriesOnMap = this.props.cities
.map(city => city.country)
.filter(onlyUnique)
.map(country => {
return {
title: country.name,
id: country.code,
color: "#66CC99"
}
});
return (
<div className="map">
<AmCharts.React
style={{
width: "100%",
height: "500px"
}}
options={{
type: "map",
mouseWheelZoomEnabled: true,
zoomDuration: 0.4,
areasSettings: {
unlistedAreasColor: "#8dd9ef"
},
imagesSettings: {
color: "#585869",
rollOverColor: "#585869",
selectedColor: "#585869"
},
dataProvider: {
"map": "worldLow",
"zoomLevel": 5,
"zoomLongitude": 21,
"zoomLatitude": 52,
"images": citiesOnMap,
"areas": countriesOnMap
}
}} />
</div>
);
}
}
WorldMap.propTypes = {
cities: PropTypes.array
};
export default WorldMap;
|
/* global google */
/* unused:false */
$(function() {
'use strict';
(function($, window, undefined) {
/**
* @name G7
* @namespace G7
* @description G7 Global Namespace Definition.
* @global
* @type {{}|*}
*/
var G7 = window.G7 = window.G7 || {};
/**
* @name Modules
* @memberof G7
* @namespace Modules
* @description Holds the defined Modules to extend the App.
* @type {{}}
*/
G7.Modules = {};
/**
* @name Pages
* @memberof G7
* @namespace Pages
* @description Holds the defined Pages to extend the App.
* @type {{}}
*/
G7.Pages = {};
/**
* @name Main
* @memberof G7
* @namespace Main
* @description Holds the defined Global App Behavior Methods.
* @type {{init}}
*/
G7.Main = (function() {
/**
* @scope G7.Main
* @description Exposed methods from the G7.Main Module.
*/
return {
/**
* @name init
* @description G7.Main Module Constructor.
*/
init: (function() {
})()
};
}());
})(jQuery, window);
});
|
export default function isShallowEqual(firstObject, secondObject) {
for (const key in firstObject) {
if (!(key in secondObject) || firstObject[key] !== secondObject[key]) return false
}
for (const key in secondObject) {
if (!(key in firstObject) || firstObject[key] !== secondObject[key]) return false
}
return true
}
|
import config from 'Config'
import log from 'Utilities/log'
import { toSmallestDenomination } from 'Utilities/convert'
import { xpubToYpub } from 'Utilities/bitcoin'
import Trezor from 'Services/Trezor'
import BitcoinWallet from './BitcoinWallet'
const typeLabel = config.walletTypes.trezor.name
export default class BitcoinWalletTrezor extends BitcoinWallet {
static type = 'BitcoinWalletTrezor';
constructor(xpub, derivationPath) {
super(xpub)
this.derivationPath = derivationPath
}
getType() { return BitcoinWalletTrezor.type }
getTypeLabel() { return typeLabel }
isLegacyAccount() { return this.derivationPath.startsWith('m/44') }
getAccountNumber() { return Number.parseInt(this.derivationPath.match(/(\d+)'$/)[1]) + 1 }
getLabel() { return this.label || `Bitcoin${this.isLegacyAccount() ? 'legacy ' : ''} account #${this.getAccountNumber()}` }
static fromPath(derivationPath = null) {
Trezor.setCurrency('BTC')
return Trezor.getXPubKey(derivationPath)
.then((result) => {
log.info('Trezor xPubKey success')
let { xpubkey, serializedPath } = result
if (!serializedPath.startsWith('m/') && /^\d/.test(serializedPath)) {
serializedPath = `m/${serializedPath}`
}
if (serializedPath.startsWith('m/49\'')) {
xpubkey = xpubToYpub(xpubkey)
log.info('Converted segwit xpub to ypub')
}
return new BitcoinWalletTrezor(xpubkey, serializedPath)
})
}
createTransaction(toAddress, amount, assetOrSymbol) {
return Promise.resolve(assetOrSymbol)
.then(::this.assertAssetSupported)
.then(::this.getAsset)
.then((asset) => ({
walletId: this.getId(),
toAddress,
amount,
assetSymbol: asset.symbol,
feeAmount: null,
feeSymbol: 'BTC',
signed: false,
sent: false,
txData: [{
address: toAddress,
amount: toSmallestDenomination(amount, asset.decimals).toNumber(),
}],
signedTxData: null,
}))
}
_signTx(tx) {
return Trezor.composeAndSignTx(tx.txData)
.then((result) => {
log.info('Transaction composed and signed:', result)
const { serialized_tx: signedTxData } = result
return {
signedTxData
}
})
}
_sendSignedTx(tx) {
return Trezor.pushTransaction(tx.signedTxData)
.then((result) => {
log.info('Transaction pushed:', result)
return {
id: result.txid
}
})
}
_validateTxData(txData) {
if (txData === null || !Array.isArray(txData)) {
throw new Error(`Invalid ${this.getType()} txData of type ${typeof txData}`)
}
return txData
}
_validateSignedTxData(signedTxData) {
if (typeof signedTxData !== 'string') {
throw new Error(`Invalid ${this.getType()} signedTxData of type ${typeof signedTxData}`)
}
return signedTxData
}
}
|
$(function () {
getLocation();
});
// =========================
var map;
var infoData;
var markers;
var userLatitude = '25.047819';
var userLongitude = '121.5147601';
var blueIcon = new L.Icon({
iconUrl: 'img/blue_marker.svg',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
});
var grayIcon = new L.Icon({
iconUrl: 'img/gray_marker.svg',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
});
var orangeIcon = new L.Icon({
iconUrl: 'img/orange_marker.svg',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
});
var selfIcon = new L.Icon({
iconUrl: 'img/self_marker.svg',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
});
_.templateSettings = { // underscore.js .Template method.
evaluate: /\{\{(.+?)\}\}/g,
interpolate: /\{\{=(.+?)\}\}/g,
escape: /\{\{-(.+?)\}\}/g
};
function initMap(location) {
if (location) {
userLatitude = location.coords.latitude;
userLongitude = location.coords.longitude;
} else {
userLatitude = '25.047819';;
userLongitude = '121.5147601';
}
map = L.map('mapid', {
center: [userLatitude, userLongitude],
zoom: 16
});
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.marker([userLatitude,userLongitude], {
icon: selfIcon
}).addTo(map);
markers = new L.MarkerClusterGroup().addTo(map);
getData();
}
function getData() {
$.ajax({
url: 'https://raw.githubusercontent.com/kiang/pharmacies/master/json/points.json',
type: 'GET',
dataType: 'json',
success: function (data) {
infoData = data.features;
dataAppendMap();
}
});
}
function dataAppendMap() {
for (var i = 0; i < infoData.length; i++) {
var id = infoData[i].properties.id;
var name = infoData[i].properties.name;
var position1 = infoData[i].geometry.coordinates[1];
var position2 = infoData[i].geometry.coordinates[0];
var phone = infoData[i].properties.phone;
var address = infoData[i].properties.address;
var mask_adult = infoData[i].properties.mask_adult;
var mask_child = infoData[i].properties.mask_child;
var updated = infoData[i].properties.updated;
var available = infoData[i].properties.available;
var note = infoData[i].properties.note;
var custom_note = infoData[i].properties.custom_note;
var website = infoData[i].properties.website;
var adultClass = '';
var childClass = '';
if (mask_adult > 0) {
adultClass = ' sufficient';
}
if (mask_child > 0) {
childClass = ' sufficient';
}
if (mask_adult > 0 && mask_child > 0) {
var icon = blueIcon;
} else if (mask_adult > 0 && mask_child === 0) {
var icon = orangeIcon;
} else if (mask_adult === 0 && mask_child > 0) {
var icon = orangeIcon;
} else {
var icon = grayIcon;
}
markers.addLayer(
L.marker([position1, position2], {
icon: icon
}).bindPopup('<div class="info_card">\
<h1>' + name + '</h1>\
<div>\
<span><i class="fas fa-map-marker-alt"></i></span>\
<span>' + address + '</span>\
</div>\
<div>\
<span><i class="fas fa-phone-alt"></i></span>\
<span>' + phone + '</span>\
</div>\
<div class="m-t-sm">\
<div class="type_count' + adultClass + '">成人:' + mask_adult + ' 個</div>\
<div class="type_count' + childClass + '">兒童:' + mask_child + ' 個</div>\
<div class="clear_both"></div>\
</div>\
</div>', {
width: '250px'
})
)
}
map.addLayer(markers);
$('#updateTime').text(infoData[0].properties.updated);
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
}
function showPosition(position) {
initMap(position);
}
function showError(error) {
initMap();
switch (error.code) {
case error.PERMISSION_DENIED:
console.log = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
console.log = "Location information is unavailable."
break;
case error.TIMEOUT:
console.log = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
console.log = "An unknown error occurred."
break;
}
} |
import firebase from 'firebase';
import { Actions } from 'react-native-router-flux';
import {
EMAIL_CHANGED,
PASSWORD_CHANGED,
LOGIN_USER_SUCCESS,
LOGIN_USER_FAIL,
LOGIN_USER
} from './types';
export const emailChanged = (text) => {
return {
type: EMAIL_CHANGED,
payload: text
};
};
// We want to communicate with the text that was provided.
export const passwordChanged = (text) => {
return {
type: PASSWORD_CHANGED,
payload: text
};
};
export const loginUser = ({ email, password }) => {
return (dispatch) => {
dispatch({ type: LOGIN_USER });
firebase.auth().signInWithEmailAndPassword(email, password)
.then(user => loginUserSuccess(dispatch, user))
.catch((error) => {
console.log(error); //Good to keep this here.
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(user => loginUserSuccess(dispatch, user))
.catch(() => loginUserFailed(dispatch));
});
};
};
const loginUserFailed = (dispatch) => {
dispatch({ type: LOGIN_USER_FAIL });
};
const loginUserSuccess = (dispatch, user) => {
dispatch({
type: LOGIN_USER_SUCCESS,
payload: user
});
Actions.tabbar();
};
// ReduxThunk Notes
// The action creator 'loginUser' returns a function
// Redux thunk sees that we return a function and it calls it
// with the dispatch function.
// Next, We do our login request.
// We wait for the request to complete and for the user to login
// our " .then() " will run.
// NOW, WE DISPATCH OUR ACTION TO THE REDUCERS!
// This is just a manual dispatch.
|
/*
* @lc app=leetcode id=605 lang=javascript
*
* [605] Can Place Flowers
*/
// @lc code=start
/**
* @param {number[]} flowerbed
* @param {number} n
* @return {boolean}
*/
var canPlaceFlowers = function(flowerbed, n) {
const isViolate = index => (flowerbed[index - 1] || flowerbed[index + 1]);
for (let i = 0; i < flowerbed.length; i++) {
if (!flowerbed[i]) {
if (!isViolate(i)) {
n--;
flowerbed[i] = 1;
}
}
}
return n <= 0;
};
// @lc code=end
|
function add(){
player1=document.getElementById("login1").value;
player2=document.getElementById("login2").value;
localStorage.setItem("player1",player1);
localStorage.setItem("player2",player2);
window.location="2index.html";
} |
import React from 'react';
import Social from '../comps/Social';
export default {
title: 'Login SignUp/Social ',
component: Social,
};
export const BasicSocial = () => <Social />
|
import React, {useEffect, useState} from 'react';
import UpdateProfileForm from '../../components/profile/UpdateProfileForm';
import {useDispatch, useSelector} from 'react-redux';
import {useDerbyTheme} from '../../utils/theme';
import isEmpty from 'validator/lib/isEmpty';
import isEmail from 'validator/lib/isEmail';
import {StyleSheet} from 'react-native';
import {updateProfile} from '../../actions/profile';
import {useUpdateProfileAlerts} from '../../hooks/useDropDownAlerts';
import {Text} from 'react-native-elements';
import i18n from 'i18n-js';
const ProfileForm = () => {
const {colors, sizes} = useDerbyTheme();
const dispatch = useDispatch();
const auth = useSelector((state) => state.auth);
const profile = useSelector((state) => state.profile);
if (!auth.user) {
return null;
}
const {updatingProfile} = profile;
const submitButtonStyle = [
styles.submitButton,
{backgroundColor: colors.primary},
];
const [firstName, setFirstName] = useState(auth.user.first_name);
const [lastName, setLastName] = useState(auth.user.last_name);
const [email, setEmail] = useState(auth.user.email);
const [username, setUsername] = useState(auth.user.username);
const [formValidMain, setFormValidMain] = useState(false);
useEffect(() => {
setFormValidMain(
!isEmpty(firstName) && !isEmpty(lastName) && isEmail(email),
);
}, [firstName, lastName, email]);
useUpdateProfileAlerts();
return (
<>
<Text
style={[
styles.titleStyle,
{
paddingHorizontal: sizes.BASE * 1.5,
paddingTop: sizes.BASE,
fontSize: sizes.FONT * 1.2,
color: colors.text,
},
]}>
{i18n.t('profile_form_title')}
</Text>
<UpdateProfileForm
firstName={firstName}
onFirstNameChange={(text) => setFirstName(text)}
lastName={lastName}
onLastNameChange={(text) => setLastName(text)}
email={email}
onEmailChange={(text) => setEmail(text)}
username={username}
onUsernameChange={(text) => setUsername(text)}
buttonStyle={submitButtonStyle}
formValid={formValidMain}
onUpdate={() => {
dispatch(updateProfile({firstName, lastName, email, username}));
}}
loading={updatingProfile}
/>
</>
);
};
const styles = StyleSheet.create({
submitButton: {
borderRadius: 30,
},
titleStyle: {
fontFamily: 'Rubik_400Regular',
},
});
export default ProfileForm;
|
import React from "react"
import { Page, Fab, Icon } from 'framework7-react';
import ModelStore from "../../stores/ModelStore";
import SurveillanceIndex from "../../containers/surveillances/index"
import * as MyActions from "../../actions/MyActions";
import { dict } from '../../Dict';
import Framework7 from 'framework7/framework7.esm.bundle';
import crypto from 'crypto-js';
//import ConcatenateBlobs from 'concatenateblobs';
export default class Layout extends React.Component {
constructor() {
super();
this.getList = this.getList.bind(this);
this.startRecording = this.startRecording.bind(this);
this.addScreenCastDb = this.addScreenCastDb.bind(this);
this.uploadFromDb = this.uploadFromDb.bind(this);
this.stopRecording = this.stopRecording.bind(this);
this.state = {
token: window.localStorage.getItem('token'),
surveillances: null,
chunks: [],
stream: null,
recorder: null,
videoSrc: null,
startTime: null,
endTime: null,
db: null,
sessionId: null
}
}
componentWillMount() {
ModelStore.on("got_list", this.getList);
}
componentWillUnmount() {
ModelStore.removeListener("got_list", this.getList);
}
componentDidMount() {
this.loadData();
}
loadData() {
const f7: Framework7 = Framework7.instance;
f7.toast.show({ text: dict.receiving, closeTimeout: 2000, position: 'top' });
MyActions.getList('surveillances', this.state.page, {}, this.state.token);
}
stopRecording() {
clearInterval(window.intervalHandle);
}
async startRecording() {
var self = this;
var supportedConstraints = navigator.mediaDevices.getSupportedConstraints();
console.log(supportedConstraints);
this.setState({ sessionId: crypto.lib.WordArray.random(32) })
var stream = await navigator.mediaDevices.getDisplayMedia({
video: { mediaSource: "screen", frameRate: 6, width: 768, height: 480 },
})
this.setState({ stream: stream })
this.setState({ startTime: new Date() })
var recorder = new MediaRecorder(stream);
var self = this;
var chunks = [];
window.intervalHandle = null;
window.intervalHandle = setInterval(function () {
if (recorder.state !== 'inactive') {
recorder.stop();
}
setTimeout(function () {
try {
recorder.start();
}
catch (err) { }
}, 2000);
}, 3000);
stream.getVideoTracks()[0].onended = function(event) {
clearInterval(window.intervalHandle);
}
recorder.ondataavailable = (e) => {
chunks.push(e.data);
};
recorder.onpause = (e) => {
//console.log(chunks);
console.log(e.data);
};
recorder.onstop = (e) => {
//this.setState({ endTime: new Date() })
const completeBlob = new Blob(chunks, { type: chunks[0].type });
//this.setState({ videoSrc: URL.createObjectURL(completeBlob) });
// var data = [{ label: 'file', value: completeBlob }, { label: 'surveillance[start_time]', value: crypto.lib.WordArray.random(32) }]
//MyActions.generalFilePost('surveillances', data, this.state.token)
this.addScreenCastDb(completeBlob, self.state.sessionId)
// var data = [{ label: 'file', value: completeBlob }, { label: 'surveillance[start_time]', value: crypto.lib.WordArray.random(32) }]
// MyActions.generalFilePost('surveillances', data, this.state.token)
//video.src = URL.createObjectURL(completeBlob);
};
}
addScreenCastDb(blob, sessionId) {
// IndexedDB
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB,
IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction,
dbVersion = 3;
// Create/open database
var request = indexedDB.open("screenCastFiles", dbVersion);
request.onsuccess = function (event) {
console.log("Success creating/accessing IndexedDB database");
var db = request.result;
db.onerror = function (event) {
console.log("Error creating/accessing IndexedDB database");
};
var transaction = db.transaction(["screenCastFiles"], "readwrite");
console.log('added')
transaction.objectStore("screenCastFiles").put({blob: blob, sessionId: sessionId} );
}
request.onupgradeneeded = function (event) {
var db = event.target.result;
console.log("running onupgradeneeded");
if (!db.objectStoreNames.contains("screenCastFiles")) {
console.log("I need to make the screenCast objectstore");
db.createObjectStore("screenCastFiles", { autoIncrement : true });
}
}
}
uploadFromDb() {
var self = this;
console.log('Started')
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB,
IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.OIDBTransaction || window.msIDBTransaction,
dbVersion = 2;
// Create/open database
var request = indexedDB.open("screenCastFiles", dbVersion);
request.onsuccess = function (event) {
console.log("Success creating/accessing IndexedDB database");
var db = request.result;
db.onerror = function (event) {
console.log("Error creating/accessing IndexedDB database");
};
// db.createObjectStore("screenCast");
var transaction = db.transaction(["screenCast"], "readwrite");
var parts = []
transaction.objectStore("screenCast").getAll().onsuccess = function (event) {
console.log(event.target.result);
window.ConcatenateBlobs(event.target.result, "video/x-matroska;codecs=avc1", function (resultingBlob) {
//const completeBlob = new Blob(parts, { type: "video/x-matroska;codecs=avc1" });
console.log(resultingBlob)
self.setState({ videoSrc: URL.createObjectURL(resultingBlob) })
}
);
}
}
}
getList() {
var surveillances = ModelStore.getList()
var klass = ModelStore.getKlass()
if (surveillances && klass === 'Surveillance') {
this.setState({
surveillances: surveillances,
});
}
}
render() {
const { surveillances, stream, videoSrc } = this.state;
return (<SurveillanceIndex
videoSrc={videoSrc}
stream={stream}
surveillances={surveillances}
uploadFromDb={this.uploadFromDb}
stopRecording={this.stopRecording}
startRecording={this.startRecording} />)
}
}
|
module.exports = {
css: {
extract: false
},
pwa: {
iconPaths: {
favicon32: 'favicon.ico',
favicon16: 'favicon.ico',
appleTouchIcon: 'favicon.ico',
maskIcon: 'favicon.ico',
msTileImage: 'favicon.ico'
}
}
};
|
// A simple component, that isn't stateful, can be provided as a single
// function that accepts props. This provides React with a hint that this
// component can be collapsed and that its state doesn't need to be preserved.
// It also encourages micro-componentization instead of custom helper functions
// outside the system.
export function Button(props : { width: number, onClick: function }) {
return (
<div>
Fancy button
<button onClick={props.onClick} style={{ width: props.width }} />
</div>
);
}
// When named exports are used, it may be valid to have multiple components
// in the same file. Destructuring can be used to provide convenience aliasing
// and defaults to props.
export function Checkbox({ checked = true, width }) {
return (
<div>
Fancy checkbox
<input type="checkbox" checked={checked} style={{ width }} />
</div>
);
}
|
var valor;
$(document).ready(function(){
$("#bTipoReserva").off("click").click(function(){
valor=$("input[name='tipoReserva']:checked").val();
if(valor!=null)
{
load("html/aluno/reservar.html");
}
else
{
alert("Selecione uma das opções");
}
});
});
|
module.exports = {
defaultLanguage: "zh"
};
|
var sockets = {};
var addUser = (userName, socket) => {
sockets[socket.id] = {
userName,
socket
}
}
var deleteUser = (socket) => {
delete sockets[socket.id];
}
var getUser = (userName) => {
console.log(userName)
var keys = Object.keys(sockets);
var obj = keys.filter(key => {
return sockets[key].userName === userName;
})
obj = obj.map(key => {
return sockets[key].socket;
})
return obj;
}
module.exports = { deleteUser, getUser, addUser }; |
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 4005 });
server.route(require('./routes/route'));
if (!module.parent) {
server.start((err) => {
if (err) {
throw (err);
}
console.log('Server started at port 4005');
});
}
module.exports = server;
|
function birthdayCakeCandles(candles) {
// Write your code here
let dict = new Map();
let result = 0;
candles.forEach((item) => {
if (dict.has(item)) {
let temp = parseInt(dict.get(item)) + 1;
dict.set(item, temp);
if (temp > result) {
result = temp;
}
} else {
dict.set(item, '1');
}
});
return result;
}
|
export { default as ActivitiesTable } from "./ActivitiesTable";
export { default as ActivitiesList } from "./ActivitiesRegistry";
|
import _taskService from "../services/TaskService";
import _commentService from "../services/CommentService";
import express from "express";
import { Authorize } from "../middleware/authorize.js";
export default class TaskController {
constructor() {
this.router = express
.Router()
.use(Authorize.authenticated)
// .post("", this.create)
.post("/:taskId/comments", this.createComment)
.post("/:taskId/get-comments", this.getCommentsByTaskId)
.delete("/:taskId/comments/:commentId", this.deleteComment)
.put("/:taskId/comments/:commentId", this.editComment)
}
// async create(req, res, next) {
// try {
// req.body.user = req.session.uid;
// let data = await _taskService.create(req.body);
// data = await data.populate("comment").execPopulate();
// return res.status(201).send(data);
// } catch (error) {
// error.message = "TaskController.js: create()";
// next(error);
// }
// }
// COMMENTS
async createComment(req, res, next) {
try {
let newComment = req.body;
let comment = await _commentService.create(newComment);
return res.send(comment);
} catch (error) {
error.message = "TaskController.js: createTask()";
next(error);
}
}
async getCommentsByTaskId(req, res, next) {
try {
let taskId = req.params.taskId;
// let userId = req.body.user;
let tasks = await _commentService
.find({ task: taskId })
.populate('user');
return res.send(tasks);
} catch (error) {
error.message = "TaskController.js: getCommentsByTaskId()";
next(error);
}
}
async deleteComment(req, res, next) {
try {
let commentId = req.params.commentId;
let deleted = await _commentService.deleteOne({ _id: commentId });
return res.send(deleted);
} catch (error) {
error.message = "TaskController.js: deleteComment()";
next(error);
}
}
async editComment(req, res, next) {
try {
let editedComment = await _commentService.findOneAndUpdate(
{ _id: req.params.commentId },
req.body,
{ new: true }
)
return res.status(201).send(editedComment);
} catch (error) {
error.message = "TaskController.js: editComment()";
next(error);
}
}
}
|
OC.L10N.register(
"core",
{
"Please select a file." : "Si us plau, selecciona un fitxer",
"File is too big" : "El fitxer és massa gran",
"Invalid file provided" : "L'arxiu proporcionat no és vàlid",
"No image or file provided" : "No s'han proporcionat imatges o fitxers",
"Unknown filetype" : "Tipus de fitxer desconegut",
"Invalid image" : "Imatge no vàlida",
"An error occurred. Please contact your admin." : "Error. Contacte amb el teu administrador.",
"No temporary profile picture available, try again" : "No hi ha imatge temporal de perfil disponible, torneu a intentar-ho",
"No crop data provided" : "No heu proporcionat dades del retall",
"No valid crop data provided" : "Les dades del retall proporcionades no són vàlides",
"Crop is not square" : "El retall no és quadrat",
"Could not reset password because the token is invalid" : "No es pot actualitzar la contrassenya perquè l'identificador és invàlid",
"Could not reset password because the token expired" : "No es pot actualitzar la contrassenya perquè l'identificador ha expirat",
"Could not reset password because the token does not match" : "No es pot actualitzar la contrassenya perquè els identificadors no coincideixen",
"%s password changed successfully" : "%scontrassenya actualitzada correctament",
"%s password reset" : "restableix la contrasenya %s",
"Couldn't send reset email. Please contact your administrator." : "No s'ha pogut restablir el correu. Contacteu amb l'administrador.",
"Download / View" : "Descarregar / Veure",
"Download / View / Upload" : "Descarregar / Veure / Pujar",
"Preparing update" : "Preparant l'actualització",
"[%d / %d]: %s" : "[%d/%d]:%s",
"Repair warning: " : "Advertiment de reparació:",
"Repair error: " : "Error de reparació:",
"Turned on maintenance mode" : "Activat el mode de manteniment",
"Turned off maintenance mode" : "Desactivat el mode de manteniment",
"Maintenance mode is kept active" : "El mode de manteniment es manté activat",
"Updated database" : "Actualitzada la base de dades",
"Checked database schema update" : "S'ha comprobat l'actualització de l'esquema de la base de dades",
"Checking updates of apps" : "Comprobant actualitzacions de les aplicacions",
"Checked database schema update for apps" : "S'ha comprobat l'actualització de l'esquema de la base de dades per les apps",
"Updated \"%s\" to %s" : "Actualitzat \"%s\" a %s",
"Following apps have been disabled: %s" : "Les aplicacions següents s'han deshabilitat: %s",
"Already up to date" : "Ja actualitzat",
"Sunday" : "Diumenge",
"Monday" : "Dilluns",
"Tuesday" : "Dimarts",
"Wednesday" : "Dimecres",
"Thursday" : "Dijous",
"Friday" : "Divendres",
"Saturday" : "Dissabte",
"Sun." : "Dg.",
"Mon." : "Dl.",
"Tue." : "Dm.",
"Wed." : "Dc.",
"Thu." : "Dj.",
"Fri." : "Dv.",
"Sat." : "Ds.",
"Su" : "Dg",
"Mo" : "Dl",
"Tu" : "Dm",
"We" : "Dc",
"Th" : "Dj",
"Fr" : "Dv",
"Sa" : "Ds",
"January" : "Gener",
"February" : "Febrer",
"March" : "Març",
"April" : "Abril",
"May" : "Maig",
"June" : "Juny",
"July" : "Juliol",
"August" : "Agost",
"September" : "Setembre",
"October" : "Octubre",
"November" : "Novembre",
"December" : "Desembre",
"Jan." : "Gen.",
"Feb." : "Febr.",
"Mar." : "Març",
"Apr." : "Abr.",
"May." : "Maig",
"Jun." : "Juny",
"Jul." : "Jul.",
"Aug." : "Ag.",
"Sep." : "Set.",
"Oct." : "Oct.",
"Nov." : "Nov.",
"Dec." : "Des.",
"Settings" : "Configuració",
"Saving..." : "Desant...",
"Dismiss" : "Ignora",
"seconds ago" : "segons enrere",
"The link to reset your password has been sent to your email. If you do not receive it within a reasonable amount of time, check your spam/junk folders.<br>If it is not there ask your local administrator." : "L'enllaç per reiniciar la vostra contrasenya s'ha enviat al vostre correu. Si no el rebeu en un temps raonable comproveu les carpetes de spam. <br>Si no és allà, pregunteu a l'administrador local.",
"Your files are encrypted. If you haven't enabled the recovery key, there will be no way to get your data back after your password is reset.<br />If you are not sure what to do, please contact your administrator before you continue. <br />Do you really want to continue?" : "Els vostres fitxers estan encriptats. Si no heu habilitat la clau de recuperació no hi haurà manera de recuperar les dades després que reestabliu la contrasenya. <br />Si sabeu què fer, contacteu amb l'administrador abans de continuar.<br />Voleu continuar?",
"I know what I'm doing" : "Sé el que faig",
"Password can not be changed. Please contact your administrator." : "La contrasenya no es pot canviar. Contacteu amb l'administrador.",
"No" : "No",
"Yes" : "Sí",
"Choose" : "Escull",
"Error loading file picker template: {error}" : "Error en carregar la plantilla de càrrega de fitxers: {error}",
"Ok" : "D'acord",
"Error loading message template: {error}" : "Error en carregar la plantilla de missatge: {error}",
"read-only" : "Només de lectura",
"_{count} file conflict_::_{count} file conflicts_" : ["{count} conflicte de fitxer","{count} conflictes de fitxer"],
"One file conflict" : "Un fitxer en conflicte",
"New Files" : "Fitxers nous",
"Already existing files" : "Fitxers que ja existeixen",
"Which files do you want to keep?" : "Quin fitxer voleu conservar?",
"If you select both versions, the copied file will have a number added to its name." : "Si seleccioneu les dues versions, el fitxer copiat tindrà un número afegit al seu nom.",
"Cancel" : "Cancel·la",
"Continue" : "Continua",
"(all selected)" : "(selecciona-ho tot)",
"({count} selected)" : "({count} seleccionats)",
"Error loading file exists template" : "Error en carregar la plantilla de fitxer existent",
"Very weak password" : "Contrasenya massa feble",
"Weak password" : "Contrasenya feble",
"So-so password" : "Contrasenya passable",
"Good password" : "Contrasenya bona",
"Strong password" : "Contrasenya forta",
"Your web server is not yet set up properly to allow file synchronization because the WebDAV interface seems to be broken." : "El servidor web no està configurat correctament per permetre la sincronització de fitxers perquè la interfície WebDAV sembla no funcionar correctament.",
"This server has no working Internet connection. This means that some of the features like mounting external storage, notifications about updates or installation of third-party apps will not work. Accessing files remotely and sending of notification emails might not work, either. We suggest to enable Internet connection for this server if you want to have all features." : "Aquest servidor no té connexió a internet. Això significa que algunes de les característiques com el muntatge d'emmagatzemament extern, les notificacions quant a actualitzacions o la instal·lació d'aplicacions de tercers no funcionarà. L'accés remot a fitxers i l'enviament de correus electrònics podria tampoc no funcionar. Us suggerim que habiliteu la connexió a internet per aquest servidor si voleu tenir totes les característiques.",
"Error occurred while checking server setup" : "Hi ha hagut un error en comprovar la configuració del servidor",
"Your data directory and your files are probably accessible from the Internet. The .htaccess file is not working. We strongly suggest that you configure your web server in a way that the data directory is no longer accessible or you move the data directory outside the web server document root." : "La carpeta de dades i els vostres fitxers probablement són accessibles des d'Internet. El fitxer .htaccess no funciona. Us recomanem que configureu el servidor web de tal manera que la carpeta de dades no sigui accessible o que moveu la carpeta de dades fora de l'arrel de documents del servidor web.",
"You are accessing this site via HTTP. We strongly suggest you configure your server to require using HTTPS instead as described in our <a href=\"{docUrl}\">security tips</a>." : "Esteu accedint aquesta web a través de HTTP. Us recomanem que configureu el servidor per requerir HTTPS tal i com es descriu als <a href=\"{docUrl}\">consells de seguretat</a>",
"Shared" : "Compartit",
"Shared with {recipients}" : "Compartit amb {recipients}",
"Error" : "Error",
"Error while sharing" : "Error en compartir",
"Error while unsharing" : "Error en deixar de compartir",
"The public link will expire no later than {days} days after it is created" : "L'enllaç públic tindrà venciment abans de {days} dies després de crear-lo",
"Expiration" : "Expiració",
"Choose an expiration date" : "Escull una data de venciment",
"Expiration date is required" : "Data de venciment requerida",
"Delete {link}" : "Borrar {link}",
"Remove link" : "Borrar l'enllaç",
"Link" : "Enllaç",
"Create public link" : "Crear un enllaç públic",
"Edit" : "Editar",
"Remove" : "Elimina",
"Copy to clipboard" : "Copia al porta-papers",
"Social share" : "Xarxes Socials",
"There are currently no link shares, you can create one" : "Actualment no hi cap enllaç a les xarxes, en pots crear un",
"Anyone with the link has access to the file/folder" : "Qualsevol podrà accedir a l'arxiu o carpeta amb aquest link",
"Copied!" : "Copiat",
"Not supported!" : "No està suportat!",
"Choose a password" : "Introdueix una contrasenya",
"Password required" : "Es requereix de contrasenya ",
"Link name" : "Nom de l'enllaç",
"Name" : "Nom",
"Filename" : "Nom del fitxer",
"Password" : "Contrasenya",
"Edit link share: {name}" : "Edita l'enllaç compartit: {name}",
"Create link share: {name}" : "Crea un enllaç compartit: {name}",
"Share" : "Comparteix",
"Save" : "Desar",
"Remove password" : "Borra contrasenya",
"Share to Twitter. Opens in a new window." : "Compartir a Twitter. Obrirà una nova finestra",
"Share to Facebook. Opens in a new window." : "Compartir a Facbook. Obrirà una nova finestra",
"Share to Diaspora. Opens in a new window." : "Compartir a Diaspora. Obrirà una nova finestra",
"Share to Google+. Opens in a new window." : "Compartir a Google+. Obrirà una nova finestra",
"Share via email. Opens your mail client." : "Compartir via email. Obrirà el teu gestor de correu",
"Email link to person" : "Enllaç per correu electrónic amb la persona",
"Send copy to self" : "Enviar-me copia",
"Send link via email" : "Enviar enllaç via e-mail",
"Add personal message" : "Afegir comentari personal",
"Sending" : "Enviant",
"Shared with you and the group {group} by {owner}" : "Compartit amb vos i amb el grup {group} per {owner}",
"Shared with you by {owner}" : "Compartit amb vos per {owner}",
"group" : "grup",
"notify by email" : "notifica per correu electrònic",
"Unshare" : "Deixa de compartir",
"can share" : "pot compartir",
"can edit" : "pot editar",
"create" : "crea",
"change" : "canvi",
"delete" : "elimina",
"access control" : "control d'accés",
"Could not unshare" : "No es pot descompartir",
"User" : "Usuari",
"Group" : "Grup",
"Public Links" : "Enllaços públics",
"Share with people on other ownClouds using the syntax username@example.com/owncloud" : "Compartir amb la gent en altres ownClouds utilitzant la sintaxi username@example.com/owncloud",
"invisible" : "invisible",
"Delete" : "Esborra",
"Rename" : "Reanomena",
"The object type is not specified." : "No s'ha especificat el tipus d'objecte.",
"Enter new" : "Escriu nou",
"Add" : "Afegeix",
"Edit tags" : "Edita etiquetes",
"Error loading dialog template: {error}" : "Error en carregar la plantilla de diàleg: {error}",
"No tags selected for deletion." : "No heu seleccionat les etiquetes a eliminar.",
"unknown text" : "text desconegut",
"Hello world!" : "Hola món!",
"sunny" : "asolellat",
"Hello {name}, the weather is {weather}" : "Hola {name}, el temps és {weather}",
"Hello {name}" : "Hola {name}",
"new" : "Nou",
"_download %n file_::_download %n files_" : ["descarregar l'arxiu %n","descarregar arxius %n "],
"Updating to {version}" : "Actualitzant a la versió {version}",
"An error occurred." : "Ha fallat",
"Please reload the page." : "Carregueu la pàgina de nou.",
"The update was unsuccessful. Please report this issue to the <a href=\"https://github.com/owncloud/core/issues\" target=\"_blank\">ownCloud community</a>." : "L'actualització ha estat incorrecte. Comuniqueu aquest error a <a href=\"https://github.com/owncloud/core/issues\" target=\"_blank\">la comunitat ownCloud</a>.",
"The update was successful. There were warnings." : "La actualització ha estat exitosa. Hi ha alertes.",
"The update was successful. Redirecting you to ownCloud now." : "L'actualització ha estat correcte. Ara us redirigim a ownCloud.",
"Searching other places" : "Buscant altres ubicacions",
"No search results in other folders" : "No s'ha trobat res en altres carpetes",
"Personal" : "Personal",
"Users" : "Usuaris",
"Apps" : "Aplicacions",
"Admin" : "Administració",
"Help" : "Ajuda",
"Access forbidden" : "Accés prohibit",
"File not found" : "No s'ha trobat l'arxiu",
"The specified document has not been found on the server." : "El document especificat no s'ha trobat al servidor.",
"You can click here to return to %s." : "Pots clicar aquí per tornar a %s.",
"Hey there,\n\njust letting you know that %s shared %s with you.\nView it: %s\n\n" : "Ei,\n\nnomés fer-te saber que %s ha compartit %s amb tu.\nMira-ho a: %s\n\n",
"The share will expire on %s." : "La compartició venç el %s.",
"Cheers!" : "Salut!",
"Internal Server Error" : "Error Intern del Servidor",
"The server encountered an internal error and was unable to complete your request." : "El servidor ha trobat un error intern i no pot finalitzar la teva petició.",
"Technical details" : "Detalls tècnics",
"Remote Address: %s" : "Adreça remota: %s",
"Request ID: %s" : "Sol·licitud ID: %s ",
"Type: %s" : "Tipus: %s",
"Code: %s" : "Codi: %s",
"Message: %s" : "Missatge: %s",
"File: %s" : "Fitxer: %s",
"Line: %s" : "Línia: %s",
"Trace" : "Traça",
"Imprint" : "Imprint",
"Create an <strong>admin account</strong>" : "Crea un <strong>compte d'administrador</strong>",
"Username" : "Nom d'usuari",
"Storage & database" : "Emmagatzematge i base de dades",
"Data folder" : "Carpeta de dades",
"Configure the database" : "Configura la base de dades",
"Only %s is available." : "Només hi ha disponible %s",
"Install and activate additional PHP modules to choose other database types." : "Instal·la i activa mòduls PHP addicionals per seleccionar altres tipus de bases de dades.",
"For more details check out the documentation." : "Per més detalls consulteu la documentació.",
"Database user" : "Usuari de la base de dades",
"Database password" : "Contrasenya de la base de dades",
"Database name" : "Nom de la base de dades",
"Database tablespace" : "Espai de taula de la base de dades",
"Database host" : "Ordinador central de la base de dades",
"Performance warning" : "Alerta de rendiment",
"SQLite will be used as database." : "SQLite s'utilitzarà com a base de dades.",
"For larger installations we recommend to choose a different database backend." : "Per a instal·lacions més grans es recomana triar una base de dades diferent.",
"Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "L'ús de SQLite està desaconsellat especialment quan s'usa el client d'escriptori per sincronitzar els fitxers.",
"Finish setup" : "Acaba la configuració",
"Finishing …" : "Acabant...",
"Need help?" : "Necessites ajuda?",
"See the documentation" : "Consulti la documentació",
"Hey there,<br><br>just letting you know that %s shared <strong>%s</strong> with you.<br><a href=\"%s\">View it!</a><br><br>" : "Ei, <br><br>només fer-vos saber que %s us ha comparti <strong>%s</strong>. <br><a href=\"%s\">Mireu-ho!</a>",
"This application requires JavaScript for correct operation. Please {linkstart}enable JavaScript{linkend} and reload the page." : "Aquesta aplicació requereix Javascript per al seu correcte funcionament . Per favor, {linkstart}habiliti Javascript{linkend} i torni a carregar la pàgina.",
"Menu" : "Menú",
"Log out" : "Surt",
"Search" : "Cerca",
"Server side authentication failed!" : "L'autenticació del servidor ha fallat!",
"Please contact your administrator." : "Contacteu amb l'administrador.",
"An internal error occurred." : "Error intern",
"Please try again or contact your administrator." : "Intenti-ho de nou o posi's en contacte amb el seu administrador.",
"Login" : "Inici de sessió",
"Username or email" : "nom d'usuari o email",
"Wrong password. Reset it?" : "Contrasenya incorrecta. Voleu restablir-la?",
"Wrong password." : "Contrasenya incorrecta.",
"You are trying to access a private link. Please log in first." : "Estàs accedint a un enllaç privat. Necessites registrar-te primer.",
"Stay logged in" : "Mantén la sessió connectada",
"Alternative Logins" : "Acreditacions alternatives",
"Use the following link to reset your password: {link}" : "Useu l'enllaç següent per restablir la contrasenya: {link}",
"Password changed successfully" : "Contrasenya actualitzada correctament",
"New password" : "Contrasenya nova",
"New Password" : "Contrasenya nova",
"Reset password" : "Reinicialitza la contrasenya",
"This ownCloud instance is currently in single user mode." : "La instància ownCloud està en mode d'usuari únic.",
"This means only administrators can use the instance." : "Això significa que només els administradors poden usar la instància.",
"Contact your system administrator if this message persists or appeared unexpectedly." : "Contacteu amb l'administrador del sistema si aquest missatge persisteix o apareix inesperadament.",
"Thank you for your patience." : "Gràcies per la paciència.",
"Cancel login" : "Cancel·lar l'accés",
"An error occurred while verifying the token" : "Detectat un problema al verificar l'identificador",
"You are accessing the server from an untrusted domain." : "Esteu accedint al servidor des d'un domini no fiable",
"App update required" : "Cal que actualitzeu la aplicació",
"%s will be updated to version %s" : "%s s'actualitzarà a la versió %s",
"These apps will be updated:" : "Aquestes aplicacions s'actualitzaran:",
"The theme %s has been disabled." : "S'ha desactivat el tema %s",
"Please make sure that the database, the config folder and the data folder have been backed up before proceeding." : "Assegureu-vos que heu fet una còpia de seguretat de la base de dades, del fitxer de configuració i de la carpeta de dades abans de continuar.",
"Start update" : "Inicia l'actualització",
"To avoid timeouts with larger installations, you can instead run the following command from your installation directory:" : "Per evitar que s'esgoti el temps d'espera en instalacions grans, pots en el seu lloc fer córrer la següent comanda en el directori d'instalació. ",
"Update needed" : "Actualització necessària",
"This %s instance is currently in maintenance mode, which may take a while." : "Aquesta instància %s està actualment en manteniment i podria trigar una estona.",
"This page will refresh itself when the %s instance is available again." : "Aquesta pàgina s'actualitzarà automàticament quan la instància %s estigui disponible de nou."
},
"nplurals=2; plural=(n != 1);");
|
const yetifreeze = require("../objects/abilitys/yetitransform");
function yetitransformuse(aobjids, entities, creator) {
if (entities[creator] != undefined) {
if (!entities[creator].isdead) {
var objids = aobjids.giveid(true);
var a = new yetifreeze(entities[creator].radius, objids, entities[creator].id, entities[creator].x, entities[creator].y)
entities[objids] = a;
}
}
}
yetitransformuse.prototype = {}
module.exports = yetitransformuse |
import * as actionTypes from './Constants';
import axios from '../../axios';
export const authSuccess = (token) => {
return {
type: actionTypes.LOGIN,
token: token
}
}
export const logout=()=>{
localStorage.setItem('token',null);
return{
type:actionTypes.AUTH_LOGOUT
}
}
export const sendErrorMsg = (msg) => {
return {
type: actionTypes.ERROR,
msg: msg
}
}
export const login = (email, password) => {
return (dispatch) => {
const format = {
email: email,
password: password
}
axios.post('/login', format).then(res => {
const status = res.data.status;
if (status === 1) {
const token = res.data.token;
console.log(token);
localStorage.setItem('token', token);
dispatch(authSuccess(token));
}
else {
const msg = res.data.msg;
console.log(msg);
dispatch(sendErrorMsg(msg));
}
}).catch(err => {
console.log(err);
dispatch(sendErrorMsg(err));
})
}
}
export const register = (fname, lname, email, file, fileName, password,account) => {
return (dispatch) => {
const format = {
fname: fname,
lname: lname,
email: email,
image: file,
token: fileName,
password: password
}
const formData=new FormData();
formData.append('fname',fname);
formData.append('lname',lname);
formData.append('email',email);
formData.append('image',file);
formData.append('password',password);
formData.append('token',fileName);
formData.append('account',account);
axios.post('/register', formData,{
headers:{
'Content-Type':'multipart/form-data'
}
}).then(res => {
const status = res.data.status;
if (status == '1') {
const token = res.data.token;
localStorage.setItem('token', token);
dispatch(authSuccess(token));
}
else {
const msg = res.data.msg;
dispatch(sendErrorMsg(msg));
}
}).catch(err => {
console.log(err);
dispatch(sendErrorMsg(err));
});
}
}
export const checkAuth = () => {
return dispatch => {
let token = localStorage.getItem('token');
if (token) {
dispatch(authSuccess(token));
}
else {
dispatch(logout());
}
}
} |
import { Link } from "gatsby"
import PropTypes from "prop-types"
import React from "react"
import { css } from "linaria"
import { styled } from "linaria/react"
import { theming } from "../styles/theme"
const HeaderBorder = styled.header`
background-color: rebeccapurple;
margin-bottom: 1.45rem;
`
const Header = ({ siteTitle }) => (
<HeaderBorder>
<div
className={css`
margin: 0 auto;
max-width: 960;
padding: 1.45rem 1.0875rem;
`}
>
<h1 style={{ margin: 0 }}>
<Link
to="/"
className={css`
${theming(c => ({ color: c.headerText }))}
text-decoration: none;
`}
>
{siteTitle}
</Link>
</h1>
</div>
</HeaderBorder>
)
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
|
(function() {
'use strict';
angular.module('icarus')
// .service('FamiliarModalService', FamiliarModalService)
.controller('FamiliarModalController', FamiliarModalController);
FamiliarModalController.$inject = ['$scope', 'close'];
function FamiliarModalController($scope, close) {
$scope.close = close;
}
}());
|
var { defineSupportCode } = require('cucumber');
const MockApp = require('../../../../nodeMock/app');
const workAllocationMockData = require('../../../mockData/workAllocation/mockData');
const rolesAccessMockData = require('../../../mockData/workAllocation/rolesAccess');
const BrowserWaits = require('../../../../e2e/support/customWaits');
const taskListPage = require('../../../../e2e/features/pageObjects/workAllocation/taskListPage');
const taskManagerPage = require('../../../../e2e/features/pageObjects/workAllocation/taskManagerPage');
const taskAssignmentPage = require('../../../../e2e/features/pageObjects/workAllocation/taskAssignmentPage');
const caseDetailsPage = require('../../pageObjects/caseDetailsPage');
const headerPage = require('../../../../e2e/features/pageObjects/headerPage');
const CaseListPage = require('../../../../e2e/features/pageObjects/CaseListPage');
const errorPage = require('../../../../e2e/features/pageObjects/errorPage');
const SoftAssert = require('../../../util/softAssert');
const browserUtil = require('../../../util/browserUtil');
const errorMessageForResponseCode = require('../../../util/errorResonseMessage');
const MockUtil = require('../../../util/mockUtil');
const WAUtil = require('../../workAllocation/utils');
// const nodeAppMockData = require('../../../../nodeMock/nodeApp/mockData');
const CucumberReporter = require('../../../../codeceptCommon/reportLogger');
const headerpage = require('../../../../e2e/features/pageObjects/headerPage');
const taskActionPage = require('../../../../e2e/features/pageObjects/workAllocation/taskActionPage');
const TaskListTable = require('../../../../e2e/features/pageObjects/workAllocation/taskListTable');
const CaseListTable = require('../../../../e2e/features/pageObjects/workAllocation/casesTable');
const workAllocationDateUtil = require('../../../../e2e/features/pageObjects/workAllocation/common/workAllocationDateUtil');
const ArrayUtil = require("../../../../e2e/utils/ArrayUtil");
const workAllocationDataModel = require("../../../../dataModels/workAllocation");
const { DataTableArgument } = require('codeceptjs');
const taskListTable = new TaskListTable();
const waCaseListTable = new CaseListTable();
const TASK_SEARHC_FILTERS_TO_IGNORE_IN_REQUEST_BODY = {
'priority': 'Is out of scope and will be removed as part of https://tools.hmcts.net/jira/browse/EUI-4809',
'taskType': 'Is to be includes only in 2.1 till the it will be ignored in test'
}
When('I click task list pagination link {string} and wait for req reference {string} not null', async function (paginationLinktext, reference) {
await taskListTable.waitForTable();
await BrowserWaits.retryWithActionCallback(async () => {
// const val = await browserUtil.addTextToElementWithCssSelector('tbody tr .cdk-column-case_category exui-task-field,tbody tr .cdk-column-case_category exui-work-field', 'Sort test', true);
// if (val !== "success"){
// throw new Error(JSON.stringify(val));
// }
await taskListTable.clickPaginationLink(paginationLinktext);
await BrowserWaits.waitForConditionAsync(async () => {
const caseCatColVal = await taskListTable.getColumnValueForTaskAt('Case category', 1);
CucumberReporter.AddMessage('OnPagination page refresh dinee: ' + !caseCatColVal.includes('Sort test'));
return !caseCatColVal.includes('Sort test');
});
await browser.sleep(2)
// await BrowserWaits.waitForConditionAsync(async () => {
// return global.scenarioData[reference] !== null
// }, 5000);
});
});
When('I click WA case list pagination link {string} and wait for req reference {string} not null', async function (paginationLinktext, reference) {
await waCaseListTable.waitForTable();
await BrowserWaits.retryWithActionCallback(async () => {
const val = await browserUtil.addTextToElementWithCssSelector('tbody tr .cdk-column-case_category exui-task-field,tbody tr .cdk-column-case_category exui-work-field', 'Sort test', true);
if (val !== "success") {
throw new Error(JSON.stringify(val));
}
await waCaseListTable.clickPaginationLink(paginationLinktext);
await BrowserWaits.waitForConditionAsync(async () => {
const caseCatColVal = await waCaseListTable.getColumnValueForCaseAt('Case category', 1);
return !caseCatColVal.includes('Sort test');
});
await BrowserWaits.waitForConditionAsync(async () => {
return global.scenarioData[reference] !== null
}, 5000);
});
});
Then('I validate task search request with reference {string} has pagination parameters', async function (requestReference, datatable) {
const reqBody = global.scenarioData[requestReference];
const datatableHash = datatable.parse().hashes()[0];
expect(reqBody.searchRequest.pagination_parameters.page_number).to.equal(parseInt(datatableHash.PageNumber));
expect(reqBody.searchRequest.pagination_parameters.page_size).to.equal(parseInt(datatableHash.PageSize));
});
Then('I validate task search request with reference {string} have search parameters', async function (requestReference, datatable) {
const softAssert = new SoftAssert();
const reqBody = global.scenarioData[requestReference];
const datatableHash = datatable.parse().hashes();
CucumberReporter.AddMessage("Req body received:");
CucumberReporter.AddJson(reqBody);
const reqSearchParams = reqBody.searchRequest.search_parameters;
for (let i = 0; i < datatableHash.length; i++) {
searchHash = datatableHash[i];
if (Object.keys(TASK_SEARHC_FILTERS_TO_IGNORE_IN_REQUEST_BODY).includes(searchHash.key)){
CucumberReporter.AddMessage(`${searchHash.key} is ignored for eeason : ${TASK_SEARHC_FILTERS_TO_IGNORE_IN_REQUEST_BODY[searchHash.key]}`);
continue;
}
const searchParamObj = await ArrayUtil.filter(reqSearchParams, async (searchObj) => searchObj.key === searchHash.key);
softAssert.setScenario(`Search param with key ${searchHash.key} is present`);
if (searchHash.value !== ''){
await softAssert.assert(async () => expect(searchParamObj.length > 0).to.be.true);
}
if (searchParamObj.length > 0) {
if (searchHash.value && searchHash.value !== ""){
softAssert.setScenario(`Search param with key ${searchHash.key} and values ${searchHash.value} is present`);
if (searchHash.value !== ''){
await softAssert.assert(async () => expect(searchParamObj[0].values).to.includes(searchHash.value));
}
}
if (searchHash.size) {
softAssert.setScenario(`Search param with key ${searchHash.key} and has value count ${searchHash.size}`);
await softAssert.assert(async () => expect(searchParamObj[0].values.length).to.equal(parseInt(searchHash.size)));
}
}
}
softAssert.finally();
});
Then('I validate task search request with reference {string} does not have search parameters', async function (requestReference, datatable) {
const softAssert = new SoftAssert();
const reqBody = global.scenarioData[requestReference];
const datatableHash = datatable.parse().hashes();
const reqSearchParams = reqBody.searchRequest.search_parameters;
for (let i = 0; i < datatableHash.length; i++) {
searchHash = datatableHash[i];
if (Object.keys(TASK_SEARHC_FILTERS_TO_IGNORE_IN_REQUEST_BODY).includes(searchHash.key)) {
CucumberReporter.AddMessage(`${searchHash.key} is ignored for eeason : ${TASK_SEARHC_FILTERS_TO_IGNORE_IN_REQUEST_BODY[searchHash.key]}`);
continue;
}
const searchParamObj = await ArrayUtil.filter(reqSearchParams, async (searchObj) => searchObj.key === searchHash.key);
softAssert.setScenario(`Search param with key ${searchHash.key} is present`);
if (searchParamObj.length > 0) {
softAssert.setScenario(`Search param with key ${searchHash.key} and values ${searchHash.values} is present`);
await softAssert.assert(async () => expect(searchParamObj[0].values).to.not.includes(searchHash.value));
}
}
softAssert.finally();
});
Then('I validate task search request with reference {string} does not have search patameter key {string}', async function (requestReference, searchKey) {
const reqBody = global.scenarioData[requestReference];
const reqSearchParams = reqBody.searchRequest.search_parameters;
const searchParametersMatchingType = await ArrayUtil.filter(reqSearchParams, async (searchObj) => searchObj.key === searchKey);
expect(searchParametersMatchingType.length, `Search parameter mathcing key "${searchKey}" found in request body ${reqBody} `).to.equal(0);
});
Given('I set MOCK case workers for release {string}', async function(forRelease,datatable){
const persons = getPersonResponse(datatable);
let url = null;
if (forRelease === "1"){
MockApp.onGet('workallocation/caseworker', (req,res) => {
res.send(persons);
});
} else if (forRelease === "2"){
MockApp.onGet('workallocation2/caseworker', (req, res) => {
res.send(persons);
});
} else{
throw new Error(`Unexpected release identifier "${forRelease}" passed to setup mock`);
}
});
Then('I validate task table values displayed', async function(datatable){
await validateTaskTableValues(datatable);
});
Then('If current user {string} is {string}, I validate task table values displayed', async function (currentUser,validationForUserType ,datatable) {
if (currentUser === validationForUserType){
await validateTaskTableValues(datatable);
}
});
Given('I have workallocation on boarded services {string}', async function(onboardedServices){
workAllocationMockData.updateWASupportedJurisdictions(onboardedServices.split(",")) ;
});
// Given('I set MOCK case roles', async function(datatable){
// const caseRoles = [];
// const tableRowHashes = datatable.parse().hashes();
// for (const row of tableRowHashes) {
// const mockCaseRole = rolesAccessMockData.dataModel.getCaseRole();
// caseRoles.push(mockCaseRole)
// const hashkeys = Object.keys(row);
// for (let j = 0; j < hashkeys.length; j++) {
// const key = hashkeys[j];
// // if (key.includes('start') || key.includes('end') || key.includes('created')) {
// // mockCaseRole[key] = workAllocationDateUtil.getDateFormat(row[key],"YYYY-MM-DD");
// // }else{
// // mockCaseRole[key] = row[key];
// // }
// mockCaseRole[key] = row[key];
// }
// }
// rolesAccessMockData.caseRoles = caseRoles;
// });
async function validateTaskTableValues(datatable){
const tableRowHashes = datatable.parse().hashes();
const softAssert = new SoftAssert();
for (let i = 0; i < tableRowHashes.length; i++) {
const expectRowHash = tableRowHashes[i];
const rowNum = parseInt(expectRowHash["row"]);
const hashkeys = Object.keys(expectRowHash);
for (let j = 0; j < hashkeys.length; j++) {
const columnName = hashkeys[j];
let expectedValue = expectRowHash[columnName];
if (columnName.includes('Due date')){
expectedValue = workAllocationDateUtil.getTaskDueDateDisplayString(expectedValue);
}
if (columnName.includes('Task created')) {
expectedValue = workAllocationDateUtil.getTaskCeateDateDisplayString(expectedValue);
}
if (columnName.includes('Hearing date')) {
expectedValue = workAllocationDateUtil.getDurationDateDisplayString(expectedValue);
}
let actualColumnValue = null;
if (columnName === "row") {
continue;
} else {
actualColumnValue = await taskListTable.getColumnValueForTaskAt(columnName, rowNum)
}
const assertionMessage = `At row ${rowNum} validation of column ${columnName}`;
softAssert.setScenario(assertionMessage);
await softAssert.assert(async () => expect(actualColumnValue.toLowerCase(), assertionMessage).to.includes(expectedValue.toLowerCase()));
}
}
softAssert.finally();
}
function getLocationsResponse(datatable){
const locationHashes = datatable.parse().hashes();
const locations = [];
for (let i = 0; i < locationHashes.length; i++) {
const locationFromDatatable = locationHashes[i];
const location = workAllocationDataModel.getLocation();
const locationInputKeys = Object.keys(locationFromDatatable);
for (let j = 0; j < locationInputKeys.length; j++) {
const key = locationInputKeys[j];
location[key] = locationFromDatatable[key];
}
locations.push(location);
}
return locations;
}
function getPersonResponse(datatable){
const personHashes = datatable.parse().hashes();
const personsData = [];
for (let i = 0; i < personHashes.length;i++){
const personFromDatatable = personHashes[i];
const person = workAllocationDataModel.getCaseWorkerOrperson();
const personInputKeys = Object.keys(personFromDatatable);
for (let j = 0; j < personInputKeys.length;j++ ){
const key = personInputKeys[j];
if (key === "location.id"){
person.location.id = personFromDatatable[key]
} else if (key === "location.locationName"){
person.location.locationName = personFromDatatable[key]
}else{
person[key] = personFromDatatable[key];
}
}
personsData.push(person);
}
return personsData;
}
|
/**
* Created by liqing on 2016/4/13.
*/
describe('Test Restaurant service', function(){
var $q, deferred, $rootScope;
var pizzaPit;
var Restaurant, Person;
var $log;
beforeEach(module('Scrum'));
beforeEach(inject(function(_$q_, _$rootScope_, _$log_, RestaurantService, PersonService){
$q = _$q_;
deferred = $q.defer();
$rootScope = _$rootScope_;
Restaurant = RestaurantService;
Person = PersonService;
}));
console.log(Person);
//pizzaPit = new Restaurant();
//var pizzaDelivered = pizzaPit.takeOrder('Capricciosa');
var pawl = new Person('Pawl');
//pizzaDelivered.then(pawl.eat, pawl.beHungry);
//pizzaPit.problemWithOrder('no Capricciosa, only Margherits left');
//
//it('should log', function(){
// expect($log.warn.logs).toContain(['Pawl is hungry, because no Capricciosa, only Margherits left']);
//})
}); |
import React from 'react';
import AddTemplate from '../../../components/Template/AddTemplate/addTemplate';
function addTemplatepage() {
return (
<AddTemplate />
)
}
export default addTemplatepage
|
const expect = require('expect.js');
const part1 = require('./part1');
const part2 = require('./part2');
describe('Day 14: Part 1', () => {
it('Can calculate required ORE for 1 FUEL', () => {
expect(part1(`9 ORE => 2 A
8 ORE => 3 B
7 ORE => 5 C
3 A, 4 B => 1 AB
5 B, 7 C => 1 BC
4 C, 1 A => 1 CA
2 AB, 3 BC, 4 CA => 1 FUEL`)).to.eql(165);
});
it('Can calculate required ORE for 1 FUEL 2', () => {
expect(part1(`157 ORE => 5 NZVS
165 ORE => 6 DCFZ
44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL
12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ
179 ORE => 7 PSHF
177 ORE => 5 HKGWZ
7 DCFZ, 7 PSHF => 2 XJWVT
165 ORE => 2 GPVTF
3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT`)).to.eql(13312);
});
it('Can calculate required ORE for 1 FUEL 3', () => {
expect(part1(`171 ORE => 8 CNZTR
7 ZLQW, 3 BMBT, 9 XCVML, 26 XMNCP, 1 WPTQ, 2 MZWV, 1 RJRHP => 4 PLWSL
114 ORE => 4 BHXH
14 VRPVC => 6 BMBT
6 BHXH, 18 KTJDG, 12 WPTQ, 7 PLWSL, 31 FHTLT, 37 ZDVW => 1 FUEL
6 WPTQ, 2 BMBT, 8 ZLQW, 18 KTJDG, 1 XMNCP, 6 MZWV, 1 RJRHP => 6 FHTLT
15 XDBXC, 2 LTCX, 1 VRPVC => 6 ZLQW
13 WPTQ, 10 LTCX, 3 RJRHP, 14 XMNCP, 2 MZWV, 1 ZLQW => 1 ZDVW
5 BMBT => 4 WPTQ
189 ORE => 9 KTJDG
1 MZWV, 17 XDBXC, 3 XCVML => 2 XMNCP
12 VRPVC, 27 CNZTR => 2 XDBXC
15 KTJDG, 12 BHXH => 5 XCVML
3 BHXH, 2 VRPVC => 7 MZWV
121 ORE => 7 VRPVC
7 XCVML => 6 RJRHP
5 BHXH, 4 VRPVC => 5 LTCX`)).to.eql(2210736);
});
});
describe('Day 14: Part 2', () => {
it('Can calculate FUEL for trillion ORE', () => {
expect(part2(`157 ORE => 5 NZVS
165 ORE => 6 DCFZ
44 XJWVT, 5 KHKGT, 1 QDVJ, 29 NZVS, 9 GPVTF, 48 HKGWZ => 1 FUEL
12 HKGWZ, 1 GPVTF, 8 PSHF => 9 QDVJ
179 ORE => 7 PSHF
177 ORE => 5 HKGWZ
7 DCFZ, 7 PSHF => 2 XJWVT
165 ORE => 2 GPVTF
3 DCFZ, 7 NZVS, 5 HKGWZ, 10 PSHF => 8 KHKGT`)).to.eql(82892753);
});
it('Can calculate FUEL for trillion ORE 2', () => {
expect(part2(`171 ORE => 8 CNZTR
7 ZLQW, 3 BMBT, 9 XCVML, 26 XMNCP, 1 WPTQ, 2 MZWV, 1 RJRHP => 4 PLWSL
114 ORE => 4 BHXH
14 VRPVC => 6 BMBT
6 BHXH, 18 KTJDG, 12 WPTQ, 7 PLWSL, 31 FHTLT, 37 ZDVW => 1 FUEL
6 WPTQ, 2 BMBT, 8 ZLQW, 18 KTJDG, 1 XMNCP, 6 MZWV, 1 RJRHP => 6 FHTLT
15 XDBXC, 2 LTCX, 1 VRPVC => 6 ZLQW
13 WPTQ, 10 LTCX, 3 RJRHP, 14 XMNCP, 2 MZWV, 1 ZLQW => 1 ZDVW
5 BMBT => 4 WPTQ
189 ORE => 9 KTJDG
1 MZWV, 17 XDBXC, 3 XCVML => 2 XMNCP
12 VRPVC, 27 CNZTR => 2 XDBXC
15 KTJDG, 12 BHXH => 5 XCVML
3 BHXH, 2 VRPVC => 7 MZWV
121 ORE => 7 VRPVC
7 XCVML => 6 RJRHP
5 BHXH, 4 VRPVC => 5 LTCX`)).to.eql(460664);
});
});
|
import { connect } from 'react-redux'
import ParameterTuning from '../components/prediction-core/ParameterTuning'
const mapStateToProps = (state, previousProps) =>({
active: state.active
})
export default connect(
mapStateToProps
)(ParameterTuning) |
/**
* @name HoldGroup
* @author Oleg Kaplya
* @overview HoldGroup model
*/
'use strict';
module.exports = function(sequelize, DataTypes) {
var HoldGroup = sequelize.define('hold_group', {
event_id: DataTypes.INTEGER,
venue_id: DataTypes.INTEGER,
title: DataTypes.STRING
}, {
underscored: true
});
return HoldGroup;
};
|
import React, { Component } from 'react';
import { NavLink, Route } from 'react-router-dom';
import { Container } from 'semantic-ui-react';
import ClientListPage from './pages/ClientListPage';
import ClientFormPage from './pages/ClientFormPage';
class App extends Component {
render() {
return (
<Container>
<div className="ui two item menu">
<NavLink className="item" activeClassName="active" exact to="/">
Client list
</NavLink>
<NavLink className="item" activeClassName="active" exact to="/clients/new">
New client
</NavLink>
</div>
<Route exact path="/" component={ClientListPage}/>
<Route path="/clients/new" component={ClientFormPage}/>
<Route path="/clients/edit/:id" component={ClientFormPage}/>
</Container>
);
}
}
export default App;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.