text
stringlengths 7
3.69M
|
|---|
import * as actionTypes from './actionTypes';
export const saveRes = (result) => {
const updatedRes = result * 2; // galima det ir i reducer logika, bet kur geriau?
return {
type: actionTypes.STORE_RESULT,
result: updatedRes
}
}
export const storeRes = (result) => {
return (dispatch, getState) => {
setTimeout(() => {
// const oldCounter = getState().ctr.counter;
// console.log(oldCounter);
dispatch(saveRes(result))
}, 2000)
}
}
export const deleteRes = (resElId) => {
return {
type: actionTypes.DELETE_RESULT,
resultElId: resElId
}
}
|
import app from '../bin/server';
import supertest from 'supertest';
import { cleanDb, authUser } from './utils';
import User from '../src/models/users';
import Feed from '../src/models/feeds';
const request = supertest.agent(app.callback());
const fixtures = {
user: {
username: 'login_feed', password: 'pass'
},
feed: {
title: 'Great history', content: 'Text here'
},
emptyFeed: {
title: '', content: ''
},
token: null,
unexistentFeedId: '12345678901234f69e3105b6',
wrongFeedId: '123',
editedFeed: { title: 'Great history2', content: 'New text here' }
};
const userData = {
user: null,
token: null
}
beforeAll(async () => {
// runs before all tests in this block
cleanDb();
const user = new User(fixtures.user);
await user.save();
userData.user = user;
userData.token = user.generateToken();
});
const urlPrefix = '/api/v1/feeds';
describe('Users', () => {
describe(`POST ${urlPrefix} - create feed`, () => {
it('Create feed without authorization', async () => {
const response = await request
.post(urlPrefix)
.send({ title: 'text', content: 'content' });
expect(response.status).toBe(401);
});
it('Create feed with wrong params', async () => {
const { token } = userData;
const response = await request
.post(urlPrefix)
.set('x-access-token', token)
.send(fixtures.emptyFeed);
expect(response.status).toBe(400);
expect(response.body.errors.title[0]).toBe('Title should be not empty');
expect(response.body.errors.content[0]).toBe('Content should be not empty');
});
it('Create feed', async () => {
const { token } = userData;
const response = await request
.post(urlPrefix)
.set('x-access-token', token)
.send(fixtures.feed);
const { _id: feedId } = response.body.feed;
expect(response.status).toBe(200);
expect(await Feed.findById(feedId)).toEqual(expect.objectContaining({
title: fixtures.feed.title,
content: fixtures.feed.content
}));
});
});
describe(`GET ${urlPrefix} - create feed`, () => {
it('Get feeds', async () => {
const { user } = userData;
const feed = new Feed({
...fixtures.feed,
creator: user._id
});
await feed.save();
const { _id: id } = feed;
const response = await request
.get(`${urlPrefix}`)
expect(response.status).toBe(200);
expect(response.body.feeds).toEqual(
expect.arrayContaining([
expect.objectContaining({
_id: expect.any(String),
title: expect.any(String),
content: expect.any(String)
})
])
);
});
});
describe(`GET ${urlPrefix}/:id - get feed`, () => {
it('Get unexistent feed', async () => {
const response = await request
.get(`${urlPrefix}/${fixtures.unexistentFeedId}`);
expect(response.status).toBe(404);
});
it('Get feed with wrong id', async () => {
const response = await request
.get(`${urlPrefix}/${fixtures.wrongFeedId}`);
expect(response.status).toBe(404);
});
it('Get feed', async () => {
const { token, user } = userData;
const feed = new Feed({
...fixtures.feed,
creator: user._id
});
await feed.save();
const { _id: id } = feed;
const response = await request
.get(`${urlPrefix}/${id}`)
expect(response.status).toBe(200);
expect(response.body.feed).toEqual(expect.objectContaining({
title: fixtures.feed.title,
content: fixtures.feed.content
}));
});
});
describe(`PUT ${urlPrefix} - create feed`, () => {
it('Update feed with wrong params', async () => {
const { token, user } = userData;
const feed = new Feed({
...fixtures.feed,
creator: user._id
});
await feed.save();
const { _id: id } = feed;
const response = await request
.put(`${urlPrefix}/${id}`)
.set('x-access-token', token)
.send(fixtures.emptyFeed);
expect(response.status).toBe(400);
expect(response.body.errors.title[0]).toBe('Title should be not empty');
expect(response.body.errors.content[0]).toBe('Content should be not empty');
});
it('Update feed', async () => {
const { token, user } = userData;
const feed = new Feed({
...fixtures.feed,
creator: user._id
});
await feed.save();
const { _id: id } = feed;
const response = await request
.put(`${urlPrefix}/${id}`)
.set('x-access-token', token)
.send(fixtures.editedFeed);
expect(response.status).toBe(200);
expect(await Feed.findById(feed.id)).toEqual(expect.objectContaining({
title: fixtures.editedFeed.title,
content: fixtures.editedFeed.content
}));
});
});
describe(`DELETE ${urlPrefix} - delete feed`, () => {
it('Update feed', async () => {
const { token, user } = userData;
const feed = new Feed({
...fixtures.feed,
creator: user._id
});
await feed.save();
const { _id: id } = feed;
const response = await request
.delete(`${urlPrefix}/${id}`)
.set('x-access-token', token);
expect(response.status).toBe(200);
expect(response.body._id).toBe(id.toHexString());
expect(await Feed.findById(feed.id)).toBe(null);
});
});
});
|
import { createContext } from 'react';
import { io } from 'socket.io-client';
const SocketContext = createContext('');
export { SocketContext };
const socket = io();
console.log('context');
const SocketProvider = (props) => {
return (
<SocketContext.Provider value={socket}>
{props.children}
</SocketContext.Provider>
);
};
export default SocketProvider;
|
const User = require('../models/User');
const mongoose = require('mongoose');
const { validationResult } = require('express-validator');
exports.createUser = async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
//extract email, userId (firebase), firstName, familyName
const { email, userId, firstName, familyName } = req.body;
try {
let user = new User({
_id: userId,
firstName: firstName,
familyName: familyName,
email: email,
});
await user.save();
return res.json({ user });
} catch (error) {
console.log(error);
res.status(400).send('Could not create user');
}
};
|
var searchData=
[
['main_0',['main',['../_number_mngr_8cpp.html#ae66f6b31b5ad750f1fe042a706a4e3d4',1,'NumberMngr.cpp']]],
['myfileout_1',['myFileOut',['../class_paged_array.html#a2a1d4dfb93bace7757baba3a3705d18f',1,'PagedArray']]]
];
|
import React from 'react';
import {connect} from "react-redux";
import MovieCard from "./movieCard";
import {loadMoviesRequest} from "../redux/actions/actions"
import Modal from "./Modal";
import {config} from "../api/defaultConfig";
import {toDisplayDate, toPercentage} from "../util/mapper";
import navTo from "../util/navigation";
class MovieCards extends React.Component {
constructor(props) {
super(props);
!this.props.movies && this.props.loadMoviesRequest();
}
navToDetails(movieId) {
navTo(`details:${movieId}`);
}
componentDidUpdate(prevProps) {
if (this.props.showDetails) {
this.navToDetails(this.props.id);
}
}
render() {
return <ul className="card-container">
<Modal className="modal" show={this.props.isLoading}/>
{this.props.movies && this.props.movies.map((movie) => {
const {id, fullPath, releaseDate, title, rating} = this.getMovieDetails(movie);
return <MovieCard key={id} id={id} fullPath={fullPath} releaseDate={releaseDate} title={title}
rating={rating}/>
})}
</ul>;
}
getMovieDetails(movie) {
const id = movie.id;
const imgBase = config.mobile_card_base;
const imgPath = movie.poster_path;
const fullPath = imgBase + imgPath;
const releaseDate = toDisplayDate(movie.release_date);
const title = movie.title;
const rating = toPercentage(movie.vote_average);
return {id, fullPath, releaseDate, title, rating};
}
};
const mapDispatchToProps = {
loadMoviesRequest
};
function mapStateToProps(state, props) {
return {
isLoading: state.moviesReducer.isLoading,
id: state.moviesReducer.id,
showDetails: state.moviesReducer.showDetails,
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MovieCards);
|
// libraries and auxiliary modules
var angular = require('angular');
var uiRouter = require('angular-ui-router');
var ngMessages = require('angular-messages');
var angularMaterial = require('angular-material');
// main module with dependencies
var app = angular.module('app', [uiRouter, angularMaterial, ngMessages]);
// services
require('./services/auth.user.service')(app);
require('./services/appstate.service')(app);
require('./services/user.service')(app);
require('./services/quiz.service')(app);
require('./services/test.service')(app);
// directives
require('./directives/login/login.directive')(app);
require('./directives/menu/menu.directive')(app);
require('./directives/flash/flash.directive')(app);
// features
require('./features/home/')(app);
require('./features/quizedit/')(app);
require('./features/quizlist/')(app);
require('./features/testedit/')(app);
require('./features/testlist/')(app);
// routes
require('./routes')(app);
// debugging
console.log('app loaded, hipertxoopie!');
|
var ChampionCacheRepository = require("../repositories/ChampionCacheRepository");
/**
* The service for managing champion data
*/
function ChampionCacheService() {
}
/**
* Caches all the champions
* @param : callback - the function to call once the operation is complete.
*/
ChampionCacheService.prototype.CacheChampions = function(callback)
{
ChampionCacheRepository.InvalidateCache(callback);
};
/**
* Gets all champion data from the cache
* @param : callback - the function to call once the operation is complete.
*/
ChampionCacheService.prototype.GetAll = function(callback)
{
ChampionCacheRepository.ReadAll(callback);
};
/**
* Gets a champions data from the cache by id
* @param : id - the champions unique id
* @param : callback - the function to call once the operation is complete.
*/
ChampionCacheService.prototype.GetById = function(id, callback)
{
ChampionCacheRepository.ReadById(id, callback);
};
/**
* Links the champion data with the mastery data of a summoner
* @param : masteries - A summoners champion masteries to be linked with the champion data
* @param : callback - the function to call once the operation is complete.
*/
ChampionCacheService.prototype.LinkMasteriesToChampions = function(masteries, callback)
{
var self = this;
ChampionCacheRepository.ReadAll(function(err, champions){
var linkedChamps = [];
for(var i = 0; i < masteries.length; i++){
for(var j = 0; j < champions.length; j++){
if(champions[j].id == masteries[i].championId){
var object = {"Champion": champions[j], "Mastery": masteries[i]};
linkedChamps.push(object);
break;
}
}
}
callback(null, linkedChamps);
});
};
module.exports = new ChampionCacheService;
|
'use strict';
import express from 'express';
import { getProduct, saveProduct, updateProduct, deleteProduct } from '../controllers/product.controller.js';
const product = express.Router();
product.post('/get', getProduct);
product.post('/save', saveProduct);
product.post('/update/:id', updateProduct);
product.post('/delete/:id', deleteProduct);
export default product;
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import CarListItem from '../components/car-list-item';
export class CarList extends Component {
shouldComponentUpdate(nextProps, nextState) {
return nextProps.carsState !== this.props.carsState;
}
render() {
return (
<div className="car-list">
<table className="table is-narrow">
<thead>
<tr>
<th className="table-header">Placa</th>
<th className="table-header">Modelo</th>
<th className="table-header">Marca</th>
<th className="table-header">Foto</th>
<th className="table-header">Combustivel</th>
<th className="table-header">Valor</th>
<th className="table-header"></th>
</tr>
</thead>
<tbody>
{this.renderItems()}
</tbody>
</table>
</div>
);
}
renderItems = (toogleModal, onDelete) => {
const pagination = this.props.carsState.get('pagination');
return pagination.get('data').map(car =>
<CarListItem
key={`car-${car.get('id')}-${car.get('marca')}-${car.get('modelo')}`}
car={car}
onEdit={this.props.toogleModal}
onDelete={this.props.onDelete}
/>
);
}
}
const mapStateToProps = (state) => {
return {
carsState: state.cars
};
}
export default connect(mapStateToProps)(CarList);
|
global.ENV_CONFIG = {
debug_enabled:true,
absolute_app_path:''
}
ENV_CONFIG.absolute_app_path = process.argv[1];
|
// Settings for our app. The 'require' call in server.js returns
// whatever we assign to 'module.exports' in this file
module.exports = {
twitter: {
// You need to go to dev.twitter.com and register your own app to get these!
consumerKey: 'BQivLThJOjZPET3uMYeNqw',
consumerSecret: 'ZWuqetEzKriWgMlgyC2HeuSShj2OOHfExC76TSqLwA',
// Hint: point this to 127.0.0.1 via /etc/hosts for easy testing with a
// URL that Twitter will accept. On your production server change to
// a real hostname. I have two apps registered with Twitter,
// justjs (the real one) and devjustjs (for testing on my own computer)
callbackURL: 'http://jobney-refresh.herokuapp.com/auth/twitter/callback'
},
github: {
//var GITHUB_CLIENT_ID = "26504acf98eae0ca8245";
//var GITHUB_CLIENT_SECRET = "7dbc72cd458e1258d640a8648d5c85e61ded76dc";
clientID: '26504acf98eae0ca8245',
clientSecret: '7dbc72cd458e1258d640a8648d5c85e61ded76dc',
callbackURL: "http://jobney-refresh.herokuapp.com/auth/github/callback",
customHeaders: {"User-Agent": "justinobney/learn-nodejs"}
},
http: {
port: process.env.PORT || 3000
},
// You should use a secret of your own to authenticate session cookies
sessionSecret: 'sfjnrfunpiu',
google: {
returnURL: 'http://jobney-refresh.herokuapp.com/auth/google/callback',
realm: 'http://jobney-refresh.herokuapp.com'
}
};
|
import React from "react"
import Link from "gatsby-link"
import presets from "../utils/presets"
import colors from "../utils/colors"
import { rhythm, scale, options } from "../utils/typography"
import { JSIcon, WebpackIcon, ReactJSIcon, GraphQLIcon } from "../assets/logos"
import { vP, vPHd, vPVHd, vPVVHd } from "../components/gutters"
import Container from "../components/container"
import Masthead from "../components/masthead"
import Cards from "../components/cards"
import Card from "../components/card"
import CardHeadline from "../components/card-headline"
import Diagram from "../components/diagram"
import BlogPostPreviewItem from "../components/blog-post-preview-item"
import FuturaParagraph from "../components/futura-paragraph"
import CtaButton from "../components/cta-button"
import TechWithIcon from "../components/tech-with-icon"
const IndexRoute = React.createClass({
render() {
console.log(this.props)
const blogPosts = this.props.data.allMarkdownRemark
return (
<div>
<Masthead />
<div
css={{
margin: rhythm(presets.gutters.default / 2),
[presets.Hd]: {
margin: vP,
marginTop: 0,
},
}}
>
<Cards>
<Card>
<CardHeadline>Modern web tech without the headache</CardHeadline>
<FuturaParagraph>
Enjoy the power of the latest web technologies –{` `}
<TechWithIcon icon={ReactJSIcon}>React.js</TechWithIcon>,{` `}
<TechWithIcon icon={WebpackIcon}>Webpack</TechWithIcon>,{` `}
modern JavaScript and CSS and more — all setup and waiting for
you to start building.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline>Bring your own data</CardHeadline>
<FuturaParagraph>
Gatsby’s rich data plugin ecosystem lets you build sites with
the data you want — from one or many sources: Pull data from
headless CMSs, SaaS services, APIs, databases, your file system
& more directly into your pages using{` `}
<TechWithIcon icon={GraphQLIcon}>GraphQL</TechWithIcon>.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline>Scale to the entire internet</CardHeadline>
<FuturaParagraph>
Gatsby.js is Internet Scale. Forget complicated deploys with
databases and servers and their expensive, time-consuming setup
costs, maintenance, and scaling fears. Gatsby.js builds your
site as “static” files which can be deployed easily on dozens of
services.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline css={{ color: presets.brandDark }}>
Future-proof your website
</CardHeadline>
<FuturaParagraph>
Don't build a website with last decade's tech. The future of the
web is mobile, JavaScript and APIs—the {` `}
<a href="https://jamstack.org/">JAMstack</a>. Every website is a
web app and every web app is a website. Gatsby.js is the
universal JavaScript framework you’ve been waiting for.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline>
<em css={{ color: presets.brand, fontStyle: `normal` }}>
Static
</em>
{` `}
Progressive Web Apps
</CardHeadline>
<FuturaParagraph>
Gatsby.js is a static PWA (Progressive Web App) generator. You
get code and data splitting out-of-the-box. Gatsby loads only
the critical HTML, CSS, data, and JavaScript so your site loads
as fast as possible. Once loaded, Gatsby prefetches resources
for other pages so clicking around the site feels incredibly
fast.
</FuturaParagraph>
</Card>
<Card>
<CardHeadline>Speed past the competition</CardHeadline>
<FuturaParagraph>
Gatsby.js builds the fastest possible website. Instead of
waiting to generate pages when requested, pre-build pages and
lift them into a global cloud of servers — ready to be delivered
instantly to your users wherever they are.
</FuturaParagraph>
</Card>
<Diagram
containerCSS={{
borderTopLeftRadius: 0,
borderTopRightRadius: 0,
flex: `1 1 100%`,
borderTop: `1px solid ${presets.veryLightPurple}`,
}}
/>
<div css={{ flex: `1 1 100%` }}>
<Container hasSideBar={false}>
<div
css={{
textAlign: `center`,
padding: `${rhythm(1)} 0 ${rhythm(2)}`,
}}
>
<h1 css={{ marginTop: 0 }}>Curious yet?</h1>
<FuturaParagraph>
It only takes a few minutes to get up and running!
</FuturaParagraph>
<CtaButton to="/docs/" overrideCSS={{ marginTop: `1rem` }}>
Get Started
</CtaButton>
</div>
</Container>
</div>
<div
css={{
borderTop: `1px solid ${presets.veryLightPurple}`,
flex: `1 1 100%`,
[presets.Tablet]: {
paddingTop: rhythm(1),
},
}}
>
<Container hasSideBar={false} css={{ maxWidth: rhythm(30) }}>
{` `}
<h2
css={{
textAlign: `left`,
marginTop: 0,
color: presets.brand,
[presets.Tablet]: {
paddingBottom: rhythm(1),
},
}}
>
Latest from the Gatsby blog
</h2>
{blogPosts.edges.map(({ node }) =>
<BlogPostPreviewItem post={node} key={node.fields.slug} />
)}
</Container>
</div>
</Cards>
</div>
</div>
)
},
})
export default IndexRoute
export const pageQuery = graphql`
query Index {
site {
siteMetadata {
title
}
}
file(relativePath: { eq: "gatsby-explanation.png" }) {
childImageSharp {
responsiveSizes(maxWidth: 870) {
src
srcSet
sizes
}
}
}
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
limit: 3
filter: {
frontmatter: { draft: { ne: true } }
fileAbsolutePath: { regex: "/blog/" }
}
) {
edges {
node {
...BlogPostPreview_item
}
}
}
}
`
|
const five ={
"results":
{
"id":5,
"user_id":"",
"date":"2019-03-14",
"heading":"At Virugambakkam market, brace yourself for an olfactory attack",
"detail":"Delayed clearance of garbage from the Virugambakkam market on Kaliamman Koil Street leaves the space with more than just accumulated waste. There is a nauseating addition to it — an overhanging smell of putrifying vegetables, fruits and vegetables.",
"address":"The market comes under the jurisdiction of Zone – 11 (Valasaravakkam) of Greater Chennai Corporation.",
"posterpath":"https://i.ibb.co/YXYy2tf/5.jpg",
"category":"Garbage Dumping",
"location":"Chennai",
"status":"Closed",
"comment":"",
}
}
export default five;
|
import axios from 'axios';
import logger from '../logger';
import constants from '../constants';
const BASE_URL = process.env.BASE_URL;
const url = `${BASE_URL}${constants.url.INVOICE}`;
const parseInvoice = invoice => {
// logger.info(JSON.stringify(invoice));
return {
header: [
{
label: 'Chrome_Entity',
id: 'entityName',
name: 'entityName',
maxlength: '50',
placeholder: 'Entity',
type: 'text',
value: invoice.entityName,
readOnly: true
},
{
label: 'PO Type',
id: 'poFrom',
name: 'poFrom',
maxlength: '50',
placeholder: 'PO',
type: 'text',
value: 'PO',
readOnly: true
},
{
label: 'Invoice #',
id: 'invoiceNo',
name: 'invoiceNo',
maxlength: '50',
placeholder: 'Invoice #',
type: 'text',
value: invoice.invoice ? invoice.invoice.invoiceNo : 0,
readOnly: true
},
{
label: 'Invoice Date',
id: 'invoiceDate',
name: 'invoiceDate',
maxlength: '50',
placeholder: 'Invoice Date',
type: 'text',
value: invoice.invoiceDate,
readOnly: true
},
{
label: 'Workflow',
id: 'workflowName',
name: 'workflowName',
maxlength: '50',
placeholder: 'Workflow',
type: 'text',
value: invoice.workflowName,
readOnly: true
},
{
label: 'Supplier',
id: 'supplierName',
name: 'supplierName',
maxlength: '50',
placeholder: 'Supplier',
type: 'text',
value: invoice.supplierName,
readOnly: true
},
{
label: 'PO',
id: 'poNo',
name: 'poNo',
maxlength: '50',
placeholder: 'PO',
type: 'text',
value: invoice.invoice ? invoice.invoice.invoiceLineItems[0].poNo : 0,
readOnly: true
},
{
label: 'Payment Terms(Days)',
id: 'paymentDays',
name: 'paymentDays',
maxlength: '50',
placeholder: 'Payment Terms(Days)',
type: 'text',
value: invoice.paymentDays,
readOnly: true
},
{
label: 'Credit Notes',
id: 'creditNotes',
name: 'creditNotes',
type: 'select',
value: invoice.creditNotes,
readOnly: true,
options: []
}
],
invoiceLineItems: !invoice.invoice ? [] : invoice.invoice.invoiceLineItems.map((x, y) => {
return {
header: x.itemDesc,
lineItemId: x.invoiceLineItemId,
receivedId: x.receivedId,
itemId: x.itemId,
desc: x.itemDesc,
uom: x.uom,
qty: x.qty,
price: x.price,
netPrice: x.netPrice,
discount: x.discount,
sgst: x.sgst,
cgst: x.cgst,
igst: x.igst,
tax: x.taxAmt,
totalAmount: x.totalAmt,
otherTax: x.otherTax,
taxName: x.taxName,
poNo: x.poNo,
itemNo: x.itemNo,
supplierPartNo: x.supplierPartNo,
supplierName: x.supplierName,
qtyOrdered: x.qtyOrdered,
taxAmt: x.taxAmt,
totalAmt: x.totalAmt,
sNo: (y + 1).toString(),
};
}),
paymentTerms: invoice.invoice ? invoice.invoice.poRequesition.paymentTerms : '',
comments: invoice.comments,
invoiceId: invoice.invoice ? invoice.invoice.invoiceId : 0,
workflowAuditId: invoice.workflowAuditId,
taskId: invoice.taskId,
seqFlow: invoice.seqFlow,
auditTrackId: invoice.auditTrackId,
processInstanceId: invoice.processInstanceId,
invoiceNo: invoice.invoice ? invoice.invoice.invoiceNo : 0,
invoiceDate: invoice.invoiceDate,
workflowId: invoice.workflowId,
supplierId: invoice.supplierId,
requisitionId: invoice.invoice ? invoice.invoice.poRequesition.requisitionId : 0,
companyId: invoice.companyId,
subTotalAmt: invoice.invoice ? invoice.invoice.subTotalAmt : 0,
additionalAmt: invoice.invoice ? invoice.invoice.additionalAmt : 0,
adjustedAmt: invoice.invoice ? invoice.invoice.adjustedAmt : 0,
discount: invoice.invoice ? invoice.invoice.discount : 0,
grandTotal: invoice.invoice ? invoice.invoice.grandTotal : 0,
entityId: invoice.entityId,
entityName: invoice.entityName,
requesterId: invoice.requesterId,
poFrom: invoice.poFrom,
paymentDays: invoice.paymentDays,
creditNotes: invoice.creditNotes,
};
};
const getInvoice = async (req, res, next) => {
logger.info(`${req.originalUrl} - ${req.method} - ${req.ip}`);
try {
const {cookie, loadBalancer, payload} = req.body;
const config = {
headers: {
name: 'content-type',
value: 'application/x-www-form-urlencoded',
Cookie: cookie
}
};
const response = await axios.post(url, payload, config);
if (!response.data) {
let err = new Error(constants.INVALID_USER);
err.status = 401;
next(err);
} else {
const invoice = await parseInvoice(response.data);
res.status(200).json(invoice);
}
} catch (err) {
if (err.toString() === constants.STATUS_401) {
err.status = 401;
}
next(err);
}
};
const updateInvoice = async (req, res, next) => {
logger.info(`${req.originalUrl} - ${req.method} - ${req.ip}`);
try {
const {cookie, loadBalancer, payload} = req.body;
const config = {
headers: {
name: 'content-type',
value: 'application/x-www-form-urlencoded',
Cookie: cookie,
}
};
const response = await axios.post(url, payload, config);
if (!response.data) {
let err = new Error(constants.INVALID_USER);
err.status = 401;
next(err);
} else {
res.status(200).json(response.data);
}
} catch (err) {
logger.info(err.toString());
if (err.toString() === constants.STATUS_401) {
err.status = 401;
}
next(err);
}
};
export {getInvoice, updateInvoice};
|
// GENERATED CODE -- DO NOT EDIT!
'use strict';
var grpc = require('@grpc/grpc-js');
var tms_pb = require('./tms_pb.js');
function serialize_tmsservice_ExecuteRequest(arg) {
if (!(arg instanceof tms_pb.ExecuteRequest)) {
throw new Error('Expected argument of type tmsservice.ExecuteRequest');
}
return Buffer.from(arg.serializeBinary());
}
function deserialize_tmsservice_ExecuteRequest(buffer_arg) {
return tms_pb.ExecuteRequest.deserializeBinary(new Uint8Array(buffer_arg));
}
function serialize_tmsservice_ExecuteResponse(arg) {
if (!(arg instanceof tms_pb.ExecuteResponse)) {
throw new Error('Expected argument of type tmsservice.ExecuteResponse');
}
return Buffer.from(arg.serializeBinary());
}
function deserialize_tmsservice_ExecuteResponse(buffer_arg) {
return tms_pb.ExecuteResponse.deserializeBinary(new Uint8Array(buffer_arg));
}
var TMSService = exports.TMSService = {
// Monitor transaction
//
// Mojaloop Transation
execute: {
path: '/tmsservice.TMS/Execute',
requestStream: false,
responseStream: false,
requestType: tms_pb.ExecuteRequest,
responseType: tms_pb.ExecuteResponse,
requestSerialize: serialize_tmsservice_ExecuteRequest,
requestDeserialize: deserialize_tmsservice_ExecuteRequest,
responseSerialize: serialize_tmsservice_ExecuteResponse,
responseDeserialize: deserialize_tmsservice_ExecuteResponse,
},
};
exports.TMSClient = grpc.makeGenericClientConstructor(TMSService);
|
/* @flow */
import React from 'react'
import MainLayout from './../components/main-layout.jsx'
import ContentBox from './../components/content-box.jsx'
import Text from './../components/text.jsx'
import Button from './../components/button.jsx'
import Spacing from './../components/spacing.jsx'
type verifyEmailType = {
title: string,
url: string
}
const VerifyEmail = ({ title, url }: verifyEmailType): React.Element => (
<MainLayout title={title}>
<ContentBox text>
<Text>
Hi there,
</Text>
<Spacing />
<Text>
please confirm your email address to activate your account and start creating your portfolio.
</Text>
<Spacing />
<Button href={url}>
Confirm account
</Button>
<Spacing />
<Text>
Thanks, we’re looking forward to seeing your work!
</Text>
</ContentBox>
</MainLayout>
)
export default VerifyEmail
|
export let contactBp;
(function () {
let delModalSpan = {
tag: 'span',
classes: ['openModal', 'openDelModal'],
props: {
blueprint: 'delModalSpan',
innerText: '\xD7'
},
attr: {
"data-modal": "delContactModal"
},
states: {},
};
let delModalOpen = {
tag: 'button',
classes: ['close', 'openModal', 'openDelModal'],
props: {
blueprint: 'delModalOpen',
},
attr: {
"data-modal": "delContactModal",
},
states: {},
children: [
delModalSpan
],
content: ["value"],
};
let contactName = {
tag: "h5",
classes: ["card-title"],
props: {
blueprint: "contactName",
},
states: {},
content: ["innerText"],
};
let contactEmail = {
tag: "h6",
classes: ["card-subtitle", "mb-2", "text-muted"],
props: {
blueprint: "contactEmail",
},
states: {},
content: ["innerText"],
};
let contactPhone = {
tag: "p",
classes: ["card-text"],
props: {
blueprint: "contactPhone",
},
states: {},
content: ["innerText"],
};
let contactBtn = {
tag: "button",
classes: ["btn", "btn-primary", "openModal"],
props: {
blueprint: "contactBtn",
innerText: "Manage Contact",
},
attr: {
"data-modal": "manageContactModal",
},
states: {},
content: ["value"],
};
let contactTags = {
tag: "div",
classes: ["tags", "mt-2"],
props: {
blueprint: "contactTags",
},
states: {},
};
let contactBody = {
tag: "div",
classes: ["card-body"],
props: {
blueprint: "contactBody",
},
states: {},
children: [
delModalOpen,
contactName,
contactEmail,
contactPhone,
contactBtn,
contactTags,
],
};
contactBp = {
tag: "div",
classes: ["card"],
props: {
blueprint: "contact",
style: "width: 18rem;",
},
states: {},
children: [
contactBody,
],
}
})();
|
var refer = {};
refer.add = function(args){
var endpoint = "services/reference.php";
var method = "POST";
utility.data(endpoint,method,args,function(data){
var response = JSON.parse(data);
console.debug(response);
alert(response.result);
control.pagetab('reference-manager.html');
});
}
refer.edit = function(args){
var endpoint = "services/reference.php";
var method = "POST";
utility.data(endpoint,method,args,function(data){
var response = JSON.parse(data);
console.debug(response);
alert(response.result);
control.pagetab('reference-manager.html');
});
}
refer.delete = function(){
console.log('call delete');
var endpoint = "services/reference.php";
var method = "POST";
var args = "";
$('input[name="mark[]"]:checked').each(function(){
var id = $(this).attr('data-id');
args = {'_':new Date().getMilliseconds(),'type':'del' , 'id':id};
utility.service(endpoint,method,args);
$('#row'+id).remove();
console.log('id='+id);
});
alert('DELETE SUCCESS.');
//refer.loadlist();
}
refer.loadlist = function(){
//$('#data_list').html('');
console.log('call list reference.');
var endpoint = "services/reference.php";
var method = "GET";
//var args = {'_':new Date().getMilliseconds(),'type':'list'};
var args = {'_':new Date().getMinutes(),'type':'list','couter':$('#counter').val(),'fetch':'20'};
utility.service(endpoint,method,args,view_list_reference);
}
refer.loaditem = function(id){
$('#id').val(id);
var endpoint = "services/reference.php";
var method = "GET";
var args = {'_':new Date().getMilliseconds(),'type':'item','id':id};
utility.service(endpoint,method,args,view_item);
}
function view_item(data){
if(data.result==undefined || data.result=="") {
console.log("reference-manager > item reference :: data not found.");
return;
}
$('#title_th').val(data.result.title_th);
$('#title_en').val(data.result.title_en);
$('#detail_th').summernote('code',data.result.detail_th);
$('#detail_en').summernote('code',data.result.detail_en);
$('#contury_th').val(data.result.contury_th);
$('#contury_en').val(data.result.contury_en);
$('#thumbnail').attr('src',data.result.thumbnail);
$('input[name="islocal"][value="'+data.result.islocal+'"]').prop('checked',true);
if(data.result.active=="1")
$('#active').prop('checked',true);
}
function view_list_reference(data){
var view = $('#data_list');
var item = "";
if(data.result==undefined || data.result=="") {
console.log("reference-manager > list reference :: data not found.")
return;
}
var max_item = $('#counter').val();
$.each(data.result,function(i,val){
var param = '?id='+val.id;
var active = val.active == "1" ? "<span class='btn btn-success btn-sm'>Enable</span> ": "<span class='btn btn-danger btn-sm'>Disable</span>";
item+="<tr id='row"+val.id+"' >";
item+="<td><input type='checkbox' name='mark[]' data-id='"+val.id+"' /></td>";
item+="<td>"+val.id+"</td>";
item+="<td>"+val.title_th+"</td>";
item+="<td>"+val.title_en+"</td>";
item+="<td>"+active+"</td>";
item+="<td><span class='btn btn-warning btn-sm' onclick=control.pagetab('reference-edit.html','"+param+"') >แก้ไข</span></td>";
item+="</tr>";
max_item++;
});
$('#counter').val(max_item);
view.append(item);
}
|
const express = require('express')
const app = express()
const routes = require('./routes')
const cors = require('cors')
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
const passport = require('./passport')
const port = process.env.PORT || 3001 //3001 is backend while 3000 is frontend in React
// middleware - JSON parsing
app.use(express.json());
// middleware - cors
const corsOptions = {
origin: ['http://localhost:3000'], // task-bite.heroku.com
credentials: true,
optionsSuccessStatus: 204
}
app.use(cors(corsOptions))
// middleware - sessions config
app.use(session({
store: new MongoStore({ url: process.env.MONGODB_URI || "mongodb://localhost:27017/task-bite" }),
// this could go in an env -> process.env.secret
secret: "AnotherAllNighter",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24
}
}))
// middleware - passport config
app.use(passport.initialize())
app.use(passport.session())
// middleware - API routes
app.use('/api/silo/projects', routes.projects);
app.use('/api/silo/tasks', routes.tasks);
app.use('/api/silo/users', routes.users);
app.use('/api/silo/auth', routes.auth);
// connection
app.listen(port, () => console.log(`Server is running on port ${port}`));
|
function ProspectSubmit(){
$('#kform').submit(false);
var errors = [];
$('.required').each(function() {
var $this = $(this);
if(!$this.val()) {
if(errors.length == 0) { errors.push("<b>Please fix the following errors..</b><br /><br />"); }
$this.addClass('has-error');
errors.push($this.attr("data-error-message"));
}else{
$this.removeClass('has-error');
if($this.attr("data-validate") == 'email') {
if(!validate_email($this.val())) {
if(errors.length == 0) { errors.push("<b>Please fix the following errors..</b><br /><br />"); }
errors.push("Email address is not valid");
$this.addClass('has-error');
}
}
if($this.attr("data-validate") == 'phone') {
if(!validate_phone($this.val())) {
if(errors.length == 0) { errors.push("<b>Please fix the following errors..</b><br /><br />"); }
errors.push("Phone number is not valid");
$this.addClass('has-error');
}
}
}
});
if(errors.length) {
error_handler(errors);
return false;
}else{
$('#loading-indicator').show();
//alert(1);
document.getElementById("kform").submit();
return true;
}
e.preventDefault();
}
function SubmitUpsellForm(){
$('#upsell_form').submit(false);
var errors = [];
$('.required').each(function() {
var $this = $(this);
if(!$this.val()) {
if(errors.length == 0) { errors.push("<b>Please fix the following errors..</b><br /><br />"); }
$this.addClass('has-error');
errors.push($this.attr("data-error-message"));
}else{
$this.removeClass('has-error');
if($this.attr("data-validate") == 'email') {
if(!validate_email($this.val())) {
if(errors.length == 0) { errors.push("<b>Please fix the following errors..</b><br /><br />"); }
errors.push("Email address is not valid");
$this.addClass('has-error');
}
}
if($this.attr("data-validate") == 'phone') {
if(!validate_phone($this.val())) {
if(errors.length == 0) { errors.push("<b>Please fix the following errors..</b><br /><br />"); }
errors.push("Phone number is not valid");
$this.addClass('has-error');
}
}
}
});
if(errors.length) {
error_handler(errors);
return false;
}else{
$('#loading-indicator').show();
jQuery.ajax({
type:'POST',
url: 'lib/new_order_trial.php',
data:jQuery('#upsell_form').serialize(),
success: function(response) {
var res = response.split("|");
if( res[0]=='success' ) {
window.onbeforeunload = null;
window.location.href = 'thankyou.php'+res[1]+'&upsell=yes';
}
else {
jQuery('#loading-indicator').hide();
errors.push(res[1]);
error_handler(errors);
}
}});
return false;
}
e.preventDefault();
}
function SubmitCheckoutForm(){
$('#kform_checkout').submit(false);
var errors = [];
$('.required').each(function() {
var $this = $(this);
if(!$this.val()) {
if(errors.length == 0) { errors.push("<b>Please fix the following errors..</b><br /><br />"); }
$this.addClass('has-error');
errors.push($this.attr("data-error-message"));
}else{
$this.removeClass('has-error');
if($this.attr("data-validate") == 'email') {
if(!validate_email($this.val())) {
if(errors.length == 0) { errors.push("<b>Please fix the following errors..</b><br /><br />"); }
errors.push("Email address is not valid");
$this.addClass('has-error');
}
}
if($this.attr("data-validate") == 'phone') {
if(!validate_phone($this.val())) {
if(errors.length == 0) { errors.push("<b>Please fix the following errors..</b><br /><br />"); }
errors.push("Phone number is not valid");
$this.addClass('has-error');
}
}
}
});
if(errors.length) {
error_handler(errors);
return false;
}else{
$('#loading-indicator').show();
jQuery.ajax({
type:'POST',
url: 'lib/new_order_trial.php',
data:jQuery('#kform_checkout').serialize(),
success: function(response) {
var res = response.split("|");
if( res[0]=='success' ) {
window.onbeforeunload = null;
window.location.href = 'upsell1.php'+res[1];
}
else {
jQuery('#loading-indicator').hide();
errors.push(res[1]);
error_handler(errors);
}
}});
return false;
}
e.preventDefault();
}
$(function() {
$("input:checkbox[name=billShipSame]").click(function(){
if($(this).val()=='0'){
$('#kform_hiddenAddress').css('display','none');
$('#billingSameAsShipping').val('yes');
$("#kform_hiddenAddress :input").removeClass("required");
$(this).val(1)
}
else{
$('#kform_hiddenAddress').css('display','block');
$("#kform_hiddenAddress :input").addClass("required");
$("#billing_street_address2").removeClass("required");
$('#billingSameAsShipping').val('no');
$(this).val(0)
}
});
if($('.required').length) {
$('.required').bind('blur', function() {
var $this = $(this);
if(!$this.val()) {
$this.addClass('has-error');
}else{
$this.removeClass('has-error');
}
});
}
$(window).keydown(function(e) {
if (e.which === 27 && $('#error_handler_overlay').length) {
$('#error_handler_overlay').remove();
}
});
$(window).keydown(function(e) {
if (e.which === 27 && $('#app_common_modal').length) {
$('#app_common_modal').remove();
}
});
$(document).off('click', '#error_handler_overlay');
$(document).on('click', '#error_handler_overlay', function() {
$(this).remove();
});
$(document).off('click', '#error_handler_overlay_close');
$(document).on('click', '#error_handler_overlay_close', function() {
$('#error_handler_overlay').remove();
});
$(document).off('click', '#app_common_modal_close');
$(document).on('click', '#app_common_modal_close', function () {
$('#app_common_modal').remove();
});
});
function validate_email(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate_phone(phone) {
var re = /^\d{10}$/;
return re.test(phone);
}
function error_handler(errors) {
if ($('#error_handler_overlay').length) {
$('#error_handler_overlay').remove();
}
$('body').append(get_ui(errors));
$('#error_handler_overlay').fadeIn(500);
}
function get_ui(errors) {
var li = '';
$.each(errors, function(key, value) {
li += '<li>' + value + '</li>';
});
var html = '';
html += '<div id="error_handler_overlay">';
html += '<div class="error_handler_body"><a href="javascript:void(0);" id="error_handler_overlay_close">X</a><ul>' + li + '</ul></div>';
html += '</div>';
return html;
}
function openNewWindow(page_url, type, window_name, width, height, top, left, features) {
if(!type) { type = 'popup'; }
if(!width) { width = 480; }
if(!height) { height = 480; }
if(!top) { top = 50; }
if(!left) { left = 50; }
if(!features) { features = 'resizable,scrollbars'; }
if(type == 'popup') {
var settings = 'height=' + height + ',';
settings += 'width=' + width + ',';
settings += 'top=' + top + ',';
settings += 'left=' + left + ',';
settings += features;
win = window.open(page_url, window_name, settings);
win.window.focus();
} else if (type == 'modal') {
var html = '';
html += '<div id="app_common_modal">';
html += '<div class="app_modal_body"><a href="javascript:void(0);" id="app_common_modal_close">X</a><iframe src="' + page_url + '" frameborder="0"></iframe></div>';
html += '</div>';
if (!$('#app_common_modal').length) {
$('body').append(html);
}
$('#app_common_modal').fadeIn();
}
}
function onlyNumbers(e,type) {
var keynum;
var keychar;
var numcheck;
if(window.event) {
keynum = e.keyCode;
} else if(e.which) {
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
numcheck = /\d/;
switch (keynum)
{
case 8: //backspace
case 9: //tab
case 35: //end
case 36: //home
case 37: //left arrow
case 38: //right arrow
case 39: //insert
case 45: //delete
case 46: //0
case 48: //1
case 49: //2
case 50: //3
case 51: //4
case 52: //5
case 54: //6
case 55: //7
case 56: //8
case 57: //9
case 96: //0
case 97: //1
case 98: //2
case 99: //3
case 100: //4
case 101: //5
case 102: //6
case 103: //7
case 104: //8
case 105: //9
result2 = true;
break;
case 109: // dash -
if (type == 'phone')
{
result2 = true;
}
else
{
result2 = false;
}
break;
default:
result2 = numcheck.test(keychar);
break;
}
return result2;
}
width = screen.width;
height=screen.height;
document.cookie="screen_resolution="+width+"X"+height;
|
import React from 'react'
import { navigate } from '@reach/router'
import { Button, Input } from '../../../components/reusable'
import { useAuth, useStories } from '../../../custom-hooks'
const CreateStory = () => {
const [user] = useAuth()
const [_, saveNewStory] = useStories(user)
const [name, setName] = React.useState()
const saveStory = async () => {
const id = await saveNewStory({ name })
navigate(`/story/${id}`)
}
return (
<>
<h3>Story Name</h3>
<Input placeholder="Enter your story name" onChange={setName} />
<Button onClick={saveStory} >Submit</Button>
</>
)
}
export default CreateStory
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "5629c60a63f5d65969b6a87cb96b14a1",
"url": "/index.html"
},
{
"revision": "254d5fb7b063f0f0a2c1",
"url": "/static/css/main.7bc619c9.chunk.css"
},
{
"revision": "14b3209e527a5cb7f2e2",
"url": "/static/js/2.d9456afe.chunk.js"
},
{
"revision": "254d5fb7b063f0f0a2c1",
"url": "/static/js/main.ce36b609.chunk.js"
},
{
"revision": "42ac5946195a7306e2a5",
"url": "/static/js/runtime~main.a8a9905a.js"
},
{
"revision": "3045c4d7454b74ad3f9113d4159d1e9a",
"url": "/static/media/art1.3045c4d7.JPG"
},
{
"revision": "31e2c721c289c59f05515ecba272b52d",
"url": "/static/media/art2.31e2c721.JPG"
},
{
"revision": "4453b1282b93d57b8f9edceb71a5df1b",
"url": "/static/media/crizell_portfolio.4453b128.pdf"
},
{
"revision": "af6b8e7801632bc144dd2f63b4c0f0e4",
"url": "/static/media/crizell_resume.af6b8e78.pdf"
},
{
"revision": "03e747680ef78352fdfedfb90caac148",
"url": "/static/media/kitel.03e74768.jpg"
}
]);
|
import React from 'react'
import classes from './SocialButton.module.scss';
const SocialButton = (props) => {
return (
<a href={props.url} className={classes.SocialButton} target="__blank">
{props.children}
</a>
)
}
export default SocialButton
|
(function() {
app.controllers = app.controllers || {};
app.controllers.stopExecution = function(msg) {
$('#progressModal').modal('hide');
$('#progressModal').on('hidden.bs.modal', function() {
app.views.progressModal.init();
});
app.views.alerts.show(msg.type, msg.text);
app.views.results.clear();
app.views.placeModal.hide();
app.views.page.enableButtons();
return;
};
/******************************************************************************************
getDetails() - Controls the flow for acquiring details when a specific place is selected
*******************************************************************************************/
app.controllers.getDetails = function(place) {
app.models.selectedPlace.init();
var requestedPlace = app.models.places.find(place);
app.models.selectedPlace.setBasicDetails(requestedPlace);
app.models.selectedPlace.setDrivingInfo(requestedPlace.drivingInfo.distance, requestedPlace.drivingInfo.duration);
app.modules.reqPlaceDetails(requestedPlace.place_id)
.then(function(results) {
app.models.selectedPlace.setSpecificDetails(results);
var origin = { lat: app.models.searchLoc.lat, lng: app.models.searchLoc.lng };
var destination = { lat: app.models.selectedPlace.lat, lng: app.models.selectedPlace.lng };
return app.modules.reqTransitDistance(origin, destination);
})
.then(function(results) {
var distance, duration;
// Guard against no transit option to destination
if (results.rows[0].elements[0].distance && results.rows[0].elements[0].duration) {
distance = results.rows[0].elements[0].distance.text;
duration = results.rows[0].elements[0].duration.text;
}
// Save distance and duration info
app.models.selectedPlace.setTransitInfo(distance, duration);
app.views.placeModal.populate(app.models.selectedPlace);
app.views.placeModal.show();
})
.catch(app.controllers.stopExecution);
};
/*****************************************************************************************************
switchToGeolocation() - Requests distance from your location to a place (triggered from placeModal)
******************************************************************************************************/
app.controllers.switchToGeolocation = function() {
app.models.searchLoc.isGeoSearch = true;
app.modules.getCurrentLocation()
.then(function(position) {
app.models.searchLoc.lat = position.coords.latitude;
app.models.searchLoc.lng = position.coords.longitude;
var origin = {
lat: app.models.searchLoc.lat,
lng: app.models.searchLoc.lng
},
destination = {
lat: app.models.selectedPlace.lat,
lng: app.models.selectedPlace.lng
};
return app.modules.reqDrivingDistance(origin, destination);
})
.then(function(results) {
var distance, duration;
// Guard against no transit option to destination
if (results.rows[0].elements[0].distance && results.rows[0].elements[0].duration) {
distance = results.rows[0].elements[0].distance.text;
duration = results.rows[0].elements[0].duration.text;
}
// Save distance and duration info
app.models.selectedPlace.setDrivingInfo(distance, duration);
var origin = {
lat: app.models.searchLoc.lat,
lng: app.models.searchLoc.lng
},
destination = {
lat: app.models.selectedPlace.lat,
lng: app.models.selectedPlace.lng
};
return app.modules.reqTransitDistance(origin, destination);
})
.then(function(results) {
var distance, duration;
// Guard against no transit option to destination
if (results.rows[0].elements[0].distance && results.rows[0].elements[0].duration) {
distance = results.rows[0].elements[0].distance.text;
duration = results.rows[0].elements[0].duration.text;
}
// Save distance and duration info
app.models.selectedPlace.setTransitInfo(distance, duration);
app.views.placeModal.populate(app.models.selectedPlace);
app.views.placeModal.show();
var places = app.models.places.get();
// Flatten to a one-dimensional array
if (places.primary || places.secondary) {
places = places.primary.concat(places.secondary);
}
// Push lat, lng for places onto new destinations array ( [{lat, lng}, {lat, lng}] )
var placesCoords = [];
places.forEach(function(place) {
placesCoords.push({ lat: place.geometry.location.lat, lng: place.geometry.location.lng });
});
return app.modules.reqMultiDistance(app.models.searchLoc.lat, app.models.searchLoc.lng, placesCoords);
})
.then(function(results) {
var places = app.models.places.get();
// Flatten to a one-dimensional array
if (places.primary || places.secondary) {
places = places.primary.concat(places.secondary);
}
results.rows[0].elements.forEach(function(element, i) {
if (element.distance) {
places[i].drivingInfo = {
value: element.distance.value,
distance: element.distance.text,
duration: element.duration.text
};
}
});
var sortedPlaces = app.modules.sortPlaces(places);
app.models.places.add(sortedPlaces);
app.models.searchLoc.totalItems = sortedPlaces.primary.length + sortedPlaces.secondary.length;
app.views.alerts.show('success', app.models.searchLoc.totalItems + ' matches! Click on an item for more details.');
app.views.results.render(sortedPlaces);
app.views.placeModal.init();
})
.catch(app.controllers.stopExecution);
};
})();
|
import React, { Component } from 'react';
import { withStyles, makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Avatar from '@material-ui/core/Avatar';
import MuiAccordion from '@material-ui/core/Accordion';
import MuiAccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import ReplyPost from './ReplyPost.jsx'
import Reply from './Reply.jsx'
import avatar from '../../assets/avatar.svg';
const styles = theme => ({
root: {
display: 'flex',
width: "95%",
margin: '1em 0 0 1em',
},
avatar: {
borderRadius: '50%',
},
comment: {
display: 'flex',
flexDirection: 'column',
},
heading: {
fontSize: theme.typography.pxToRem(15),
fontWeight: theme.typography.fontWeightRegular,
},
accDetails: {
padding: "0.5em",
},
});
const Accordion = withStyles({
root: {
boxShadow: 'none',
'&:not(:last-child)': {
borderBottom: 0,
},
'&:before': {
height: '2em',
minHeight: '1em',
display: 'none',
},
'&$expanded': {
margin: '0',
},
},
expanded: {
margin: 0,
}
})(MuiAccordion);
const AccordionSummary = withStyles({
root: {
backgroundColor: 'rgba(0, 0, 0, 0)',
marginBottom: -1,
minHeight: 0,
'&$expanded': {
minHeight: 0,
margin: '0',
},
},
content: {
marginTop: '0.4em',
marginBottom: 0,
minHeight: 0,
'&$expanded': {
margin: '0.4em 0px',
},
},
expanded: {},
})(MuiAccordionSummary);
class Comment extends Component{
constructor(props){
super(props);
this.state = {
replies: [
{
"username": "Oscar",
"content": "123",
"key": "0",
},
{
"username": "Morris",
"content": "456",
"key": "1",
}
],
isExpand: false,
};
}
renderReply() {
const { classes } = this.props;
if (this.state.replies.length === 0) {
return <div>No Replies</div>
} else {
return this.state.replies.map((reply) => {
return (
<AccordionDetails className={classes.accDetails}>
<Reply
content={reply.content}
username={reply.username}
key={reply.key}
/>
</AccordionDetails>
)
})
}
}
onCreateReply = (content) => {
if(content.length !== 0){
let key = this.state.replies.length.toString();
this.setState({ replies: this.state.replies.concat([{"username": 'Shren', "content": content, "key": key}])});
this.setState({isExpand: true})
}
}
onSetExpand = () =>{
if(this.state.isExpand === false){
this.setState({isExpand: true})
}
else if(this.state.isExpand === true){
this.setState({isExpand: false})
}
}
render() {
const { classes } = this.props;
return(
<div className={classes.root}>
<div style={{marginRight: '1em'}}>
<Avatar className={classes.avatar} src={avatar} />
</div>
<div style={{width: '90%'}}>
<div className={classes.comment}>
<div style={{display: 'flex', alignItems: 'center'}}>
<Typography variant='h5'>{this.props.username}</Typography>
<Typography variant='h6' style={{margin: '0 0.4em'}}>•</Typography>
<Typography variant='h6'>{'5 min ago'}</Typography>
</div>
<Typography variant='body1'>{this.props.context}</Typography>
</div>
<Accordion elevation={0} expanded={this.state.isExpand}>
<AccordionSummary onClick={event => this.onSetExpand()}>
<Typography variant='h5'>Reply</Typography>
</AccordionSummary>
{this.renderReply()}
<ReplyPost createReply={this.onCreateReply}/>
</Accordion>
</div>
</div>
)
}
}
export default withStyles(styles)(Comment);
|
angular.module('read-more-directive', [])
.directive('readMore', function ($compile) {
return {
restrict:'AE',
scope:{
hmtext : '@',
hmlimit : '@',
hmfulltext:'@',
hmMoreText:'@',
hmLessText:'@',
hmMoreClass:'@',
hmLessClass:'@'
},
templateUrl: 'components/directives/COMMON/readMore/template.html',
transclude: true,
controller : function($scope){
$scope.toggleValue=function(){
$scope.hmfulltext = !$scope.hmfulltext;
}
}
};
});
|
class Wallet {
constructor(money) {
let _money = money;
//pobieranie aktuwalnej zawartości portfela
this.getWalletValue = () => _money;
//Sprawdzanie czy użytkownik ma odpowiednią ilośc środków
this.checkCanPlay = (value) => {
if (_money >= value) return true;
return false
}
this.changeWallet = (value, type = "+") => {
if (typeof value === "number" && !isNaN(value)) { // sprawdzenie czy value type jest liczba i czy nie jest not a number (negacja z true isNAN)
if (type === "+") {
return _money += value;
} else if (type === "-") {
return _money -= value;
} else {
throw new Error("nieprawidłowy typ działania")
}
} else {
console.log(typeof value);
throw new Error("nieprawidłowa liczba")
}
}
}
}
// const wallet = new Wallet(200) //obiekt zostanie stworzony w pliku Game.js który będzie spajał klasy ze wszystkich modułów/plików
|
import React, { useState } from "react";
import { connect } from "react-redux";
import { getBoards, createBoard } from "./../../redux/actions/boardsActions";
import { Link } from "react-router-dom";
import { v4 as uuid } from "uuid";
import "./Home.scss";
const ConnectedHome = props => {
const [boardName, setBoardName] = useState("");
const [emptyError, setEmptyError] = useState(false);
const handleBoardNameChange = e => {
if (emptyError) {
setEmptyError(false);
}
const value = e.target.value;
setBoardName(value);
};
const createNewBoard = e => {
if (!boardName) {
setEmptyError(true);
return;
}
props.createBoard({
id: uuid(),
name: boardName
});
setBoardName("");
};
const handleOnKeyDown = e => {
if (e.key === "Enter") {
createNewBoard(e);
}
};
return (
<div className="container home-container">
<h3 className="main-heading">All Boards ({props.boards.length})</h3>
{/* <p>
{props.boards.length} Board{props.boards.length > 1 ? "s" : null}
</p> */}
<div className="add-new-board">
<div className="board-input-wrapper">
<input
className="board-name"
type="text"
value={boardName}
placeholder="Add new board"
onChange={handleBoardNameChange}
onKeyDown={handleOnKeyDown}
/>
{emptyError && <p className="error">Enter board name</p>}
</div>
<button
className="create-board-btn"
type="button"
onClick={createNewBoard}
>
Create
</button>
</div>
<div className="boards-wrapper">
{props.boards &&
props.boards.map(board => {
return (
<Link to={`board/${board.id}`} key={board.id}>
<div className="board-wrapper">
<h4 className="board-name">{board.name}</h4>
<p>
{board.data.length} list{board.data.length > 1 ? "s" : null}
</p>
</div>
</Link>
);
})}
{/* <div className="board-wrapper add-new-board">
<p className="icon">+</p>
<h4 className="board-name">Add New Board</h4>
</div> */}
</div>
</div>
);
};
const mapStateToProps = state => {
return {
boards: state.boards.boards
};
};
const mapDispatchToProps = dispatch => {
return {
getBoards: payload => {
dispatch(getBoards(payload));
},
createBoard: payload => {
dispatch(createBoard(payload));
}
};
};
const Home = connect(
mapStateToProps,
mapDispatchToProps
)(ConnectedHome);
export default Home;
|
// @flow
export { default as Game } from './Game.js';
export { default as Time } from './Time.js';
export { default as root } from './platform/root.js';
|
/**
* @file Select.js
* @author leeight
*/
import u from 'lodash';
import {DataTypes, defineComponent} from 'san';
import {hasUnit, create} from './util';
import {asInput} from './asInput';
import Layer from './Layer';
import ScrollIntoView from './ScrollIntoView';
import TextBox from './TextBox';
import StopScroll from './StopScroll';
const cx = create('ui-select');
const kDefaultLabel = '请选择';
function defaultFilter(datasource, keyword) {
if (!keyword) {
return datasource;
}
const rv = [];
u.each(datasource, item => {
if (item.text && item.text.toLowerCase().indexOf(keyword.toLowerCase()) !== -1) {
rv.push(item);
}
});
return rv;
}
/* eslint-disable */
const template = `<div on-click="toggleLayer($event)" class="{{mainClass}}" style="{{mainStyle}}">
<span class="${cx('text')}" s-if="multi">{{multiLabel|raw}}</span>
<span class="${cx('text')}" s-else>{{label|raw}}</span>
<ui-layer open="{=active=}" follow-scroll="{{false}}" s-ref="layer" offset-top="{{layerOffsetTop}}" offset-left="{{layerOffsetLeft}}">
<ui-ss class="${cx('layer')} ${cx('layer-x')}" style="{{layerStyle}}">
<ul s-if="multi">
<ui-textbox s-if="filter"
value="{=keyword=}"
placeholder="{{filterPlaceholder}}"
width="{{realLayerWidth - 50}}"
/>
<li class="${cx('item', 'item-all')}" s-if="filteredDatasource.length">
<label>
<input type="checkbox" on-change="onToggleAll" checked="{=checkedAll=}" />全选/全不选
</label>
</li>
<li class="${cx('x-group')}"
s-for="group in groupedDatasource">
<div s-if="group.title !== '-' "
class="${cx('group-title')}" title="{{group.title}}">{{group.title}}</div>
<ul class="${cx('group-list')}">
<li class="{{item | itemClass}}"
aria-label="{{item.tip}}"
s-for="item in group.datasource">
<label>
<input type="checkbox"
value="{{item.value}}"
class="${cx('selected-box')}"
disabled="{{item.disabled}}"
checked="{=value=}" /><span style="{{textStyle}}">{{item.text}}</span>
</label>
</li>
</ul>
</li>
</ul>
<ul s-else>
<ui-textbox s-if="filter"
value="{=keyword=}"
placeholder="{{filterPlaceholder}}"
width="{{realLayerWidth - 50}}"
/>
<li class="${cx('x-group')}"
s-for="group in groupedDatasource">
<div s-if="group.title !== '-' "
class="${cx('group-title')}" title="{{group.title}}">{{group.title}}</div>
<ul class="${cx('group-list')}">
<li on-click="selectItem($event, item)"
class="{{item | itemClass}}"
aria-label="{{item.tip}}"
s-for="item in group.datasource">
<ui-siv s-if="item.value === value"><span>{{item.text}}</span></ui-siv>
<span s-else>{{item.text}}</span>
</li>
</ul>
</li>
</ul>
</ui-ss>
</ui-layer>
</div>`;
/* eslint-enable */
const Select = defineComponent({ // eslint-disable-line
template,
components: {
'ui-textbox': TextBox,
'ui-layer': Layer,
'ui-ss': StopScroll,
'ui-siv': ScrollIntoView
},
initData() {
return {
active: false,
multi: false, // 是否支持多选,也就是之前的 MultiSelect 的功能
layerWidth: null, // 手工设置的
autoLayerWidth: null, // this.el.clientWidth 自动算出来的
layerOffsetTop: 2,
layerOffsetLeft: 0,
filter: false, // 是否支持搜索过滤
filterPlaceholder: '', // filter textbox placeholder
filterCallback: defaultFilter,
keyword: '', // 过滤的关键词
defaultLabel: kDefaultLabel,
value: '', // any | any[]
checkedAll: false
};
},
dataTypes: {
/**
* 获取或者设置 Select 组件的当前的值
*
* @bindx
* @default ''
*/
value: DataTypes.any,
/**
* 浮层的打开或者关闭状态
*
* @bindx
* @default false
*/
active: DataTypes.bool,
/**
* Select 的数据源,每一项的格式如下:
* <pre><code>{
* text: string,
* value: any,
* group?: string (如需要分组展示,设置这个字段)
* }</code></pre>
*/
datasource: DataTypes.array,
/**
* 未选中任何项时的文字
*
* @default '请选择'
*/
defaultLabel: DataTypes.string,
/**
* 是否支持选择多项,如果设置为 true,那么 value 的类型是 any[]
*
* @default false
*/
multi: DataTypes.bool,
/**
* 浮层的宽度,如果没有设置的话,默认跟 Select 的宽度保持一致(每次展示的时候会计算)
*/
layerWidth: DataTypes.number,
/**
* 调整 Layer 的偏移量
*
* @default 2
*/
layerOffsetTop: DataTypes.number,
/**
* 调整 Layer 的偏移量
*
* @default 0
*/
layerOffsetLeft: DataTypes.number,
/**
* 是否支持搜索的功能
*/
filter: DataTypes.bool,
/**
* 搜索框的 placeholder
*/
filterPlaceholder: DataTypes.string,
/**
* 自定义的过滤器<br>
* function(datasource: any[], keyword: string): any[]
*/
filterCallback: DataTypes.func
},
computed: {
multiLabel() {
// const datasource = this.data.get('datasource');
const values = this.data.get('value');
return values && values.length > 0 ? `您已经选择了${values.length}项` : this.data.get('defaultLabel');
/**
const labels = [];
u.each(datasource, item => {
if (u.indexOf(values, item.value) !== -1) {
labels.push(item.text);
}
});
return labels.length > 0 ? labels.join(',') : this.data.get('defaultLabel');
*/
},
label() {
const selectedItem = this.data.get('selectedItem');
return selectedItem ? selectedItem.text : this.data.get('defaultLabel');
},
filteredDatasource() {
// XXX(leeight) https://github.com/ecomfe/san/issues/97
const filter = this.data.get('filter');
const datasource = this.data.get('datasource');
if (!filter) {
return datasource;
}
const keyword = this.data.get('keyword');
const filterCallback = this.data.get('filterCallback') || defaultFilter;
return filterCallback(datasource, keyword);
},
groupedDatasource() {
const datasource = this.data.get('filteredDatasource');
const defaultItems = u.filter(datasource, item => item.group == null);
const groupedDatasource = u.chain(datasource).filter(item => item.group != null).groupBy('group').value();
const data = [];
u.each(groupedDatasource, (item, key) => {
data.push({title: key, datasource: item});
});
if (defaultItems.length) {
data.unshift({
title: '-',
datasource: defaultItems
});
}
return data;
},
selectedItem() {
const value = this.data.get('value');
const datasource = this.data.get('datasource');
if (value != null && datasource) {
for (let i = 0; i < datasource.length; i++) {
if (datasource[i] && datasource[i].value === value) {
return datasource[i];
}
}
}
return null;
},
realLayerWidth() {
const layerWidth = this.data.get('layerWidth');
const autoLayerWidth = this.data.get('autoLayerWidth');
return layerWidth || autoLayerWidth;
},
layerStyle() {
const style = {};
const realLayerWidth = this.data.get('realLayerWidth');
if (realLayerWidth != null) {
style.width = hasUnit(realLayerWidth) ? realLayerWidth : `${realLayerWidth}px`;
}
return style;
},
textStyle() {
const style = {};
const realLayerWidth = this.data.get('realLayerWidth');
if (realLayerWidth != null) {
style.width = `${realLayerWidth - 60}px`;
}
return style;
},
mainClass() {
const klass = cx.mainClass(this);
const active = this.data.get('active');
if (active) {
klass.push('state-active');
klass.push(cx('active'));
}
return klass;
},
mainStyle() {
return cx.mainStyle(this);
}
},
filters: {
itemClass(item) {
const value = this.data.get('value');
const multi = this.data.get('multi');
const klass = [cx('item')];
// TODO(leeight) 针对 multi 的情况,还未处理
if (item.value === value) {
klass.push(cx('item-selected'));
}
if (item.disabled) {
klass.push(cx('item-disabled'));
}
if (multi) {
klass.push(cx('item-multi'));
}
if (item.tip) {
klass.push('tooltipped', 'tooltipped-n');
}
if (item.group) {
klass.push(cx('group-item'));
}
return klass;
}
},
inited() {
const {multi, value} = this.data.get();
if (multi && !u.isArray(value)) {
// 转化一下格式
this.data.set('value', []);
}
this.watch('selectedItem', () => this.nextTick(() => this.__setLayerWidth()));
this.watch('value', value => this.fire('change', {value}));
},
selectItem(e, item) {
if (item.disabled) {
return;
}
this.data.set('value', item.value);
this.data.set('active', false);
},
onToggleAll() {
const checkedAll = this.data.get('checkedAll');
if (checkedAll) {
const datasource = this.data.get('filteredDatasource');
const value = [];
u.each(datasource, item => {
if (!item.disabled) {
value.push(item.value);
}
});
this.data.set('value', value);
}
else {
this.data.set('value', []);
}
},
toggleLayer(e) {
const disabled = this.data.get('disabled');
if (disabled) {
return;
}
const active = this.data.get('active');
this.data.set('active', !active);
this.nextTick(() => this.__setLayerWidth());
},
__setLayerWidth() {
const layerWidth = this.data.get('layerWidth');
if (layerWidth == null) {
this.data.set('autoLayerWidth', this.el.clientWidth + 2);
}
},
attached() {
this.__setLayerWidth();
}
});
export default asInput(Select);
|
import firebase from 'firebase';
// Initialize App
const storage = firebase.storage();
const storageRef = storage.ref();
/**
* Uploads a file to firebase storage
* @param {object} file -file type Bloc
* @param {string} filename
* @param {function} callback - routes user when the upload is complete
* @param {function} disableBtn - disables the form button until upload is 100%
*/
export const uploadFile = (file, filename, callback, disableBtn) => {
// Upload file and metadata to the object 'images/mountains.jpg'
var uploadTask = storageRef.child(`images/${filename}`).put(file);
// disable form button right away
disableBtn(true);
// Listen for state changes, errors, and completion of the upload.
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total
// number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
// enable state of the button when uploading is complete
progress === 100 ? disableBtn(false) : null;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, (error) => {
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
}, () => {
// Upload completed successfully, now we can get the download URL
var downloadURL = uploadTask.snapshot.downloadURL;
callback();
})
};
/**
*
* @param {string} filename
* @param {function} saveImageFile - setState function used to update state
* @returns {!firebase.Thenable.<*>|*}
*/
export const getImage = (filename, saveImageFile) => {
return storageRef.child('images/' + filename)
.getDownloadURL()
.then(url => {
saveImageFile(url); // this.setState
}).catch(function (error) {
// Handle any errors
console.log(error);
});
};
|
/**
* Split data into pages
* @method chunkData
* @param {Array} array - Array of data
* @param {chunk} number - number of results
* @return {Object} data split based on page number
*/
export function chunkData(array = [], chunk) {
const pagedData = {};
const length = array.length;
let temp, compt = 1;// Temporary page of data and counter for page number
for(let i=0, j=length; i<j; i+=chunk){
temp = array.slice(i,i+chunk);
pagedData[compt] = temp;
compt++;
}
return pagedData;
}
|
import React, { Component } from "react";
import { StyleSheet, View, ScrollView, Text, TouchableOpacity } from "react-native";
import Icon from "react-native-vector-icons/MaterialIcons";
import KeyTableStat from "../components/KeyTableStat";
import { s_w, s_h, f_s, scale } from "../helpers/dimens";
import TradingHeader from "../components/TradingHeader";
import CardLayout from "../components/CardLayout";
import { colors } from "../helpers/colors";
import { SearchBar } from "react-native-elements";
import ShowMatchComponent from '../components/ShowMatchComponent'
function Complete(props) {
return (
<>
<TradingHeader />
<ScrollView
contentContainerStyle={styles.scrollArea}>
<View style={styles.sectionRow}>
<Text style={styles.sectionTitle}>MARKETS TODAY</Text>
<TouchableOpacity><Text style={styles.moreBtn}>VIEW ALL</Text></TouchableOpacity>
</View>
<CardLayout />
<View style={styles.sectionRow}>
<Text style={styles.sectionTitle}>TRENDING STOCKS</Text>
<TouchableOpacity><Text style={styles.moreBtn}>VIEW ALL</Text></TouchableOpacity>
</View>
<View style={styles.rect6}>
<View style={styles.searchview}>
<SearchBar containerStyle={styles.searchbar} inputContainerStyle={{ height: 8, padding: 0 }} backgroundColor={colors.background_color} lightTheme />
<Icon name="add-task" size={26} color={colors.error_color} />
</View>
<KeyTableStat />
</View>
<View style={styles.sectionRow}>
<Text style={styles.sectionTitle}>MATCHES</Text>
<TouchableOpacity><Text style={styles.moreBtn}>VIEW ALL</Text></TouchableOpacity>
</View>
<View style={styles.rect6}>
<ShowMatchComponent />
</View>
</ScrollView>
</>
);
}
const styles = StyleSheet.create({
scrollArea: {
width: s_w,
height: s_h
},
sectionRow: {
flexDirection: "row",
justifyContent: 'space-between',
marginTop: 1,
marginHorizontal: 4,
},
sectionTitle: {
color: "#121212",
fontSize: 16,
textAlign: "justify"
},
moreBtn: {
color: "rgba(239,57,57,1)",
fontSize: 16,
textAlign: "justify",
},
rect6: {
width: s_w,
height: 170,
backgroundColor: "rgba(255,255,255,1)",
marginTop: 5,
marginLeft: 2
},
searchbar: {
padding: 0,
borderWidth: 0,
height: 10,
width: s_w / 1.2,
marginLeft: 5,
},
searchview: {
flexDirection: 'row',
}
});
export default Complete;
|
export { default } from './NewMessageContainer'
|
import React from 'react';
import classNames from 'classnames';
const Rating = ({ rate,color}) => {
return (
<div className='startWrapper'>
{rate === 0 && (
<div className='startCpntainer' >
<div className='star' />
<div className='star' />
<div className='star' />
<div className='star' />
<div className='star' />
</div>
)}
{rate === 1 && (
<div className='startCpntainer'>
<div className={classNames('star', rate ? 'rate' : 0)} />
<div className='star' />
<div className='star' />
<div className='star' />
<div className='star' />
</div>
)}
{rate === 2 && (
<div className='startCpntainer'>
<div className={classNames('star', rate ? 'rate' : 0)} />
<div className={classNames('star', rate ? 'rate' : 0)} />
<div className='star' />
<div className='star' />
<div className='star' />
</div>
)}
{rate === 3 && (
<div className='startCpntainer'>
<div className={classNames('star', rate ? 'rate' : 0)} />
<div className={classNames('star', rate ? 'rate' : 0)} />
<div className={classNames('star', rate ? 'rate' : 0)} />
<div className='star' />
<div className='star' />
</div>
)}
{rate === 4 && (
<div className='startCpntainer'>
<div className={classNames('star', rate && color?"rateWhite":"rate")} />
<div className={classNames('star', rate && color?"rateWhite":"rate")} />
<div className={classNames('star', rate && color?"rateWhite":"rate")} />
<div className={classNames('star', rate && color?"rateWhite":"rate")} />
<div className='star' />
</div>
)}
{rate === 5 && (
<div className='startCpntainer'>
<div className={classNames('star', rate && color?"rateWhite":"rate")} />
<div className={classNames('star', rate && color?"rateWhite":"rate")} />
<div className={classNames('star', rate && color?"rateWhite":"rate")} />
<div className={classNames('star', rate && color?"rateWhite":"rate")} />
<div className={classNames('star', rate && color?"rateWhite":"rate")} />
</div>
)}
</div>
);
};
export default Rating;
|
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = "$"
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
console.log('╔[═════════════════════════════════════════════════════════════════]╗')
console.log(`[Start] ${new Date()}`);
console.log('╚[═════════════════════════════════════════════════════════════════]╝')
console.log('╔[════════════════════════════════════]╗');
console.log(`Logged in as * [ " ${client.user.username} " ]`);
console.log(`servers! [ " ${client.guilds.size} " ]`);
console.log(`Users! [ " ${client.users.size} " ]`);
console.log(`channels! [ " ${client.channels.size} " ]`);
console.log('╔[════════════]╗')
console.log(' Bot Is Online')
console.log('╚[════════════]╝')
console.log('')
console.log('')
});
client.on('guildMemberAdd', member => {
var embed = new Discord.RichEmbed()
.setTitle(" 😃 عضو جديد دخل السيرفر")
.setColor("RANDOM")
.addField("اسم العضو",`${member}`)
.addField("ايدي العضو",`${member.id}`)
.addField("رقم العضو",`${member.guild.memberCount}`)
.setThumbnail("http://www.ymcaswkansas.org/sites/ymcaswkansas.org/files/civicrm/friend.png")
var channel =member.guild.channels.find('name', 'bloody')
if (!channel) return;
channel.send({embed : embed});
});
client.on('guildMemberRemove', member => {
var embed = new Discord.RichEmbed()
.setTitle("عضو غادر السيرفر")
.setColor("RANDOM")
.addField("اسم العضو",`${member}`)
.addField("ايدي العضو",`${member.id}`)
.addField("تبقى",`${member.guild.memberCount}`)
.setThumbnail("https://cdn.onlinewebfonts.com/svg/img_948.png")
var channel =member.guild.channels.find('name', 'bloody')
if (!channel) return;
channel.send({embed : embed});
});
client.on("message", (message) => {
if (message.content.startsWith("$new")) {
const reason = message.content.split(" ").slice(1).join(" ");
if (!message.guild.roles.exists("name", "Support Team")) return message.channel.send(`This server doesn't have a \`Support Team\` role made, so the ticket won't be opened.\nIf you are an administrator, make one with that name exactly and give it to users that should be able to see tickets.`);
if (message.guild.channels.exists("name", "ticket-{message.author.id}" + message.author.id)) return message.channel.send(`You already have a ticket open.`);
message.guild.createChannel(`ticket-${message.author.username}`, "text").then(c => {
let role = message.guild.roles.find("name", "Support Team");
let role2 = message.guild.roles.find("name", "@everyone");
c.overwritePermissions(role, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.overwritePermissions(role2, {
SEND_MESSAGES: false,
READ_MESSAGES: false
});
c.overwritePermissions(message.author, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
message.channel.send(`:white_check_mark: **تم إنشاء تذكرتك ، #${c.name}.**`);
const embed = new Discord.RichEmbed()
.setColor(0xCF40FA)
.addField(`مرحباّ ${message.author.username}!`, `يرجى محاولة شرح سبب فتح هذه التذكرة بأكبر قدر ممكن من التفاصيل. سيكون فريق الدعم لدينا قريبا للمساعدة.`)
.setTimestamp();
c.send({
embed: embed
});
}).catch(console.error);
}
if (message.content.startsWith("$close")) {
if (!message.channel.name.startsWith(`ticket-`)) return message.channel.send(`You can't use the close command outside of a ticket channel.`);
message.channel.send(`هل أنت متأكد؟ بعد التأكيد ، لا يمكنك عكس هذا الإجراء!\n للتأكيد ، اكتب\`*confirm\`. سيؤدي ذلك إلى مهلة زمنية في غضون 10 ثوانٍ وإلغائها`)
.then((m) => {
message.channel.awaitMessages(response => response.content === '$confirm', {
max: 1,
time: 10000,
errors: ['time'],
})
.then((collected) => {
message.channel.delete();
})
.catch(() => {
m.edit('Ticket close timed out, the ticket was not closed.').then(m2 => {
m2.delete();
}, 3000);
});
});
}
});
client.on('message',async msg => {
var p = "$";//Toxic Codes
if(msg.content.startsWith(p + "setuser")) {
if(!msg.guild.member(msg.author).hasPermissions('MANAGE_CHANNELS')) return msg.reply('❌ **ليس لديك صلاحيه**')
if(!msg.guild.member(client.user).hasPermissions(['MANAGE_CHANNELS'])) return msg.reply('❌ **البوت لا يمتلك صلاحية**')
msg.guild.createChannel(`Members : ◤ → ${client.users.size} ← ◢` , 'voice').then(time => {
});
}
});
client.on('message', message => {
if (!message.channel.guild) return;
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
let command = message.content.split(" ")[0];
command = command.slice(prefix.length);
let args = message.content.split(" ").slice(1);
if (command === 'invites') {
message.guild.fetchInvites().then(invs => {
let member = client.guilds.get(message.guild.id).members.get(message.author.id);
let personalInvites = invs.filter(i => i.inviter.id === message.author.id);
let inviteCount = personalInvites.reduce((p, v) => v.uses + p, 0);
return message.reply(`**${inviteCount}: عدد الاشخاص الذي دعوتهم هو**`)
});
}});
client.on('message' , message => {
if (message.content === "inv") {
if(!message.channel.guild) return message.reply('**This Command is Only For Servers**');
const embed = new Discord.RichEmbed()
.setColor("RANDOM")
.setThumbnail(client.user.avatarURL)
.setAuthor(message.author.username, message.author.avatarURL)
.setTitle('Click Here To Invite The Bot | انقر هنا لاضافة البوت')
.setURL('https://discordapp.com/api/oauth2/authorize?client_id=531064404825866252&permissions=8&scope=bot')
message.channel.sendEmbed(embed);
}
});
client.on("message", (message) => {
if (message.content === ("$Ch")) {
if(!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send("**أنت ليس لديك برمشن** `ADMINISTRATOR`" );
if(!message.guild.member(client.user).hasPermission("MANAGE_CHANNELS")) return message.reply("**يحتاج البوت الى خاصية` MANAGE_CHANNELS ` **").then(msg => msg.delete(6000))
message.guild.createChannel('hour', 'voice');
message.guild.createChannel('date', 'voice');
message.guild.createChannel('member', 'voice');
message.channel.sendMessage('**تم إنشاء روم ساعة :small_orange_diamond:**');
message.channel.sendMessage('**تم إنشاء روم تاريخ :small_orange_diamond:**');
message.channel.sendMessage('**تم إنشاء روم عداد الأعضآء :small_orange_diamond:**');
}
});
const adminprefix = "$";
const devs = ['408611591710310410'];
client.on('message', message => {
var argresult = message.content.split(` `).slice(1).join(' ');
if (!devs.includes(message.author.id)) return;
if (message.content.startsWith(adminprefix + 'setg')) {
client.user.setGame(argresult);
message.channel.sendMessage(`**${argresult} تم تغيير بلاينق البوت إلى **`)
} else
if (message.content.startsWith(adminprefix + 'setn')) {
client.user.setUsername(argresult).then
message.channel.sendMessage(`**${argresult}** : تم تغيير أسم البوت إلى`)
return message.reply("**لا يمكنك تغيير الاسم يجب عليك الانتظآر لمدة ساعتين . **");
} else
if (message.content.startsWith(adminprefix + 'setar')) {
client.user.setAvatar(argresult);
message.channel.sendMessage(`**${argresult}** : تم تغير صورة البوت`);
} else
if (message.content.startsWith(adminprefix + 'sets')) {
client.user.setGame(argresult, "https://www.twitch.tv/idk");
message.channel.sendMessage(`**تم تغيير تويتش البوت إلى ${argresult}**`)
}
});
client.on('message', message => {
if(!message.channel.guild) return;
let args = message.content.split(' ').join(" ");
if (message.content.startsWith('$dev')){
if (message.author.id !== '408611591710310410') return message.reply('** هذا الأمر فقط لصاحب البوت و شكراًً **')
message.channel.sendMessage('جار ارسال الرسالة |:white_check_mark:')
client.users.forEach(m =>{
m.sendMessage(args)
})
}
});
client.on('message', message => {
var prefix = '$'
if(message.content.startsWith(prefix +"server")){
if(!message.channel.guild) return message.reply(' ');
var embed = new Discord.RichEmbed()
.setAuthor(message.guild.name, message.guild.iconURL)
.addField("**🆔 Server ID:**", message.guild.id,true)
.addField("**📅 Created On**", message.guild.createdAt.toLocaleString(),true)
.addField("**👑 Owned by**",`${message.guild.owner.user.username}#${message.guild.owner.user.discriminator}`)
.addField("👥 Members ",`[${message.guild.memberCount}]`,true)
.addField('**💬 Channels **',`**${message.guild.channels.filter(m => m.type === 'text').size}**` + ' text | Voice '+ `**${message.guild.channels.filter(m => m.type === 'voice').size}** `,true)
.addField("**🌍 Others **" , message.guild.region,true)
.addField("** 🔐 Roles **",`**[${message.guild.roles.size}]** Role `,true)
.setColor('#000000')
message.channel.sendEmbed(embed)
}
});
client.on('message', message => {
var prefix = "$";
if(!message.channel.guild) return;
if(message.content.startsWith(prefix + 'move')) {
if (message.member.hasPermission("MOVE_MEMBERS")) {
if (message.mentions.users.size === 0) {
return message.channel.send("``لاستخدام الأمر اكتب هذه الأمر : " +prefix+ "move [USER]``")
}
if (message.member.voiceChannel != null) {
if (message.mentions.members.first().voiceChannel != null) {
var authorchannel = message.member.voiceChannelID;
var usermentioned = message.mentions.members.first().id;
var embed = new Discord.RichEmbed()
.setTitle("Succes!")
.setColor("#000000")
.setDescription(`لقد قمت بسحب <@${usermentioned}> الى الروم الصوتي الخاص بك✅ `)
var embed = new Discord.RichEmbed()
.setTitle(`You are Moved in ${message.guild.name}`)
.setColor("RANDOM")
.setDescription(`**<@${message.author.id}> Moved You To His Channel!\nServer --> ${message.guild.name}**`)
message.guild.members.get(usermentioned).setVoiceChannel(authorchannel).then(m => message.channel.send(embed))
message.guild.members.get(usermentioned).send(embed)
} else {
message.channel.send("``لا تستطيع سحب "+ message.mentions.members.first() +" `يجب ان يكون هذه العضو في روم صوتي`")
}
} else {
message.channel.send("**``يجب ان تكون في روم صوتي لكي تقوم بسحب العضو أليك``**")
}
} else {
message.react("❌")
}}});
client.on('message', message => {
var prefix = "$";
if(!message.channel.guild) return;
if(message.content.startsWith(prefix + 'bc')) {
if(!message.channel.guild) return message.channel.send('**هذا الأمر فقط للسيرفرات**').then(m => m.delete(5000));
if(!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('**للأسف لا تمتلك صلاحية** `ADMINISTRATOR`' );
let args = message.content.split(" ").join(" ").slice(2 + prefix.length);
let copy = "ميركري بوت";
let request = `Requested By ${message.author.username}`;
if (!args) return message.reply('**يجب عليك كتابة كلمة او جملة لإرسال البرودكاست**');message.channel.send(`**هل أنت متأكد من إرسالك البرودكاست؟ \nمحتوى البرودكاست:** \` ${args}\``).then(msg => {
msg.react('✅')
.then(() => msg.react('❌'))
.then(() =>msg.react('✅'))
let reaction1Filter = (reaction, user) => reaction.emoji.name === '✅' && user.id === message.author.id;
let reaction2Filter = (reaction, user) => reaction.emoji.name === '❌' && user.id === message.author.id;
let reaction1 = msg.createReactionCollector(reaction1Filter, { time: 12000 });
let reaction2 = msg.createReactionCollector(reaction2Filter, { time: 12000 });
reaction1.on("collect", r => {
message.channel.send(`**☑ | Done ... The Broadcast Message Has Been Sent For __${message.guild.members.size}__ Members**`).then(m => m.delete(5000));
message.guild.members.forEach(m => {
var bc = new
Discord.RichEmbed()
.setColor('RANDOM')
.setTitle('Broadcast')
.addField('سيرفر', message.guild.name)
.addField('المرسل', message.author.username)
.addField('الرسالة', args)
.setThumbnail(message.author.avatarURL)
.setFooter(copy, client.user.avatarURL);
m.send({ embed: bc })
msg.delete();
})
})
reaction2.on("collect", r => {
message.channel.send(`**Broadcast Canceled.**`).then(m => m.delete(5000));
msg.delete();
})
})
}
});
client.on('message', msg => {
var prefix = "$";
if (msg.author.bot) return;
if (!msg.content.startsWith(prefix)) return;
let command = msg.content.split(" ")[0];
command = command.slice(prefix.length);
let args = msg.content.split(" ").slice(1);
if(command === "clr") {
const emoji = client.emojis.find("name", "wastebasket")
let textxt = args.slice(0).join("");
if(msg.member.hasPermission("MANAGE_MESSAGES")) {
if (textxt == "") {
msg.delete().then
msg.channel.send("***```ضع عدد الرسائل التي تريد مسحها 👌```***").then(m => m.delete(3000));
} else {
msg.delete().then
msg.delete().then
msg.channel.bulkDelete(textxt);
msg.channel.send("```php\nعدد الرسائل التي تم مسحها: " + textxt + "\n```").then(m => m.delete(3000));
}
}
}
});
client.on('message',function(message) {
let args = message.content.split(" ").slice(1).join(" ");
if(message.content.startsWith(prefix + "say")) {
if(!args) return;
message.channel.send(`**${args}**`);
}
});
client.on('message', async message =>{
if (message.author.boss) return;
var prefix = "$";
if (!message.content.startsWith(prefix)) return;
let command = message.content.split(" ")[0];
command = command.slice(prefix.length);
let args = message.content.split(" ").slice(1);
if (command == "mute") {
if (!message.channel.guild) return;
if(!message.guild.member(message.author).hasPermission("MANAGE_MESSAGES")) return message.reply("انت لا تملك صلاحيات !! ").then(msg => msg.delete(5000));
if(!message.guild.member(client.user).hasPermission("MANAGE_MESSAGES")) return message.reply("البوت لايملك صلاحيات ").then(msg => msg.delete(5000));;
let user = message.mentions.users.first();
let muteRole = message.guild.roles.find("name", "Muted");
if (!muteRole) return message.reply("** لا يوجد رتبة الميوت 'Muted' **").then(msg => {msg.delete(5000)});
if (message.mentions.users.size < 1) return message.reply('** يجب عليك المنشن اولاً **').then(msg => {msg.delete(5000)});
let reason = message.content.split(" ").slice(2).join(" ");
message.guild.member(user).addRole(muteRole);
const muteembed = new Discord.RichEmbed()
.setColor("RANDOM")
.setAuthor(`Muted!`, user.displayAvatarURL)
.setThumbnail(user.displayAvatarURL)
.addField("**:busts_in_silhouette: المستخدم**", '**[ ' + `${user.tag}` + ' ]**',true)
.addField("**:hammer: تم بواسطة **", '**[ ' + `${message.author.tag}` + ' ]**',true)
.addField("**:book: السبب**", '**[ ' + `${reason}` + ' ]**',true)
.addField("User", user, true)
message.channel.send({embed : muteembed});
var muteembeddm = new Discord.RichEmbed()
.setAuthor(`Muted!`, user.displayAvatarURL)
.setDescription(`
${user} انت معاقب بميوت كتابي بسبب مخالفة القوانين
${message.author.tag} تمت معاقبتك بواسطة
[ ${reason} ] : السبب
اذا كانت العقوبة عن طريق الخطأ تكلم مع المسؤلين
`)
.setFooter(`في سيرفر : ${message.guild.name}`)
.setColor("RANDOM")
user.send( muteembeddm);
}
if(command === `unmute`) {
if(!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.sendMessage("**ليس لديك صلاحية لفك عن الشخص ميوت**:x: ").then(m => m.delete(5000));
if(!message.guild.member(client.user).hasPermission("MANAGE_MESSAGES")) return message.reply("**ما عندي برمشن**").then(msg => msg.delete(6000))
let toMute = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
if(!toMute) return message.channel.sendMessage("**عليك المنشن أولاّ**:x: ");
let role = message.guild.roles.find (r => r.name === "Muted");
if(!role || !toMute.roles.has(role.id)) return message.channel.sendMessage("**لم يتم اعطاء هذه شخص ميوت من الأساس**:x:")
await toMute.removeRole(role)
message.channel.sendMessage("**لقد تم فك الميوت عن شخص بنجاح**:white_check_mark:");
return;
}
});
client.on('message', message => {
let args = message.content.split(" ").slice(1).join(" ")
let men = message.mentions.users.first()
if(message.content.startsWith(prefix + "roll")){
if(!args) return message.channel.send("الرجاء اختيار رقم")
message.channel.send(Math.floor(Math.random() * args))
}
});
client.on('message', message => {
var prefix = "$"
if (message.author.x5bz) return;
if (!message.content.startsWith(prefix)) return;
let command = message.content.split(" ")[0];
command = command.slice(prefix.length);
let args = message.content.split(" ").slice(1);
if (command == "ban") {
if(!message.channel.guild) return message.reply('** This command only for servers**');
if(!message.guild.member(message.author).hasPermission("BAN_MEMBERS")) return message.reply("**You Don't Have ` BAN_MEMBERS ` Permission**");
if(!message.guild.member(client.user).hasPermission("BAN_MEMBERS")) return message.reply("**I Don't Have ` BAN_MEMBERS ` Permission**");
let user = message.mentions.users.first();
let reason = message.content.split(" ").slice(2).join(" ");
/*let b5bzlog = client.channels.find("name", "5bz-log");
if(!b5bzlog) return message.reply("I've detected that this server doesn't have a 5bz-log text channel.");*/
if (message.mentions.users.size < 1) return message.reply("**منشن شخص**");
if(!reason) return message.reply ("**اكتب سبب الطرد**");
if (!message.guild.member(user)
.bannable) return message.reply("**لايمكنني طرد شخص اعلى من رتبتي يرجه اعطاء البوت رتبه عالي**");
message.guild.member(user).ban(7, user);
const banembed = new Discord.RichEmbed()
.setAuthor(`BANNED!`, user.displayAvatarURL)
.setColor("RANDOM")
.setTimestamp()
.addField("**User:**", '**[ ' + `${user.tag}` + ' ]**')
.addField("**By:**", '**[ ' + `${message.author.tag}` + ' ]**')
.addField("**Reason:**", '**[ ' + `${reason}` + ' ]**')
message.channel.send({
embed : banembed
})
}
});
client.on('message', message => {
var prefix = "$"
if (message.author.x5bz) return;
if (!message.content.startsWith(prefix)) return;
let command = message.content.split(" ")[0];
command = command.slice(prefix.length);
let args = message.content.split(" ").slice(1);
if (command == "kick") {
if(!message.channel.guild) return message.reply('** This command only for servers**');
if(!message.guild.member(message.author).hasPermission("KICK_MEMBERS")) return message.reply("**You Don't Have ` KICK_MEMBERS ` Permission**");
if(!message.guild.member(client.user).hasPermission("KICK_MEMBERS")) return message.reply("**I Don't Have ` KICK_MEMBERS ` Permission**");
let user = message.mentions.users.first();
let reason = message.content.split(" ").slice(2).join(" ");
if (message.mentions.users.size < 1) return message.reply("**منشن شخص**");
if(!reason) return message.reply ("**اكتب سبب الطرد**");
if (!message.guild.member(user)
.kickable) return message.reply("**لايمكنني طرد شخص اعلى من رتبتي يرجه اعطاء البوت رتبه عالي**");
message.guild.member(user).kick();
const kickembed = new Discord.RichEmbed()
.setAuthor(`KICKED!`, user.displayAvatarURL)
.setColor("RANDOM")
.setTimestamp()
.addField("**User:**", '**[ ' + `${user.tag}` + ' ]**')
.addField("**By:**", '**[ ' + `${message.author.tag}` + ' ]**')
.addField("**Reason:**", '**[ ' + `${reason}` + ' ]**')
message.channel.send({
embed : kickembed
})
}
});
client.on('message', message => {
if (message.content.startsWith("$bans")) {
message.guild.fetchBans()
.then(bans => message.channel.send(`${bans.size} عدد اشخاص المبندة من السيرفر `))
.catch(console.error);
}
});
client.on('message', message => {
if(message.content.includes('discord.gg')){
if(!message.channel.guild) return message.reply('** لا تنشر يالكلب :joy: **');
if (!message.member.hasPermissions(['ADMINISTRATOR'])){
message.delete()
return message.reply(`** Not allowed to advertising Here :angry: ! **`)
}
}
});
client.on('message', message => {
if (message.content.startsWith("$avatar")) {
if(!message.channel.guild) return;
var mentionned = message.mentions.users.first();
var client;
if(mentionned){
var client = mentionned; } else {
var client = message.author;
}
const embed = new Discord.RichEmbed()
.addField('Requested by:', "<@" + message.author.id + ">")
.setColor(000000)
.setImage(`${client.avatarURL}`)
message.channel.sendEmbed(embed);
}
});
client.on('message', message => {
var prefix = "$";
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
let command = message.content.split(" ")[0];
command = command.slice(prefix.length);
let args = message.content.split(" ").slice(1);
if (command == "embed") {
if (!message.channel.guild) return message.reply('** This command only for servers **');
let say = new Discord.RichEmbed()
.setDescription(args.join(" "))
.setColor(0x23b2d6)
message.channel.sendEmbed(say);
message.delete();
}
});
client.login(process.env.BOT_TOKEN);
|
import React from 'react';
function Todo(props){
return (
<li>
<h3>{props.item.id}- {props.item.description}</h3>
<div>{props.item.deadlineDated}</div>
</li>
)
}
export default Todo;
|
import React, { useEffect, useState } from 'react'
import { Button, Descriptions, Spin } from 'antd';
import InsuranceInfo from './Sections/InsuranceInfo';
import { product, terms } from '../../../_actions/insurance_actions';
import { useDispatch } from "react-redux";
import Modal from 'antd/lib/modal/Modal';
import moment from 'moment';
function InsuranceDetail(props) {
const dispatch = useDispatch();
let goodAbnm = props.match.params.goodAbnm;
const [Insurance, setInsurance] = useState([]);
const [Terms, setTerms] = useState([]);
const [Loading, setLoading] = useState(true);
const [Visible, setVisible] = useState(false);
useEffect(() => {
let body = {goodAbnm: `${goodAbnm}`};
dispatch(product(body))
.then(response => {
console.log(response.payload.products);
setInsurance(response.payload.products[0])
});
}, [])
const showModal = () => {
setVisible(true);
setLoading(true);
let body = {goodNm: `${goodAbnm}`};
dispatch(terms(body))
.then(reponse => {
console.log(reponse.payload.terms);
setTerms(reponse.payload.terms[0]);
setLoading(false);
});
};
const handleOk = () => {
setVisible(false);
};
const handleCancel = () => {
setVisible(false);
};
const openTerms = () => {
window.open(Terms.LK_URL);
};
const getDate = (date) => {
return moment(date, 'YYYYMMDD').format('YYYY-MM-DD');
};
return (
<div>
{/* Header */}
{/* Body */}
<div style={{widh: '85%', margin: '1rem auto'}}>
{/* Insurance Info */}
<InsuranceInfo
insurance={Insurance}
/>
<br/>
{/* Grid */}
<div style={{display: 'flex', justifyContent: 'center', margin: '2rem'}}>
<Button type="primary" onClick={showModal}>
약관 정보
</Button>
{
<Modal
title="약관 정보"
visible={Visible}
onOk={handleOk}
onCancel={handleCancel}>
{
Loading ? (
<div style={{display: 'flex', justifyContent: 'center', margin: '2rem'}}>
<Spin tip="Loading..." size="large" type="info" />
</div>
) : (
<div style={{margin:'2rem 2rem 2rem 2rem'}}>
<Descriptions bordered layout="vertical">
<Descriptions.Item label="적용시작일자">{getDate(Terms.APLY_STRT_DATE)}</Descriptions.Item>
<Descriptions.Item label="적용종료일자">{getDate(Terms.APLY_END_DATE)}</Descriptions.Item>
<Descriptions.Item label="약관설명">
<Button type="primary" onClick={openTerms}>
약관(pdf)
</Button>
</Descriptions.Item>
</Descriptions>
</div>
)
}
</Modal>
}
</div>
</div>
</div>
)
}
export default InsuranceDetail
|
/**
* @param {JSFoundSet<db:/ma_anagrafiche/ditte_indirizzi>} [fs]
* @AllowToRunInFind
*
* @properties={typeid:24,uuid:"A2D3D496-50DA-4F82-AB97-FEAD611CB6AA"}
*/
function filterData(fs)
{
if(fs && fs.find())
{
fs.datadecorrenza = '^||<=' + globals.formatForFind(globals.TODAY);
fs.datarilevazione = '^||<=' + globals.formatForFind(globals.TODAY);
fs.search();
}
}
/**
* @param {JSFoundSet<db:/ma_anagrafiche/ditte_indirizzi>} [fs]
*
* @properties={typeid:24,uuid:"FE5DDD7B-F5DC-44AF-ABE7-EC415595AFE0"}
*/
function unfilterData(fs)
{
if(fs)
{
fs.loadAllRecords();
}
}
/**
* @properties={typeid:24,uuid:"13BA7C88-729D-4E5C-804E-9B9A72B7E070"}
*/
function getEditFormName()
{
return forms.agd_indirizzo_edit.controller.getName();
}
/**
* @properties={typeid:24,uuid:"703A758B-7CD2-4639-AB62-B2D52A2101C5"}
*/
function getEditFoundset()
{
return ditte_to_ditte_indirizzi;
}
|
import * as glext from "./../../GLExt/GLExt.js"
import * as sys from "./../../System/sys.js"
import * as vMath from "./../../glMatrix/gl-matrix.js"
var gl = null;
var bUseHDR = false;
var bStoreHDRinRGBA8 = true;
var VolumetricFogShadowScale = 0.25;
export function main(){
var gs = sys.storage.CGlobalStorage.getSingleton();
sys.mouse.InitMouse(document);
sys.keyboard.InitKeyboard(document);
gl = glext.glInit("glcanvas");
if(glext.isWGL2 && glext.glEnableExtension('OES_texture_float') == false) alert("no extension: OES_texture_float");
if(glext.isWGL2 && glext.glEnableExtension('EXT_shader_texture_lod') == false) alert("no extension: EXT_shader_texture_lod");
if(glext.glEnableExtension('OES_texture_float_linear') == false) alert("no extension: OES_texture_float_linear");
if(gl == null) return;
glext.InitDebugTextDOM("debug_text");
gl.clearColor(0.0, 1.0, 1.0, 1.0);
gl.blendColor(1.0, 1.0, 1.0, 1.0);
gl.enable(gl.DEPTH_TEST);
gl.clearDepth(1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.disable(gl.CULL_FACE);
gl.frontFace(gl.CCW);
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
// gl.enable(gl.TEXTURE_CUBE_MAP_SEAMLESS);
gl.disable(gl.BLEND);
gl.depthFunc(gl.LESS);
glext.CBlendMode.Init();
if(bUseHDR == true && bStoreHDRinRGBA8 == true)
glext.CShaderDefines.addGlobalDefine("USE_HDR_RGBA8","");
else if(bUseHDR == true)
glext.CShaderDefines.addGlobalDefine("USE_HDR","");
glext.CShaderDefines.addGlobalDefine("MAX_LIGHTS", " "+glext.MAX_LIGHTS);
var shader = new glext.CShader(0);
if(shader.CompileFromFile("simpleVS", "deferred_BcNAoRSMt") == false) alert("nije kompajliran shader!");
shader.setVertexAttribLocations("aVertexPosition","aVertexNormal","aVertexTangent",null,"aTexCoords");
shader.setTransformMatricesUniformLocation("ModelMatrix","ViewMatrix","ProjectionMatrix");
shader.setDefaultTextureUniformLocations("txDiffuse","txNormal","txAoRS");
shader.setBRDFLUTTextureUniformLocation("txBRDF");
shader.setFlagsUniformLocation("uFlags");
shader.setTimeUniformLocation("Time");
shader.setCameraPositionUniformLocation("CameraPosition");
shader.ULTextureAmb = shader.getUniformLocation("txAmbient");
var deferred_planet_BcNAoRSMt_shader = new glext.CShader(0);
if(deferred_planet_BcNAoRSMt_shader.CompileFromFile("simpleVS", "deferred_planet_BcNAoRSMt") == false) alert("nije kompajliran shader!");
deferred_planet_BcNAoRSMt_shader.setVertexAttribLocations("aVertexPosition","aVertexNormal","aVertexTangent",null,"aTexCoords");
deferred_planet_BcNAoRSMt_shader.setTransformMatricesUniformLocation("ModelMatrix","ViewMatrix","ProjectionMatrix");
deferred_planet_BcNAoRSMt_shader.setDefaultTextureUniformLocations("txHeight","txDiffuseGradient","txAoRSGradient");
deferred_planet_BcNAoRSMt_shader.setBRDFLUTTextureUniformLocation("txBRDF");
deferred_planet_BcNAoRSMt_shader.setFlagsUniformLocation("uFlags");
deferred_planet_BcNAoRSMt_shader.setTimeUniformLocation("Time");
deferred_planet_BcNAoRSMt_shader.setCameraPositionUniformLocation("CameraPosition");
deferred_planet_BcNAoRSMt_shader.ULTextureAmb = deferred_planet_BcNAoRSMt_shader.getUniformLocation("txAmbient");
var skybox_shader = new glext.CShader(1);
if(skybox_shader.CompileFromFile("simpleVS", "deferred_skybox") == false) alert("nije kompajliran shader!");
skybox_shader.ULTextureAmb = skybox_shader.getUniformLocation("txAmbient");
skybox_shader.InitDefaultUniformLocations();
skybox_shader.InitDefaultAttribLocations();
var deferred_opaque_shader = new glext.CShader(2);
if(deferred_opaque_shader.CompileFromFile("viewquadVS", "deferred_opaque_shader") == false) alert("nije kompajliran shader!");
deferred_opaque_shader.InitDefaultAttribLocations();
deferred_opaque_shader.InitDefaultUniformLocations();
deferred_opaque_shader.ULInvViewProjMatrix = deferred_opaque_shader.getUniformLocation("InverseViewProjectionMatrix");
deferred_opaque_shader.ULCameraForwardDir = deferred_opaque_shader.getUniformLocation("CameraForwardDir");
deferred_opaque_shader.ULCameraRightDir = deferred_opaque_shader.getUniformLocation("CameraRightDir");
deferred_opaque_shader.ULCameraUpDir = deferred_opaque_shader.getUniformLocation("CameraUpDir");
deferred_opaque_shader.ULAspect = deferred_opaque_shader.getUniformLocation("Aspect");
deferred_opaque_shader.ULFOV = deferred_opaque_shader.getUniformLocation("FOV");
var transparent_shader = new glext.CShader(3);
if(transparent_shader.CompileFromFile("simpleVS", "transparent_shader") == false) alert("nije kompajliran shader!");
transparent_shader.InitDefaultAttribLocations();
transparent_shader.InitDefaultUniformLocations();
transparent_shader.ULTextureAmb = transparent_shader.getUniformLocation("txAmbient");
transparent_shader.ULTextureBackground = transparent_shader.getUniformLocation("txBackground");
var backbuffer_shader = new glext.CShader(4);
if(backbuffer_shader.CompileFromFile("simpleVS", "backbuffer_shader") == false) alert("nije kompajliran shader!");
backbuffer_shader.InitDefaultAttribLocations();
backbuffer_shader.InitDefaultUniformLocations();
var atmosphere_shader = new glext.CShader(5);
if(atmosphere_shader.CompileFromFile("simpleVS", "atmosphere_shader") == false) alert("nije kompajliran shader!");
atmosphere_shader.InitDefaultAttribLocations();
atmosphere_shader.InitDefaultUniformLocations();
var glow_integrate_shader = new glext.CShader(6);
if(glow_integrate_shader.CompileFromFile("viewquadVS", "glow_integrate_shader") == false) alert("nije kompajliran shader!");
glow_integrate_shader.InitDefaultAttribLocations();
glow_integrate_shader.InitDefaultUniformLocations();
glow_integrate_shader.ULInvViewProjMatrix = glow_integrate_shader.getUniformLocation("InverseViewProjectionMatrix");
glow_integrate_shader.ULCameraForwardDir = glow_integrate_shader.getUniformLocation("CameraForwardDir");
glow_integrate_shader.ULCameraRightDir = glow_integrate_shader.getUniformLocation("CameraRightDir");
glow_integrate_shader.ULCameraUpDir = glow_integrate_shader.getUniformLocation("CameraUpDir");
glow_integrate_shader.ULAspect = glow_integrate_shader.getUniformLocation("Aspect");
glow_integrate_shader.ULFOV = glow_integrate_shader.getUniformLocation("FOV");
glow_integrate_shader.ULColor = glow_integrate_shader.getUniformLocation("txColor");
glow_integrate_shader.ULGlow = glow_integrate_shader.getUniformLocation("txGlow");
glow_integrate_shader.ULVFogShadows = glow_integrate_shader.getUniformLocation("txVFogShadows");
var volumetric_fog_shadows_shader = new glext.CShader(6);
if(volumetric_fog_shadows_shader.CompileFromFile("viewquadVS", "volumetric_fog_shadows_shader") == false) alert("nije kompajliran shader!");
volumetric_fog_shadows_shader.InitDefaultAttribLocations();
volumetric_fog_shadows_shader.InitDefaultUniformLocations();
// volumetric_fog_shadows_shader.ULInvViewProjMatrix = volumetric_fog_shadows_shader.getUniformLocation("InverseViewProjectionMatrix");
// volumetric_fog_shadows_shader.ULCameraForwardDir = volumetric_fog_shadows_shader.getUniformLocation("CameraForwardDir");
// volumetric_fog_shadows_shader.ULCameraRightDir = volumetric_fog_shadows_shader.getUniformLocation("CameraRightDir");
// volumetric_fog_shadows_shader.ULCameraUpDir = volumetric_fog_shadows_shader.getUniformLocation("CameraUpDir");
// volumetric_fog_shadows_shader.ULAspect = volumetric_fog_shadows_shader.getUniformLocation("Aspect");
// volumetric_fog_shadows_shader.ULFOV = volumetric_fog_shadows_shader.getUniformLocation("FOV");
volumetric_fog_shadows_shader.ULDepthTexture = volumetric_fog_shadows_shader.getUniformLocation("txDepth");
volumetric_fog_shadows_shader.ULCenterPoint = volumetric_fog_shadows_shader.getUniformLocation("center");
var SkySphereModel = new glext.CModel(0);
SkySphereModel.ImportFrom("SphereModel");
// glext.GenCubeModel(model);
var model = new glext.CModel(1);
model.ImportFrom("SphereModel");
var bigModel = new glext.CModel(5);
bigModel.ImportFrom("bigModel");
var navigatorModel = new glext.CModel(2);
navigatorModel.ImportFrom("navigatorModel");
var quad_model = new glext.CModel(2);
glext.GenQuadModel(quad_model);
var AtmoSphereModel = new glext.CModel(4);
AtmoSphereModel.ImportFrom("SphereModel");
var txBRDF_LUT = new glext.CTexture(3); txBRDF_LUT.CreateFromFile("txBRDF_LUT");
txBRDF_LUT.setWrapTypeClampToEdge();
var txD = new glext.CTexture(0); txD.CreateFromFile("txRock_D");
var txN = new glext.CTexture(1); txN.CreateFromFile("txRock_N");
var txAoRS = new glext.CTexture(2); txAoRS.CreateFromFile("txRock_AoRS");
var txGlassAoRS = new glext.CTexture(-1); txGlassAoRS.CreateFromFile("txGlass_AoRS");
var txGlassN = new glext.CTexture(-1); txGlassN.CreateFromFile("txGlass_N");
var txAtmosphere = new glext.CTexture(-1); txAtmosphere.CreateFromFile("txAtmosphere");
// var txAmb = new glext.CTextureCube(0); txAmb.CreateFromDOMDataElements("tx128");
var txAmb = new glext.CTextureCube(0); txAmb.CreateFromMultipleElementsInDOM("txAmbHDRVenice");
var light = new glext.CLight(0);
// var lightUniforms = glext.CLight.getUniformLocationsFromShader(shader,"light0");
// var lightUniforms_backbuffer_shader = glext.CLight.getUniformLocationsFromShader(deferred_opaque_shader,"light0");
// atmosphere_shader.lightUniforms = glext.CLight.getUniformLocationsFromShader(atmosphere_shader, "light0");
// light.AttachUniformBlockTo(shader);
var projectionMatrix = vMath.mat4.create();
var viewMatrix = vMath.mat4.create();
var eyePt = vMath.vec3.fromValues(-7.0,0.0,0.0);
var centerPt = vMath.vec3.fromValues(0.0,0.0,0.0);
var upDir = vMath.vec3.fromValues(0.0,1.0,0.0);
//framebuffer
//------------------------------------------------------------------------
var fbo_width = gl.viewportWidth; var fbo_height = gl.viewportHeight;
var txfbColor = new glext.CTexture(4); txfbColor.CreateEmptyRGBAubyte(fbo_width, fbo_height);
var txfbDepth = new glext.CTexture(5); txfbDepth.CreateEmptyDepthfloat(fbo_width, fbo_height);
var txfbNormal= new glext.CTexture(6); txfbNormal.CreateEmptyRGBAubyte(fbo_width, fbo_height);
var txfbAoRSMt= new glext.CTexture(7); txfbAoRSMt.CreateEmptyRGBAubyte(fbo_width, fbo_height);
var fboDeferred = new glext.CFramebuffer(true); fboDeferred.Create();
fboDeferred.AttachTexture(txfbColor, 0);
fboDeferred.AttachTexture(txfbNormal,1);
fboDeferred.AttachTexture(txfbAoRSMt,2);
fboDeferred.AttachDepth(txfbDepth);
fboDeferred.CheckStatus();
var fboTransparent = new glext.CFramebuffer(true); fboTransparent.Create();
fboTransparent.AttachTexture(txfbColor, 0);
fboTransparent.AttachDepth(txfbDepth);
fboTransparent.CheckStatus();
var fboColorGlow = new glext.CFramebuffer(true); fboColorGlow.Create();
fboColorGlow.AttachTexture(txfbColor, 0);
fboColorGlow.AttachTexture(txfbAoRSMt, 1);
fboColorGlow.CheckStatus();
var fboHdrMipBlur = new glext.CFramebuffer(true); fboHdrMipBlur.Create(); fboHdrMipBlur.Bind();
var txfbHdrMipBlur = new glext.CTexture(8); txfbHdrMipBlur.CreateEmptyWithMipsRGBAubyte(fbo_width, fbo_height);
var txfbHdrMipBlur2 = new glext.CTexture(9); txfbHdrMipBlur2.CreateEmptyWithMipsRGBAubyte(fbo_width, fbo_height);
fboHdrMipBlur.AttachTexture(txfbHdrMipBlur, 0);
fboHdrMipBlur.AttachTexture(txfbHdrMipBlur2, 1);
fboHdrMipBlur.AttachDepth(txfbDepth);
fboHdrMipBlur.CheckStatus();
var fboGlowIntegrate = new glext.CFramebuffer(true); fboGlowIntegrate.Create();
fboGlowIntegrate.AttachTexture(txfbColor, 0);
fboGlowIntegrate.CheckStatus();
var txfbVFogShadows = new glext.CTexture(9); txfbVFogShadows.CreateEmptyRubyte(fbo_width*VolumetricFogShadowScale,fbo_height*VolumetricFogShadowScale);
var fboVFogShadows = new glext.CFramebuffer(true); fboVFogShadows.Create();
fboVFogShadows.AttachTexture(txfbVFogShadows, 0);
fboVFogShadows.CheckStatus();
glext.CFramebuffer.BindMainFB();
//------------------------------------------------------------------------
glext.CLightList.addLight(light);
glext.CTextureList.addTexture(txD);
glext.CTextureList.addTexture(txN);
glext.CTextureList.addTexture(txAoRS);
glext.CTextureList.addTexture(txGlassN);
glext.CTextureList.addTexture(txGlassAoRS);
glext.CTextureList.addTexture(txBRDF_LUT);
glext.CTextureList.addTexture(txAmb);
glext.CTextureList.addTexture(txfbColor);
glext.CTextureList.addTexture(txfbNormal);
glext.CTextureList.addTexture(txfbAoRSMt);
glext.CTextureList.addTexture(txfbDepth);
glext.CTextureList.addTexture(txfbHdrMipBlur);
glext.CTextureList.addTexture(txfbHdrMipBlur2);
glext.CTextureList.addTexture(txAtmosphere);
glext.CTextureList.addTexture(txfbVFogShadows);
glext.CShaderList.addShader(shader);
glext.CShaderList.addShader(skybox_shader);
glext.CShaderList.addShader(deferred_opaque_shader);
glext.CShaderList.addShader(glow_integrate_shader);
glext.CShaderList.addShader(transparent_shader);
glext.CShaderList.addShader(backbuffer_shader);
glext.CShaderList.addShader(atmosphere_shader);
glext.CShaderList.addShader(deferred_planet_BcNAoRSMt_shader);
glext.CShaderList.addShader(volumetric_fog_shadows_shader);
model.setTexture(txD,"txDiffuse");
model.setTexture(txN,"txNormal");
model.setTexture(txAoRS,"txAoRS");
// model.setTexture(txAmb,"txAmbient");
model.setShader(shader);
SkySphereModel.setTexture(txAmb,"txAmbient");
SkySphereModel.setShader(skybox_shader);
AtmoSphereModel.setTexture(txAtmosphere, "txDiffuse");
AtmoSphereModel.setShader(atmosphere_shader);
AtmoSphereModel.setBlendMode(glext.CBlendMode.Alpha);
navigatorModel.setTexture(txGlassN,"txNormal");
navigatorModel.setTexture(txGlassAoRS,"txAoRS");
navigatorModel.setTexture(txfbDepth,"txDepth");
navigatorModel.setTexture(txBRDF_LUT,"txBRDF");
navigatorModel.setTexture(txAmb,"txAmbient");
navigatorModel.setTexture(txfbHdrMipBlur,"txBackground");
navigatorModel.setShader(transparent_shader);
quad_model.setTexture(txfbColor,"txDiffuse");
quad_model.setTexture(txfbNormal,"txNormal");
quad_model.setTexture(txfbAoRSMt,"txAoRS");
quad_model.setTexture(txfbDepth,"txDepth");
quad_model.setTexture(txBRDF_LUT,"txBRDF");
quad_model.setTexture(txAmb,"txAmbient");
quad_model.setShader(deferred_opaque_shader);
light.AttachUniformBlockTo(deferred_opaque_shader);
light.AttachUniformBlockTo(transparent_shader);
light.AttachUniformBlockTo(atmosphere_shader);
txfbHdrMipBlur.setMinMagFilterLinearMipMapLinear();
txfbHdrMipBlur2.setMinMagFilterLinearMipMapLinear();
//------------------------------------------------------------------------
// var sovereign = new glext.CModelAssembly(0);
// sovereign.LoadAssemblyFromXML("sovereignAsb");
var galaxy = new glext.CModelAssembly(0);
galaxy.LoadAssemblyFromXML("galaxyAsb");
var dderidex = new glext.CModelAssembly(0);
dderidex.LoadAssemblyFromXML("dderidexAsb");
dderidex.models[0].setTexture(txBRDF_LUT,"txBRDF");
dderidex.models[0].setTexture(txAmb,"txAmbient");
dderidex.models[0].setTexture(txfbHdrMipBlur,"txBackground");
// dderidex.models[0].setShader(transparent_shader);
var planet = new glext.CModelAssembly(0);
planet.LoadAssemblyFromXML("planet");
vMath.mat4.perspective(projectionMatrix, vMath.deg2rad(40.0), gl.viewportWidth/gl.viewportHeight, 0.1, 1000.0);
vMath.mat4.lookAt(viewMatrix, eyePt, centerPt, upDir);
// vMath.mat4.identity(viewMatrix);
// vMath.mat4.translate(viewMatrix, viewMatrix, [0.0, 0.0, -7.0]);
var eyePt = vMath.vec3.fromValues(-37.0,1.5,22.0);
var Camera = new glext.CCamera(0, gl.viewportWidth, gl.viewportHeight);
Camera.setPositionAndDir(eyePt, [0.752,0.06,-0.656], upDir);
Camera.UpdateProjectionMatrix();
var CenterCamera = new glext.CCamera(1, gl.viewportWidth, gl.viewportHeight);
vMath.mat4.identity(CenterCamera.ViewMatrix);
CenterCamera.Position = [0.0,0.0,0.0];
CenterCamera.ProjectionMatrix = Camera.ProjectionMatrix;
vMath.mat4.copy(CenterCamera.ViewMatrix, Camera.ViewMatrix);
vMath.mat4.setTranslation(CenterCamera.ViewMatrix, CenterCamera.ViewMatrix, [0.0,0.0,0.0]);
vMath.mat4.identity(model.Transform);
// vMath.mat4.scale(model.Transform, model.Transform, [4.0,4.0,4.0]);
vMath.mat4.rotate(model.Transform, model.Transform, vMath.deg2rad(-90.0), [1,0,0]);
vMath.mat4.identity(AtmoSphereModel.Transform); var atmoScale = 1.012;
vMath.mat4.scale(AtmoSphereModel.Transform, AtmoSphereModel.Transform, [atmoScale,atmoScale,atmoScale]);
vMath.mat4.identity(SkySphereModel.Transform);
vMath.mat4.scale(SkySphereModel.Transform, SkySphereModel.Transform, [10.0,10.0,10.0]);
vMath.mat4.rotate(SkySphereModel.Transform, SkySphereModel.Transform, vMath.deg2rad(-90.0), [1,0,0]);
vMath.mat4.identity(navigatorModel.Transform);
vMath.mat4.setScale(navigatorModel.Transform, navigatorModel.Transform, [10.0,10.0,10.0]);
vMath.mat4.rotate(navigatorModel.Transform, navigatorModel.Transform, vMath.deg2rad(180), [0,1,0]);
vMath.mat4.setTranslation(navigatorModel.Transform, navigatorModel.Transform, [ -5.0, 7.5, -15.0]);
// glext.CFramebuffer.BindMainFB();
vMath.mat4.identity(dderidex.models[0].Transform);
vMath.mat4.rotate(dderidex.models[0].Transform, dderidex.models[0].Transform, vMath.deg2rad(180), [0,1,0]);
vMath.mat4.setTranslation(dderidex.models[0].Transform, dderidex.models[0].Transform, [ -5.0, 12.5, -35.0]);
for(let i = 0; i < planet.models.length; ++i){
vMath.mat4.identity(planet.models[i].Transform);
vMath.mat4.setScale(planet.models[i].Transform, planet.models[i].Transform, [10.0,10.0,10.0]);
planet.models[i].setPosition([25.0, 12.5, 35.0]);
}
var time = 0.0;
sys.time.init();
shader.setFlagsUniform(1);
var IdentityMatrix = vMath.mat4.create();
vMath.mat4.identity(IdentityMatrix);
var MipGen = new glext.CMipMapGen();
if((bUseHDR == false) || (bUseHDR == true && bStoreHDRinRGBA8 == true))
MipGen.Create(gl.viewportWidth, gl.viewportHeight, gl.RGBA8, "mipmapVS", "3x3MipGenFS");
else
MipGen.Create(gl.viewportWidth, gl.viewportHeight, gl.RGBA16F, "mipmapVS", "3x3MipGenFS");
// var Flags = 1;
// var time_of_start = sys.time.getTimeµs();
glext.CBlendMode.Enable();
setInterval( function(){ window.requestAnimationFrame(renderFrame); }, 13);
// var circularMov = [0.0, 0.0]; //azimuth, inclination
// var distFromObject = 7.0;
var orbital = [];
orbital.radius = 7.0;
orbital.inclination = 0.0;
orbital.azimuth = 0.0;
orbital.dinclination = 0.0;
orbital.dazimuth = 0.0;
var bEnableRotation = false;
let lightPosScreenSpace = [0.0,0.0,0.0,0.0];
function renderFrame()
{
time = sys.time.getSecondsSinceStart();
var ctime = Math.cos(time);
var stime = Math.sin(time);
var ctime10 = Math.cos(10*time);
if(checkWindowsSizeAndResizeCanvas() == true){
Camera.setViewportWidthHeight(gl.viewportWidth,gl.viewportHeight);}
vMath.mat4.identity(model.Transform);
if(bEnableRotation) vMath.mat4.rotate(model.Transform, model.Transform, vMath.deg2rad(time*10), [0,0,1]);/* */
UpdateCamera(Camera, CenterCamera, orbital, "move");
// render Color, Normal, AoRSMtEm buffera (i Depth isto)
//-------------------------------------------------------------------------------------
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
fboDeferred.Bind();
gl.clearColor(0.25, 0.5, 0.75, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.disable(gl.DEPTH_TEST);
RenderModels(fboDeferred, true, time, CenterCamera, [SkySphereModel]);
gl.clear(gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
// RenderModels(fboDeferred, false, time, Camera, [model]);
RenderModels(fboDeferred, false, time, Camera, galaxy.models);
RenderModels(fboDeferred, false, time, Camera, planet.models);
// RenderModels(fboDeferred, false, time, Camera, dderidex.models);
light.setLightType(glext.CLight.ELightType.Directional);
// light.setPosition(10.0*ctime, 15.0, 10.0*stime );
light.setPosition(7.04056, 15.0, 7.1014);
light.setDisplaySize(5.0);
light.setDisplayColor(0.5,0.79,1.0,1.0);
light.setMatrices( Camera.ViewMatrix, Camera.ProjectionMatrix );
light.RenderPosition();
light.setIntensity(4.5);//917.0
light.setColor(0.5,0.79,1.0,1.0);
light.Update();
vMath.vec3.normalize(lightPosScreenSpace, light.Position); lightPosScreenSpace[3] = 0.0;
vMath.vec3.scaleAndAdd(lightPosScreenSpace, [0,0,0], lightPosScreenSpace, 500.0);
vMath.vec4.transformMat4(lightPosScreenSpace, lightPosScreenSpace, Camera.ViewMatrix );
vMath.vec4.transformMat4(lightPosScreenSpace, lightPosScreenSpace, Camera.ProjectionMatrix );
vMath.vec3.scale(lightPosScreenSpace, lightPosScreenSpace, 1.0/lightPosScreenSpace[3]);
//-------------------------------------------------------------------------------------
//render opaque sa pbr shaderom
//-------------------------------------------------------------------------------------
fboHdrMipBlur.Bind();
fboHdrMipBlur.DetachDepth(); //kako se nebi prebrisao sa quadom
gl.viewport(0, 0, fboHdrMipBlur.width, fboHdrMipBlur.height);
gl.clearColor(0.5, 0.5, 0.5, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
fboHdrMipBlur.ActivateDrawBuffers(deferred_opaque_shader);
deferred_opaque_shader.Bind();
// txfbColor.Bind(0, deferred_opaque_shader.ULTextureD);
quad_model.BindTexturesToShader(deferred_opaque_shader);
deferred_opaque_shader.setViewMatrixUniform( IdentityMatrix );
deferred_opaque_shader.setProjectionMatrixUniform( IdentityMatrix );
deferred_opaque_shader.setTimeUniform(time);
deferred_opaque_shader.setCameraPositionUniform(Camera.Position);
deferred_opaque_shader.setFloat3Uniform(deferred_opaque_shader.ULCameraForwardDir, Camera.ForwardDir);
deferred_opaque_shader.setFloat3Uniform(deferred_opaque_shader.ULCameraRightDir, Camera.RightDir);
deferred_opaque_shader.setFloat3Uniform(deferred_opaque_shader.ULCameraUpDir, Camera.UpDir);
deferred_opaque_shader.setFloatUniform(deferred_opaque_shader.ULAspect, Camera.PixelAspect);
deferred_opaque_shader.setFloatUniform(deferred_opaque_shader.ULFOV, vMath.deg2rad(Camera.FOV));
deferred_opaque_shader.setMatrix4Uniform(deferred_opaque_shader.ULInvViewProjMatrix, Camera.InverseViewProjectionMatrix);
// light.UploadToShader(deferred_opaque_shader, lightUniforms_backbuffer_shader);
quad_model.RenderIndexedTriangles(deferred_opaque_shader);
fboHdrMipBlur.AttachDepth(txfbDepth); //reatachamo "spaseni" depth
//atmosphere render
//-------------------------------------------------------------------------------------
// light.UploadToShader(atmosphere_shader, atmosphere_shader.lightUniforms);
// glext.CBlendMode.Bind(glext.CBlendMode.Additive);
glext.CBlendMode.Bind(glext.CBlendMode.Alpha);
RenderModels(fboHdrMipBlur, false, time, Camera, planet.models, "transparent_blend");
glext.CBlendMode.Bind(null);
//render volumetric fog shadowsa
//-------------------------------------------------------------------------------------
/*fboVFogShadows.Bind();
gl.viewport(0, 0, fboVFogShadows.width, fboVFogShadows.height);
gl.clearColor(0.5, 0.5, 0.5, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
volumetric_fog_shadows_shader.Bind();
txfbDepth.Bind(0, volumetric_fog_shadows_shader.ULDepthTexture);
volumetric_fog_shadows_shader.setViewMatrixUniform( IdentityMatrix );
volumetric_fog_shadows_shader.setProjectionMatrixUniform( IdentityMatrix );
volumetric_fog_shadows_shader.setFloat4Uniform( volumetric_fog_shadows_shader.ULCenterPoint, lightPosScreenSpace );
volumetric_fog_shadows_shader.setTimeUniform(time);
quad_model.RenderIndexedTriangles(volumetric_fog_shadows_shader);*/
glext.CFramebuffer.BindMainFB();
//-------------------------------------------------------------------------------------
//kopiranje iz mip blur u main color buffer
//-------------------------------------------------------------------------------------
glext.CFramebuffer.CopyTextureFromFBColorAttachment(txfbHdrMipBlur, 0, txfbColor, 0, MipGen.framebuffer, true);
//gen mipmapa za blured glow
//-------------------------------------------------------------------------------------
glext.CFramebuffer.CopyTextureFromFBColorAttachment(txfbHdrMipBlur2, 0, txfbAoRSMt, 0, MipGen.framebuffer, true);
MipGen.Generate(txfbHdrMipBlur2);
//integriranje blured glowa u main txfbHdrMipBlur
//-------------------------------------------------------------------------------------
fboGlowIntegrate.Bind();
gl.viewport(0, 0, fboGlowIntegrate.width, fboGlowIntegrate.height);
gl.clearColor(0.5, 0.5, 0.5, 1.0);
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
fboGlowIntegrate.ActivateDrawBuffers(glow_integrate_shader);
glow_integrate_shader.Bind();
quad_model.BindTexturesToShader(glow_integrate_shader);
txfbHdrMipBlur.Bind(0, glow_integrate_shader.ULColor);
txfbHdrMipBlur2.Bind(1, glow_integrate_shader.ULGlow);
// txfbVFogShadows.Bind(2, glow_integrate_shader.ULVFogShadows);
glow_integrate_shader.setViewMatrixUniform( IdentityMatrix );
glow_integrate_shader.setProjectionMatrixUniform( IdentityMatrix );
glow_integrate_shader.setTimeUniform(time);
glow_integrate_shader.setCameraPositionUniform(Camera.Position);
glow_integrate_shader.setFloat3Uniform(glow_integrate_shader.ULCameraForwardDir, Camera.ForwardDir);
glow_integrate_shader.setFloat3Uniform(glow_integrate_shader.ULCameraRightDir, Camera.RightDir);
glow_integrate_shader.setFloat3Uniform(glow_integrate_shader.ULCameraUpDir, Camera.UpDir);
glow_integrate_shader.setFloatUniform(glow_integrate_shader.ULAspect, Camera.PixelAspect);
glow_integrate_shader.setFloatUniform(glow_integrate_shader.ULFOV, vMath.deg2rad(Camera.FOV));
glow_integrate_shader.setMatrix4Uniform(glow_integrate_shader.ULInvViewProjMatrix, Camera.InverseViewProjectionMatrix);
quad_model.RenderIndexedTriangles(glow_integrate_shader);
glext.CFramebuffer.BindMainFB();
//-------------------------------------------------------------------------------------
//gen mipmapa za renderirani color buffer
//-------------------------------------------------------------------------------------
MipGen.Generate(txfbHdrMipBlur);
//rendanje transparentnih modela
//-------------------------------------------------------------------------------------
gl.viewport(0, 0, txfbColor.width, txfbColor.height);
fboTransparent.Bind();
// fbo.AttachTexture(txfbColor, 0);
// RenderModels(fboTransparent, false, time, Camera, [navigatorModel]);
RenderModels(fboTransparent, false, time, Camera, dderidex.models);
//render to main FB, sa shaderom koji prikazuje mipove.
//-------------------------------------------------------------------------------------
glext.CFramebuffer.BindMainFB();
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
backbuffer_shader.Bind();
// guad_model.BindTexturesToShader(backbuffer_shader);
txfbColor.Bind(0, backbuffer_shader.ULTextureD);
backbuffer_shader.setViewMatrixUniform( IdentityMatrix );
backbuffer_shader.setProjectionMatrixUniform( IdentityMatrix );
backbuffer_shader.setTimeUniform(time);
backbuffer_shader.setCameraPositionUniform(Camera.Position);
quad_model.RenderIndexedTriangles(backbuffer_shader);
sys.mouse.Update();
sys.keyboard.Update();
gl.flush();
gs.Update();
}
return; /* */
}
function RenderModels(fbo, bClearFBO, time, camera, models, renderpass){
if(fbo != null){
fbo.Bind();
gl.viewport(0, 0, fbo.width, fbo.height);
}
if(renderpass === undefined) renderpass = "-";
if(bClearFBO == true){ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);}
for(var m = 0; m < models.length; ++m){
var model = models[m];
if(model.getRenderpass() != renderpass) continue;
var shader = glext.CShaderList.get(model.shaderID);
if(fbo != null) fbo.ActivateDrawBuffers(shader);
shader.Bind();
model.BindTexturesToShader(shader);
shader.setViewMatrixUniform( camera.ViewMatrix );
shader.setProjectionMatrixUniform( camera.ProjectionMatrix );
shader.setCameraPositionUniform(camera.Position);
shader.setTimeUniform(time);
model.RenderIndexedTriangles(shader);
}
}
function UpdateCamera(Camera, CenterCamera, orbital, mode){
//Calc camera view i proj
//-------------------------------------------------------------------------------------
let bUpdateCamera = false;
let mousePos = sys.mouse.getPosition();
let mouseDelta = sys.mouse.getDeltaPosition();
let moveDir = [0.0,0.0,0.0];
let tilt = 0.0;
orbital.dinclination = 0.0;
orbital.dazimuth = 0.0;
if(sys.mouse.get().btnLeft == true)
{
if(mouseDelta[0] != 0 || mouseDelta[1] != 0)
{
orbital.dazimuth = -mouseDelta[0];
orbital.dinclination = mouseDelta[1];
bUpdateCamera = true;
}
}
if(sys.mouse.get().dz != 0)
{
orbital.radius = orbital.radius - orbital.radius*(sys.mouse.get().dz / 20.0);
if(orbital.radius < 0.1) orbital.radius = 0.1;
if(orbital.radius > 100.0) orbital.radius = 100.0;
bUpdateCamera = true;
}
if(sys.keyboard.isKeyPressed("w") != false){
vMath.vec3.scaleAndAdd(moveDir, moveDir, Camera.ForwardDir, 1.0/orbital.radius); bUpdateCamera = true; }
if(sys.keyboard.isKeyPressed("s") != false){
vMath.vec3.scaleAndAdd(moveDir, moveDir, Camera.ForwardDir, -1.0/orbital.radius); bUpdateCamera = true; }
if(sys.keyboard.isKeyPressed("a") != false){
vMath.vec3.scaleAndAdd(moveDir, moveDir, Camera.RightDir, -1.0/orbital.radius); bUpdateCamera = true; }
if(sys.keyboard.isKeyPressed("d") != false){
vMath.vec3.scaleAndAdd(moveDir, moveDir, Camera.RightDir, 1.0/orbital.radius); bUpdateCamera = true; }
if(sys.keyboard.isKeyPressed("f") != false){
vMath.vec3.scaleAndAdd(moveDir, moveDir, Camera.UpDir, -1.0/orbital.radius); bUpdateCamera = true; }
if(sys.keyboard.isKeyPressed("r") != false){
vMath.vec3.scaleAndAdd(moveDir, moveDir, Camera.UpDir, 1.0/orbital.radius); bUpdateCamera = true; }
if(sys.keyboard.isKeyPressed("q") != false){
tilt += -0.25/orbital.radius; bUpdateCamera = true; }
if(sys.keyboard.isKeyPressed("e") != false){
tilt += 0.25/orbital.radius; bUpdateCamera = true; }
if(mode == "orbital"){
if(bUpdateCamera == true)
{
let RightAdd = vMath.vec3.create();
let UpAdd = vMath.vec3.create();
let sinA = Math.sin(vMath.deg2rad(orbital.dazimuth)); let sinI = Math.sin(vMath.deg2rad(orbital.dinclination));
vMath.vec3.scale(RightAdd, Camera.RightDir, orbital.radius * sinA);
vMath.vec3.scale(UpAdd, Camera.UpDir, orbital.radius * sinI);
vMath.vec3.add(Camera.Position, Camera.Position, RightAdd);
vMath.vec3.add(Camera.Position, Camera.Position, UpAdd);
vMath.vec3.normalize(Camera.Position, Camera.Position);
vMath.vec3.scale(Camera.Position, Camera.Position, orbital.radius);
Camera.setPositionAndLookPt(Camera.Position, [0.0,0.0,0.0], Camera.UpDir);
Camera.CalcInverseViewProjectionMatrix();
vMath.mat4.copy(CenterCamera.ViewMatrix, Camera.ViewMatrix);
vMath.mat4.setTranslation(CenterCamera.ViewMatrix, CenterCamera.ViewMatrix, [0.0,0.0,0.0]);
}
}
else if(mode == "move"){
if(bUpdateCamera == true)
{
vMath.vec3.add(Camera.Position, Camera.Position, moveDir);
let RightAdd = vMath.vec3.create();
let UpAdd = vMath.vec3.create();
let sinA = -Math.sin(vMath.deg2rad(orbital.dazimuth)); let sinI = -Math.sin(vMath.deg2rad(orbital.dinclination));
Camera.Rotate(0.1*sinA, 0.1*sinI);
Camera.Tilt(0.1*tilt);
Camera.UpdateViewMatrix();
Camera.CalcInverseViewProjectionMatrix();
vMath.mat4.copy(CenterCamera.ViewMatrix, Camera.ViewMatrix);
vMath.mat4.setTranslation(CenterCamera.ViewMatrix, CenterCamera.ViewMatrix, [0.0,0.0,0.0]);
}
}
/*
if(sys.mouse.get().btnLeft == true)
if(sys.mouse.get().dx != 0 || sys.mouse.get().dy != 0){
Camera.Rotate(sys.mouse.get().dx / 100.0, sys.mouse.get().dy / 100.0);
Camera.CalcInverseViewProjectionMatrix();
}
*/
//-------------------------------------------------------------------------------------
}
export function recompileShader(fragment_name){
if(gl == null) return;
for(var i = 0; i < glext.CShaderList.count(); ++i)
{
var shader = glext.CShaderList.get(i);
if(shader.FragmentShaderName == fragment_name)
{
shader.Recompile();
shader.InitDefaultAttribLocations();
shader.InitDefaultUniformLocations();
switch(fragment_name){
case "transparent_shader":
shader.ULTextureAmb = shader.getUniformLocation("txAmbient");
shader.ULTextureBackground = shader.getUniformLocation("txBackground");
glext.CLightList.get(0).AttachUniformBlockTo(shader);
break;
case "atmosphere_shader":
shader.ULTextureAmb = shader.getUniformLocation("txAtmosphereGradient");
glext.CLightList.get(0).AttachUniformBlockTo(shader);
break;
case "deferred_opaque_shader":
shader.ULInvViewProjMatrix = shader.getUniformLocation("InverseViewProjectionMatrix");
shader.ULCameraForwardDir = shader.getUniformLocation("CameraForwardDir");
shader.ULCameraRightDir = shader.getUniformLocation("CameraRightDir");
shader.ULCameraUpDir = shader.getUniformLocation("CameraUpDir");
shader.ULAspect = shader.getUniformLocation("Aspect");
shader.ULFOV = shader.getUniformLocation("FOV");
glext.CLightList.get(0).AttachUniformBlockTo(shader);
break;
case "glow_integrate_shader":
shader.ULInvViewProjMatrix = shader.getUniformLocation("InverseViewProjectionMatrix");
shader.ULCameraForwardDir = shader.getUniformLocation("CameraForwardDir");
shader.ULCameraRightDir = shader.getUniformLocation("CameraRightDir");
shader.ULCameraUpDir = shader.getUniformLocation("CameraUpDir");
shader.ULColor = shader.getUniformLocation("txColor");
shader.ULGlow = shader.getUniformLocation("txGlow");
shader.ULAspect = shader.getUniformLocation("Aspect");
shader.ULFOV = shader.getUniformLocation("FOV");
shader.ULVFogShadows = shader.getUniformLocation("txVFogShadows");
break;
case "volumetric_fog_shadows_shader":
// shader.ULInvViewProjMatrix = shader.getUniformLocation("InverseViewProjectionMatrix");
// shader.ULCameraForwardDir = shader.getUniformLocation("CameraForwardDir");
// shader.ULCameraRightDir = shader.getUniformLocation("CameraRightDir");
// shader.ULCameraUpDir = shader.getUniformLocation("CameraUpDir");
// shader.ULColor = shader.getUniformLocation("txColor");
// shader.ULGlow = shader.getUniformLocation("txGlow");
// shader.ULAspect = shader.getUniformLocation("Aspect");
// shader.ULFOV = shader.getUniformLocation("FOV");
shader.ULDepthTexture = shader.getUniformLocation("txDepth");
shader.ULCenterPoint = shader.getUniformLocation("center");
break;
case "deferred_BcNAoRSMt":
shader.ULTextureAmb = shader.getUniformLocation("txAmbient");
break;
case "deferred_planet_BcNAoRSMt":
shader.ULTextureAmb = shader.getUniformLocation("txAmbient");
shader.setDefaultTextureUniformLocations("txHeight","txDiffuseGradient","txAoRSGradient");
shader.setBRDFLUTTextureUniformLocation("txBRDF");
shader.setFlagsUniformLocation("uFlags");
shader.setTimeUniformLocation("Time");
shader.setCameraPositionUniformLocation("CameraPosition");
break;
case "atmosphere_shader":
// shader.lightUniforms = glext.CLight.getUniformLocationsFromShader(shader, "light0");
glext.CLightList.get(0).AttachUniformBlockTo(shader);
break;
default: break;
}
break;
}
}
}
export function reloadTexture(texture_name){
if(gl == null) return;
for(var i = 0; i < glext.CTextureList.count(); ++i)
{
var texture = glext.CTextureList.get(i);
if(texture.name == texture_name){
texture.Reload();
break;
}
}
}
export function constructTextureDOMobj(texture_name){
if(gl == null) return;
let texture = null;
for(var i = 0; i < glext.CTextureList.count(); ++i)
{
var tx = glext.CTextureList.get(i);
if(tx.name == texture_name){
texture = tx;
break;
}
}
if(texture == null) return null;
let obj = document.createElement("IMG");
obj.id = texture_name;
obj.src = texture.src;
obj.style.display = "none";
document.body.appendChild(obj);
return obj;
}
function checkWindowsSizeAndResizeCanvas(){
if(gl == null) return false;
var wOmjer = gl.viewportWidth / window.innerWidth;
var hOmjer = gl.viewportHeight / window.innerHeight;
if(vMath.floatEqual(wOmjer, 1.0, 0.05) == true && vMath.floatEqual(hOmjer, 1.0, 0.05) == true) return false;
glext.ResizeCanvas(window.innerWidth, window.innerHeight);
return true;
}
|
(function(b) {
var e = function() {
return function() {};
}();
b.GameUtil = e;
e.prototype.__class__ = "utils.GameUtil";
b.hitTest = function(b, a) {
var c = b.getBounds(), e = a.getBounds();
c.x = b.x;
c.y = b.y;
e.x = a.x;
e.y = a.y;
return c.intersects(e);
};
b.createBitmapByName = function(b) {
var a = new egret.Bitmap();
b = RES.getRes(b);
a.texture = b;
return a;
};
b.createSpriteByName = function(b) {
var a = new egret.Bitmap();
b = RES.getRes(b);
a.texture = b;
b = new egret.Sprite();
b.addChild(a);
return b;
};
b.createSoundByName = function(b) {
return RES.getRes(b);
};
b.createRectangular = function(b, a, c, e, q, l) {
void 0 === b && (b = 0);
void 0 === a && (a = 0);
void 0 === c && (c = 480);
void 0 === e && (e = 640);
void 0 === q && (q = 1);
void 0 === l && (l = 0);
var f = new egret.Sprite();
f.graphics.beginFill(l, q);
f.graphics.drawRect(b, a, c, e);
f.graphics.endFill();
f.width = c;
f.height = e;
return f;
};
b.createCircle = function(b, a, c, e, q) {
void 0 === b && (b = 0);
void 0 === a && (a = 0);
void 0 === c && (c = 10);
void 0 === e && (e = 1);
void 0 === q && (q = 16777215);
var l = new egret.Sprite();
l.graphics.beginFill(q, e);
l.graphics.drawCircle(b, a, c);
l.graphics.endFill();
return l;
};
b.createTextLabel = function(b, a, c, e, q, l, f, g, h, n, m, p) {
void 0 === a && (a = 0);
void 0 === c && (c = "left");
void 0 === e && (e = "none");
void 0 === q && (q = 14);
void 0 === l && (l = 0);
void 0 === f && (f = 0);
void 0 === g && (g = 0);
void 0 === h && (h = 0);
void 0 === n && (n = 0);
void 0 === m && (m = 0);
void 0 === p && (p = 0);
b = new egret.TextField();
b.textColor = a;
b.textAlign = c;
b.text = e;
b.size = q;
b.fontFamily = "Microsoft Yahei";
0 != l && (b.width = l);
0 != f && 0 != g && (b.strokeColor = f, b.stroke = g);
b.rotation = m;
0 != p && (b.skewX = p);
b.x = h;
b.y = n;
return b;
};
b.hitTestSquare = function(b, a) {
new egret.Point(b.x, b.y);
new egret.Point(a.x, a.y);
};
b.randomInt = function(b, a) {
if (0 >= a - b) return 0;
var c = a - b;
return Math.floor(Math.random() * c) + b;
};
b.createBitmap = function(b, a, c, e) {
void 0 === c && (c = 0);
void 0 === e && (e = 0);
var q = new egret.Bitmap();
q.texture = b.getTexture(a);
q.x = c;
q.y = e;
return q;
};
b.isWeiXin = function() {
return "MicroMessenger" == navigator.userAgent.toString().match(/MicroMessenger/i) ? !0 : !1;
};
})(window.utils || (window.utils = {}));
var __extends = this.__extends || function(b, e) {
function d() {
this.constructor = b;
}
for (var a in e) e.hasOwnProperty(a) && (b[a] = e[a]);
d.prototype = e.prototype;
b.prototype = new d();
},
Settings = function() {
function b() {}
b.StageWidth = 640 ;
b.StageHeight = 1138;
b.frameTime = 60;
b.score = 0;
b.timer = 40;
return b;
}(),
myElement = function(b) {
function e(d) {
b.call(this);
this.id = "";
this.destory = !1;
this.id = d;
var a = new egret.Sprite();
"box1" == d ? a = utils.createSpriteByName("h_box1_png") : "box2" == d ? a = utils.createSpriteByName("h_box2_png") : "box3" == d ? a = utils.createSpriteByName("h_box3_png") : "box4" == d ? a = utils.createSpriteByName("h_box4_png") : "box5" == d ? a = utils.createSpriteByName("h_box5_png") : "box6" == d && (a = utils.createSpriteByName("h_box6_png"));
this.addChild(a);
}
__extends(e, b);
return e;
}(egret.Sprite),
SpriteControl = function(b) {
function e() {
b.call(this);
}
__extends(e, b);
e.loadingInit = function() {
e.GameBg = utils.createBitmapByName("bg_jpg");
e.loadingBool = !0;
};
e.playInit = function() {
e.top_flag = utils.createBitmapByName("game_top_png");
e.playBool = !0;
};
e.loadingBool = !1;
e.playBool = !1;
return e;
}(egret.Sprite),
FloatTxt = function(b) {
function e() {
b.call(this);
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
__extends(e, b);
e.prototype.onAddToStage = function(){
this.floatSpr = new egret.Sprite();
this.addChild(this.floatSpr);
this.floatSpr.alpha = 0;
this.floatSpr.y = Settings.StageHeight - 250;
this.floatSpr.x = Settings.StageWidth / 2;
};
e.prototype.add = function(b, a) {
//void 0 === a && (a = 0);
egret.Tween.removeTweens(this.floatSpr);
this.floatSpr._children = [];
this.floatSpr.scaleX = this.floatSpr.scaleY = 1;
this.floatSpr.alpha = 1;
switch (b) {
case "win":
this.floatSpr.addChild(utils.createBitmapByName("great_png"));
break;
case "lose":
this.floatSpr.addChild(utils.createBitmapByName(a === undefined ? "miss_png" : "wrong_png"));
break;
}
this.floatSpr.anchorX = .5;
this.floatSpr.anchorY = .5;
egret.Tween.get(this.floatSpr).wait(400).to({
scaleX: 2,
scaleY: 2,
alpha: 0
}, 100);
};
return e;
}(egret.Sprite),
MyBox = function(b) {
function e() {
b.call(this);
this.boxArray = [];
}
__extends(e, b);
e.prototype.boxinit = function() {
for (var b = 1; 7 > b; b++) {
var a = utils.createSpriteByName("box" + b.toString() + "_png");
a.name = "box" + b.toString();
this.addChild(a);
this.boxArray.push(a);
}
this.boxArray[0].x = Settings.StageWidth - this.boxArray[0].width;
this.boxArray[0].y = 716;
this.boxArray[1].x = Settings.StageWidth - this.boxArray[1].width;
this.boxArray[1].y = 472;
this.boxArray[2].x = Settings.StageWidth - this.boxArray[2].width;
this.boxArray[2].y = 217;
this.boxArray[3].y = 716;
this.boxArray[4].y = 472;
this.boxArray[5].y = 217;
};
e.prototype.destory = function(b) {
var a = Number(String(b.id).substr(3, 1)) - 1;
var c = this.boxArray[a];
var d = utils.hitTest(b, c);
b.destory = !0;
b.visible = !1;
return d;
};
return e;
}(egret.Sprite),
BitMapText = function(b) {
function e() {
b.call(this);
this._type = "timer";
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
__extends(e, b);
e.prototype.onAddToStage = function(){
};
e.prototype.setText = function(text) {
if( text == null || text == undefined ) return;
var self = this;
var lastNumBitMap;
this._children = [];
text.split("").forEach(function(num){
var numBitMap;
if( num == ":" ){
numBitMap = utils.createBitmapByName("--_png");
} else {
numBitMap = utils.createBitmapByName("g"+num+"_png");
}
if( lastNumBitMap ){
numBitMap.x = lastNumBitMap.x + lastNumBitMap.width + 3;
}
self.addChild(numBitMap);
lastNumBitMap = numBitMap;
});
var suffix = utils.createBitmapByName(this._type == 'timer' ? "miao_png" : "fen_png");
this.addChild(suffix);
suffix.x = lastNumBitMap.x + lastNumBitMap.width + 5;
suffix.y = -3;
};
return e;
}(egret.Sprite),
Score_Time_Plan = function(b) {
function e() {
b.call(this);
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
__extends(e, b);
e.prototype.onAddToStage = function(){
this.scoreTxt = new BitMapText();
this.timeTxt = new BitMapText();
this.scoreTxt._type = "score";
this.scoreTxt.x = 75;
this.scoreTxt._x = this.scoreTxt.x;
this.timeTxt.x = 495;
this.timeTxt.setText(Settings.timer.toString());
this.addChild(this.scoreTxt);
this.addChild(this.timeTxt);
};
e.prototype.setTime = function(b) {
this.timeTxt.setText(b.toString());
};
e.prototype.setScore = function(b) {
Settings.score += b;
this.scoreTxt.x = this.scoreTxt._x -10 * (Settings.score.toString().length - 1);
this.scoreTxt.setText(Settings.score.toString());
};
return e;
}(egret.Sprite),
VIEW_Over = function(b) {
function e() {
b.call(this);
this.hotGameLoaded = !1;
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
__extends(e, b);
e.prototype.onAddToStage = function(){
this.addChild(SpriteControl.leaveButton);
SpriteControl.leaveButton.y = 253;
SpriteControl.leaveButton.x = Settings.StageWidth/2 - SpriteControl.leaveButton.width/2;
this.addChild(SpriteControl.restartButton);
SpriteControl.restartButton.y = 533;
SpriteControl.restartButton.x = Settings.StageWidth/2 - SpriteControl.restartButton.width/2;
SpriteControl.leaveButton.touchEnabled = true;
SpriteControl.restartButton.touchEnabled = true;
SpriteControl.leaveButton.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
alert("have a rest");
}, this);
SpriteControl.restartButton.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
this.parent.removeChild(this);
Game.MainInstance.rStart();
}, this);
};
e.prototype.setScore = function() {
//this.ScoreTxt.text = "您的成绩:" + Settings.score.toString() + "分";
gameResult(Settings.score);
};
return e;
}(egret.Sprite),
Game = function(b) {
function showGameResult(score){
saveResult(score).then(function(data){
if( data.received ){
showRanking(score);
} else {
location.href = data.url;
}
});
}
function saveResult(score){
var defer = $.Deferred();
app.http.post("vivo/score", {
userId: app.getUserId(),
score: score
}).then(function(data){
defer.resolve(data);
}, function(err){
alert("score error:" + err);
defer.reject(err);
});
return defer.promise();
}
function setNumber(el, number ){
var numhtml = "";
number.toString().split("").forEach(function(num){
numhtml += '<b class="n'+ num +'"></b>';
});
$(el).html(numhtml);
}
function showRanking(score){
$("#dialog-rank").show();
app.http.post("vivo/top20", {
userId: app.getUserId()
}).then(function(res){
var rankList = '';
(res.top20||[]).forEach(function(item){
rankList += '<div class="rank-item">' +
'<span class="rank-name">'+ item.nickname +'</span>' +
'<span class="rank-dot"></span>' +
'<span class="rank-num">'+ item.bestScore +'分</span>' +
'</div>';
});
setNumber("#myScore", score);
setNumber("#myRank", res.currentRank);
$("#rank_list").html(rankList);
}, function(err){
alert("topTen error:" + err);
});
}
var __timer = Settings.timer;
function e() {
b.call(this);
this.ScoreTimePlan = new Score_Time_Plan();
this.Box = new MyBox();
this.GameTimeNum = __timer;
this.GameTime = new egret.Timer(1e3);
this.EnterFrameTime = new egret.Timer(1e3 / Settings.frameTime);
this.runTimeNum = 2e3;
this.runTime = new egret.Timer(this.runTimeNum);
this.ElementArr = [];
this.speed = 3;
this.eTarget = null;
this.floatTxt = new FloatTxt();
this.combo = 0;
this.miss = !1;
this._isElementLeft = !0;
Game.MainInstance = this;
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
__extends(e, b);
e.prototype.onAddToStage = function(b) {
var self = this;
this.layer_bg = new egret.Sprite();
this.layer_center = new egret.Sprite();
this.layer_top = new egret.Sprite();
this.addChild(this.layer_bg);
this.addChild(this.layer_center);
this.addChild(this.layer_top);
$(".music-control").on("click", function(e){
var soundObj = self.bgSound;
if( !soundObj ) return;
if( soundObj.audio.paused ){
$(this).removeClass("off");
soundObj.play(-1);
} else {
$(this).addClass("off");
soundObj.pause();
}
});
};
e.prototype.preStart = function(){
//===================
this.layer_top.visible = !1;
this.alphaBg = utils.createBitmapByName("alpha_bg_png");
this.startButton = utils.createBitmapByName("start_button_png");
this.layer_bg.addChild(this.alphaBg);
this.layer_bg.addChild(this.startButton);
this.startButton.x = (Settings.StageWidth - this.startButton.width)/2;
this.startButton.y = (Settings.StageHeight - this.startButton.height)/2;
this.startButton.touchEnabled = true;
this.startButton.addEventListener(egret.TouchEvent.TOUCH_TAP, function(){
app.http.post("vivo/isPlayed", {
userId: app.getUserId()
}).then(function(data){
var _canPlay = typeof data == 'object' ? (data.canPlay == undefined ? true : data.canPlay) : data;
if( _canPlay ) {
this.start();
this.layer_bg.removeChild(this.alphaBg);
this.layer_bg.removeChild(this.startButton);
this.layer_top.visible = !0;
} else {
showShare();
}
}.bind(this), function(err){
alert("isPlayed error:" + err);
});
}, this);
};
e.prototype.readyStart = function(){
this.layer_bg.addChild(SpriteControl.GameBg);
this.layer_top.addChild(SpriteControl.top_flag);
SpriteControl.top_flag.x = 20;
SpriteControl.top_flag.y = 22;
this.layer_top.addChild(this.floatTxt);
this.layer_top.addChild(this.ScoreTimePlan);
this.ScoreTimePlan.y = 60;
this.Box.boxinit();
this.layer_bg.addChild(this.Box);
this.preStart();
};
e.prototype.start = function() {
this.GameTime.addEventListener(egret.TimerEvent.TIMER, this.onGameTime, this);
this.EnterFrameTime.addEventListener(egret.TimerEvent.TIMER, this.onEnterFrameTime, this);
this.runTime.addEventListener(egret.TimerEvent.TIMER, this.onRunTime, this);
this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.myElementTouchMove, this);
this.stage.addEventListener(egret.TouchEvent.TOUCH_END, this.myElementTouchEnd, this);
this.bgSound = utils.createSoundByName("bgSound_mp3");
//this.over_view = new VIEW_Over();
this.play();
};
e.prototype.rStart = function(b) {
this.play();
};
e.prototype.helpTap = function(b) {
this.removeChild(SpriteControl.help_view);
SpriteControl.help_view.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.helpTap, this);
this.play();
};
e.prototype.play = function() {
this.GameTimeNum = __timer;
this.runTime.delay = 2e3;
this.speed = 3;
this.combo = 0;
Settings.score = 0;
this.ScoreTimePlan.setScore(0);
this.GameTime.start();
this.EnterFrameTime.start();
this.runTime.start();
this.miss = !1;
this.bgSound&&this.bgSound.play(-1);
$(".music-control").show();
console.log("<--游戏开始-->");
};
e.prototype.over = function() {
console.log("<--游戏结束-->");
this.GameTime.stop();
this.EnterFrameTime.stop();
this.runTime.stop();
this.destory();
this.bgSound&&this.bgSound.pause();
$(".music-control").hide();
/*if( Settings.score >= Settings.awardScore ){
showGameResult(Settings.score);
} else {
this.addChild(this.over_view);
this.over_view.setScore();
}*/
showGameResult(Settings.score);
this.preStart();
};
e.prototype.destory = function() {
for (var b = this.ElementArr.length - 1; 0 <= b; b--) this.layer_center.removeChild(this.ElementArr[b]),
this.ElementArr[b] = null, this.ElementArr.splice(b, 1);
this.eTarget = null;
};
e.prototype.onGameTime = function(b) {
0 >= this.GameTimeNum ? this.over() : (this.GameTimeNum -= 1, this.ScoreTimePlan.setTime(this.GameTimeNum),
this.runTime.delay -= 45, this.speed += .22);
};
e.prototype.onEnterFrameTime = function(b) {
if (!(0 >= this.ElementArr.length)) for (b = 0; b < this.ElementArr.length; b++) this.ElementArr[b].destory ? (this.layer_center.removeChild(this.ElementArr[b]),
this.ElementArr.splice(b, 1)) : Settings.StageHeight > this.ElementArr[b].y && this.eTarget != this.ElementArr[b] ? this.ElementArr[b].y += this.speed : this.eTarget != this.ElementArr[b] && Settings.StageHeight <= this.ElementArr[b].y && (this.layer_center.removeChild(this.ElementArr[b]),
this.ElementArr.splice(b, 1), this.floatTxt.add("lose"), this.miss = !0, this.combo = 0);
};
e.prototype.onRunTime = function(b) {
b = "box" + (Math.floor(6 * Math.random()) + 1).toString();
b = new myElement(b);
b.x = this._isElementLeft ? Settings.StageWidth/2 - b.width : Settings.StageWidth/2;
b.y = -b.height;
this.layer_center.addChild(b);
b.touchEnabled = !0;
b.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.myElementTouchDown, this);
this.ElementArr.push(b);
this._isElementLeft = !this._isElementLeft;
};
e.prototype.myElementTouchDown = function(b) {
null == this.eTarget && (this.eTarget = b.target);
};
e.prototype.myElementTouchEnd = function(b) {
null != this.eTarget && (b = this.Box.destory(this.eTarget), this.check(b));
console.log("touch_end");
this.eTarget = null;
};
e.prototype.check = function(b) {
b ? (this.combo += 1, b = 2 * this.combo + 1, this.ScoreTimePlan.setScore(b), this.floatTxt.add("win", b),
this.miss = !1) : (this.floatTxt.add("lose", b), this.miss = !0, this.combo = 0);
};
e.prototype.myElementTouchMove = function(b) {
null != this.eTarget && (/*console.log("touchMove_" + Math.floor(65535 * Math.random())), */
this.eTarget.x = b.stageX - this.eTarget.width / 2, this.eTarget.y = b.stageY - this.eTarget.height / 2);
};
return e;
}(egret.DisplayObjectContainer),
UILoading = function(b) {
function e() {
b.call(this);
this.spin = document.querySelector('.loading-spin');
showLoading();
}
__extends(e, b);
e.prototype.loading = function(b, a, c) {
void 0 === a && (a = 0);
void 0 === c && (c = 0);
"start" == b ? (
//this.addChild(SpriteControl.GameBg),
//this.loadingtxt = utils.createTextLabel(this.loadingtxt, 0xffffff, "center", "LOADING... 0%", 32, 0, "",2),
//this.addChild(this.loadingtxt),
//this.loadingtxt.y = Settings.StageHeight/2 - this.loadingtxt.height/2,
//this.loadingtxt.x = (Settings.StageWidth-this.loadingtxt.width)/2
this._startTime = Date.now()
) : "end" == b ? (
//this.removeChild(SpriteControl.GameBg)
hideLoading(),
_hmt&&_hmt.push(['_trackEvent', 'game', 'loadingDuration', '', (Date.now() - this._startTime)/1000]),
console.log("loading duration: " + ((Date.now() - this._startTime)/1000).toString() + "s")
) : "set" == b && (
//this.loadingtxt.text = "正在加载资源:" + a.toString() + "/" + c.toString()
//SpriteControl.GameLoadingBar.width = a/c*320,
//SpriteControl.GameLoadingTxtBG.x = a/c*320 + 30,
//this.loadingtxt.x = a/c*320 + 50,
//this.loadingtxt.text = "LOADING... " + parseInt(a/c*100).toString() + "%"
this.spin.innerHTML = parseInt(a/c*100).toString() + "%"
);
};
return e;
}(egret.Sprite),
UIControl = function(b) {
function e() {
b.call(this);
this.GameLoading = new UILoading();
this.Game = new Game();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
__extends(e, b);
e.prototype.onAddToStage = function(b) {
this.addChild(this.GameLoading);
};
e.prototype.GameStart = function() {
SpriteControl.loadingBool && (this.GameLoading.loading("end"),
this.addChild(this.Game), this.Game.readyStart())
};
e.prototype.showRule = function() {
if( typeof showRule == "undefined" ) return;
showRule();
}
return e;
}(egret.DisplayObjectContainer),
Main = function(b) {
function e() {
b.call(this);
this.GameUI = new UIControl();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
}
__extends(e, b);
e.prototype.onAddToStage = function(b) {
RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
RES.loadConfig("resource/resource.json", "resource/");
};
e.prototype.onConfigComplete = function(b) {
RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
RES.loadGroup("preload", 1);
RES.loadGroup("loading", 2);
};
e.prototype.onResourceLoadComplete = function(b) {
"preload" == b.groupName && (RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this),
RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this),
//this.GameUI.GameLoading.loadingtxt.text = "点击开始游戏",
//this.GameUI.GameLoading.removeChild(this.GameUI.GameLoading.loadingtxt),
SpriteControl.playInit(),
this.GameUI.GameStart()
);
"loading" == b.groupName && (SpriteControl.loadingInit(), this.addChild(this.GameUI),
this.GameUI.GameLoading.loading("start"));
};
e.prototype.onResourceProgress = function(b) {
"preload" == b.groupName && SpriteControl.loadingBool && this.GameUI.GameLoading.loading("set", b.itemsLoaded, b.itemsTotal);
};
return e;
}(egret.DisplayObjectContainer);
|
const { Router } = require('express')
const CategoryController = require('../../controllers/category.controller')
const router = Router()
router.route('/').get(CategoryController.getCategories)
module.exports = router
|
'use strict';
const Shoe = require('../source/shoe');
describe('Shoe object', () => {
it('Can create a new shoe object', () => {
const shoe = new Shoe(0);
expect(shoe).toEqual({
shoe: [],
usedShoe: [],
numberOfDecks: 0,
});
});
it('Can fill the shoe with cards', () => {
const shoe = new Shoe(1);
expect(shoe.shoe.length).toEqual(52);
});
it('Can get one card from the shoe', () => {
const shoe = new Shoe(1);
shoe.getOneCard();
expect(shoe.usedShoe.length).toEqual(1);
expect(shoe.shoe.length).toEqual(51);
});
it('Can refill the shoe when shuffled', () => {
const shoe = new Shoe(1);
shoe.getOneCard();
shoe.getOneCard();
shoe.getOneCard();
expect(shoe.usedShoe.length).toEqual(3);
shoe.refillShoe();
expect(shoe.usedShoe.length).toEqual(0);
});
it('Can re-shuffle when <20% of the deck remains', () => {
const shoe = new Shoe(1);
for (let i = 0; i < 41; i++) {
shoe.getOneCard();
}
shoe.getOneCard();
shoe.getOneCard();
expect(shoe.shoe.length).toEqual(51);
});
});
|
(() => {
//Global Variable Assigning
var mPropertyId;
var mRoomType;
var uiRoomType = {
"SingleBedRoom": "Single Bed Room",
"DoubleBedRoom": "Double Bed Room",
"OneBHKApartment": "One BHK Apartment",
"TwoBHKApartment": "Two BHK Apartment",
"ThreeBHKApartment": "Three BHK Apartment",
};
var amenitiesUiMap = {
"AirConditioning": {
"img": "<i class=\"fas fa-snowflake\"></i>",
"name": "Air Conditioning"
},
"AirportTransfer": {
"img": "<i class=\"fa fa-plane\" aria-hidden=\"true\"></i>",
"name": "Airport Transfer"
},
"Balcony": {
"img": "<i class=\"fas fa-dungeon\"></i>",
"name": "Balcony"
},
"Bathtub": {
"img": "<i class=\"fa fa-bath\" aria-hidden=\"true\"></i>",
"name": "Bathtub"
},
"BusinessFriendly": {
"img": "<i class=\"fa fa-handshake-o\" aria-hidden=\"true\"></i>",
"name": "Business Friendly"
},
"CarPark": {
"img": "<i class=\"fa fa-car\" aria-hidden=\"true\"></i>",
"name": "Car Park"
},
"CoffeeMaker": {
"img": "<i class=\"fa fa-coffee\" aria-hidden=\"true\"></i>",
"name": "Coffee Maker"
},
"DisableFriendly": {
"img": "<i class=\"fas fa-wheelchair\"></i>",
"name": "Disable Friendly"
},
"FrontDesk": {
"img": "<i class=\"fa fa-desktop\" aria-hidden=\"true\"></i>",
"name": "Front Desk"
},
"FullyFurnished": {
"img": "<i class=\"fas fa-couch\"></i>",
"name": "Fully Furnished"
},
"Gym": {
"img": "<i class=\"fas fa-dumbbell\"></i>",
"name": "Gym"
},
"Heating": {
"img": "<i class=\"fas fa-water\"></i>",
"name": "Heater"
},
"Internet": {
"img": "<i class=\"fa fa-wifi\" aria-hidden=\"true\"></i>",
"name": "WiFi"
},
"Kitchen": {
"img": "<i class=\"fas fa-utensils\"></i>",
"name": "Kitchen"
},
"Nightclub": {
"img": "<i class=\"fas fa-glass-cheers\"></i>",
"name": "Nightclub"
},
"NonSmoking": {
"img": "<i class=\"fas fa-smoking-ban\"></i>",
"name": "Non Smoking"
},
"PetsAllowed": {
"img": "<i class=\"fas fa-dog\"></i>",
"name": "Pets Allowed"
},
"PrivatePool": {
"img": "<i class=\"fas fa-swimming-pool\"></i>",
"name": "Private Pool"
},
"Refrigerator": {
"img": "<i class=\"fas fa-door-closed\"></i>",
"name": "Refrigerator"
},
"Restaurant": {
"img": "<i class=\"fas fa-bread-slice\"></i>",
"name": "Restaurant"
},
"Sauna": {
"img": "<i class=\"fas fa-hot-tub\"></i>",
"name": "Sauna"
},
"SemiFurnished": {
"img": "<i class=\"fas fa-chair\"></i>",
"name": "Semi Furnished"
},
"Smoking": {
"img": "<i class=\"fas fa-smoking\"></i>",
"name": "Smoking"
},
"SmokingArea": {
"img": "<i class=\"fas fa-smoking\"></i>",
"name": "Smoking Area"
},
"Spa": {
"img": "<i class=\"fas fa-spa\"></i>",
"name": "Spa"
},
"SwimmingPool": {
"img": "<i class=\"fas fa-swimmer\"></i>",
"name": "Swimming Pool"
},
"TV": {
"img": "<i class=\"fa fa-television\" aria-hidden=\"true\"></i>",
"name": "TV"
},
"Terrace": {
"img": "<i class=\"fas fa-dungeon\"></i>",
"name": "Terrace"
},
"WashingMachine": {
"img": "<i class=\"fas fa-dumpster\"></i>",
"name": "Washing Machine"
}
};
// Do followings, on page load.
$(document).ready(() => {
// Date Picker
$('.t-datepicker').tDatePicker({});
// Based on Screen size
jQuery(document).ready(function ($) {
var alterClass = function () {
var ww = document.body.clientWidth;
if (ww <= 1200) {
$('.PropertySearchResult').addClass('container-fluid');
$('.PropertySearchResult').removeClass('container');
$('#LeftNavFilter').addClass('col-lg-2 col-md-2');
$('#rightpropertySearch').addClass('col-lg-10 col-md-10');
$('#LeftNavFilter').removeClass('col-lg-3 col-md-3');
$('#rightpropertySearch').removeClass('col-lg-9 col-md-9');
}
else if (ww >= 1200) {
$('.PropertySearchResult').addClass('container');
$('.PropertySearchResult').removeClass('container-fluid');
$('#LeftNavFilter').addClass('col-lg-3 col-md-3');
$('#rightpropertySearch').addClass('col-lg-9 col-md-9');
$('#LeftNavFilter').removeClass('col-lg-2 col-md-2');
$('#rightpropertySearch').removeClass('col-lg-10 col-md-10');
};
if (ww <= 1035) {
$('#rightpropertySearch').addClass('col-lg-12 col-md-12');
$('#rightpropertySearch').removeClass('col-lg-10 col-md-10');
}
};
$(window).resize(function () {
alterClass();
});
//Fire it when the page first loads:
alterClass();
});
// Image Light Box
$('#roomThumbnailfetch').simpleLightbox();
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36251023-1']);
_gaq.push(['_setDomainName', 'jqueryscript.net']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
// Get First Property Id
Property.listProperties().done((property) => {
mPropertyId = property[0]._id;
// Fetch Room details
fetchRoomType();
// Fetch property Amenities
fetchamenities();
// Fetch images
fetchimages();
// Fetch Nearby Places
fetchNearbyPlaces();
// Fetch Room Details
fetchRoomDetails();
// Nav Fixed on scrool
// window.onscroll = function () {
// myFunction()
// };
// var header = document.getElementById("fixednav");
// var sticky = header.offsetTop;
// function myFunction() {
// if (window.pageYOffset > sticky) {
// header.classList.add("sticky");
// } else {
// header.classList.remove("sticky");
// }
// }
});
});
// Fetch available room types and show in drop-down
function fetchRoomType() {
var buildingType = 'Hotel';
Meta.getRoomTypes(buildingType).done((rooms) => {
mRoomType = rooms;
var roomTypehtml = mRoomType.reduce((acc, cv) => {
acc += '<option value="' + cv + '">' + uiRoomType[cv] + '</option>';
return acc;
}, '');
$("#roomType").html(roomTypehtml);
});
}
// Fetch property amenities
function fetchamenities() {
Property.getProperty(mPropertyId).done((property) => {
var propertyAmenitiesHtml = '';
var propertyAmenitieslength = property.amenities.length;
var propertyAmenities = property.amenities;
for (i = 0; i <= propertyAmenitieslength - 1; i++) {
propertyAmenitiesHtml += '<div class="col-lg-2 col-md-4 col-sm-6 col-">' +
'<p class="icon-hover">' + amenitiesUiMap[propertyAmenities[i]].img + ' ' + amenitiesUiMap[propertyAmenities[i]].name + '</p>' +
'</div>';
// '<span style="font-size:13px;padding:5px;">' + amenities[amenityIndex].img + ' ' + amenities[amenityIndex].name + '</span>';
$("#AmenitiesData").html(propertyAmenitiesHtml);
}
});
}
// Fetch Iamges
function fetchimages() {
Property.getProperty(mPropertyId).done((property) => {
createpropertyEntry(property);
});
}
//Fetch Property images, name, and address.
function createpropertyEntry(propertydata) {
// Fetch address in navigation
$('#PropertyAddress').html('<li>' + propertydata.address.line1 + '<br>' + propertydata.address.line2 + '<br>' +
'<span class="contact">Phone no: +91 ' + propertydata.phonenumber1 + '</span>' +
'</li>');
// fetch search bar propertyname
$('#propertyname').html(propertydata.name);
var propImage = propertydata.images;
var imageUrls = propImage.map(image => 'http://192.168.1.211:3000/facility' + image.url);
// fetch Property first images
var propertyfirstimageHtml =
'<img src=\"' + imageUrls[0] + '\" alt="test" height="350px" width="100%" id="sameheight">' +
'<div class="carousel-caption">' +
'<div class="row">' +
'<div class="col-md-12" style="background: rgba(0, 0, 0, 0.5);border-radius:5px;padding:5px;">' +
'<ul id="list-line-height" style="list-style-type:none; margin: 0;padding: 0;overflow: hidden;text-align:left;">' +
'<li style="float: left;display: block;padding-right:20px;">' +
'<p style="border-radius: 3px;background-color:#f05700;padding: 2px 10px;color:#fff;">Exceptional price for this location</p>' +
'</li>' +
'<li style="float: left;display: block;">' +
'<p style="border-radius: 3px;background-color:green;padding: 2px 10px;color:#fff;">Free Wi-fi</p>' +
'</li>' +
'</ul>' +
'<ul id="list-line-height" style="list-style-type:none; margin: 0;padding: 0;overflow: hidden;text-align:left;">' +
'<li style="display: inline-block;padding-right:20px;">' +
'<p style="color:#fff;font-size: 16px;">' +
'<i class="fab fa-pagelines fa-flip-horizontal"></i> <b>Favorite choice for travelers!</b> <i class="fab fa-pagelines"></i>' +
'</p>' +
'</li>' +
'<li style="display: inline-block;">' +
'<p style="color:#fff;font-size: 22px;"><b>' + propertydata.name + '</b> <i class="fas fa-star"></i> <i class="fas fa-star"></i> ' +
'<i class="fas fa-star"></i> <i class="fas fa-star"></i>' +
'</p>' +
'</li>' +
'</ul>' +
'<p id="list-line-height" style="color:#fff;text-align:left;margin-bottom:0;">' + propertydata.address.line1 + ', ' + propertydata.address.line2 + '</p>' +
'</div>' +
'</div>' +
'</div>';
$('#propertyFirstImage').html(propertyfirstimageHtml);
// fetch Property Second images
var propertySecondImageHtml =
'<img src=\"' + imageUrls[1] + '\" alt="test" height="350px" width="100%" id="sameheight">';
// '<div class="carousel-caption">' +
// '<div class="row">' +
// '<div class="col-md-3 col-sm-3" style="background: #fff;padding:0;width:92px;">' +
// '<div id="price" style="color:#000;font-size:14px;text-align:center;" >' +
// '<span style="float:right;margin-right:10px;">from</span>' +
// '<p style="color:#EE595D;font-size:18px;margin-bottom:0px;"><b>Rs.1,814</b></p>' +
// '</div>' +
// '</div>' +
// '<div class="col-md-3 col-sm-3" style="background:#ee595d;padding:0px;width:92px;">' +
// '<div id="discount" style="color:white;font-size:14px;text-align:center;">' +
// '<span style="font-size:18px;"><b>21%</b></span>' +
// '<p style="margin-bottom:0px;">Discount</p>' +
// '</div>' +
// '</div>' +
// '</div>' +
// '</div>';
$('#propertySecondImage').html(propertySecondImageHtml);
//fetch Room Thumbnail Images
var propRoomImage = propertydata.rooms;
var roomthumbnailHtml = '';
for (roomindex in propRoomImage) {
var propRoom = propertydata.rooms[roomindex].images;
var imageUrls = propRoom.map(image => 'http://192.168.1.211:3000/facility/room' + image.url);
var propImage = propertydata.images;
for (roomImage in propRoom) {
roomthumbnailHtml +=
'<div class="col-md-2">' +
'<a href="' + imageUrls[roomImage] + '" rel="lightbox">' +
'<img src=' + `data:image/jpg;base64,${propRoom[roomImage].thumbnail}` + ' id="smallimage" class="img-responsive">' +
'</a>' +
// '<img src=' + `data:image/jpg;base64,${propRoom[roomImage].thumbnail}` + ' alt="test" id="smallimage" style="width: 150px; height: 90px;" >' +
'</div>';
}
}
$('#roomThumbnailfetch').html(roomthumbnailHtml);
}
// Fetch Nearby
function fetchNearbyPlaces() {
Property.getProperty(mPropertyId).done((property) => {
var propetyNearbyHtml = '';
var propertyNearby = property.nearby;
propertyNearby.sort(function (a, b) {
return a.distanceinmeters - b.distanceinmeters;
});
for (x in propertyNearby) {
propetyNearbyHtml +=
'<tr>' +
'<td>' + propertyNearby[x].name + '</td>' +
'<td>' + propertyNearby[x].distanceinmeters + ' m</td>' +
'</tr>';
}
$('#NearbyFetch').html(propetyNearbyHtml);
});
}
// Fetch Room
function fetchRoomDetails() {
Property.getProperty(mPropertyId).done((property) => {
var propetyRoomHtml = '';
var propertyroom = property.rooms;
for (roomIndex in property.rooms) {
propetyRoomHtml += createRoomEntry(property.rooms[roomIndex]);
}
$('#roomTable').html(propetyRoomHtml);
});
}
function createImageWidget(images) {
var imageUrls = images.map(image => 'http://192.168.1.211:3000/facility/room' + image.url);
var html = '<div class="col-lg-12 col-md-12">' +
'<img id="myImg" src=\"' + imageUrls[0] + '\" alt="" style="width:100%;height: auto;">' +
'<div class="row no-gutters">' +
'<div class="col-lg-6 col-md-6 col-sm-6">' +
'<div class="img-container">' +
'<img class="img-to-fit" src=\"' + imageUrls[1] + '\" />' +
'</div>' +
'</div>' +
'<div class="col-lg-6 col-md-6 col-sm-6">' +
'<div class="img-container">' +
'<img class="img-to-fit" src=\"' + imageUrls[2] + '\" />' +
'</div>' +
'</div>' +
'</div>' +
'</div><hr>' +
'</div>';
return html;
}
function creationRoomWidgetHeader(roomName) {
var html = '<div class="col-xl-12 col-lg-12 col-md-12 bg-light" style="overflow:hidden;clear:both;border:1px solid #CFCDCE;border-radius:10px;padding:10px;background:#E5E5E5;margin-bottom:20px;">' +
'<div class="row">' +
'<div class="col-xl-2 col-lg-2 col-md-3">' +
'<h6 class="align-middle" style="font-size: 16px;font-weight:600;">' + roomName + '</h6>' +
'</div>' +
'<div class="col-xl-2 col-lg-2 col-md-3">' +
'<ul class="list-group" style="color:#000;">' +
'<li>' +
'<a><i class="fa fa-shower"> Shower</i></a>' +
'</li>' +
'<li>' +
'<a> <i class="fa fa-ban"> Non-Smoking</i></a>' +
'</li>' +
'</ul>' +
'</div>' +
'<div class="col-xl-2 col-lg-2 col-md-3">' +
'<ul class="list-group">' +
'<li>' +
'<a> <i class="fa fa-home" aria-hidden="true"> Room Size</i></a>' +
'</li>' +
'<li>' +
'<a> <i class="fa fa-building-o" aria-hidden="true"> City View</i></a>' +
'</li>' +
'</ul>' +
'</div>' +
'</div>' +
'<div class="row" style="border:1px solid #BBBBBB;">' +
'</div></br>' +
'<div class="row no-gutters">' +
'<div class="col-lg-3 col-md-3">';
return html;
}
function createRoomWidgetFooter(price) {
return '<div class="col-xl-9 col-lg-9 col-md-9">' +
'<table class="table table-borderless" cellspacing="0" cellpadding="0">' +
'<thead>' +
'<tr>' +
'<th>Benefits</th>' +
'<th>Sleeps</th>' +
'<th>Price Per Night</th>' +
'<th>Rooms</th>' +
'<th>Most Booked</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'<tr>' +
'<td style="width:30%;height=300px">' +
'<div id="benefits">' +
'<p style="font-size:14px;">Your Price Includes:</p>' +
'<p style = "font-size:14px;"> <i class = "fa fa-check" style = " color:green;" > </i> Free cancellation</p>' +
'<p style = "font-size:14px;"> <i class = "fa fa-check" style = " color:green;" > </i> Pay nothing until</p>' +
'<p style = "font-size:14px;"> <i class = "fa fa-check" style = " color:green;" > </i> Extra low price! (non-refundable)</p>' +
'</div>' +
'</td>' +
'<td height="300">' +
'<i class="fa fa-plus" aria-hidden="true" style="font-size:12px;float:right" ></i>' +
'<div>' +
'<i class="fa fa-male" style="font-size:16px;"></i></i>' +
'<i class="fa fa-female" style="font-size:16px;"></i>' +
'<i class="fa fa-child"style="font-size:14px;"></i>' +
'<i class="fa fa-child"style="font-size:14px;"></i>' +
'</div>' +
'<h6 style = "font-size:14px;"> 2 kids under 8 years stay <span style = "color:green"> FREE! </span></h6>' +
'</td>' +
'<td height="300">' +
'<div>' +
'<span class="badge badge-danger">SAVE 21% TODAY!</span>' +
'<span class = "badge badge-danger" > <i class = "fa fa-tag" aria - hidden = "true"> </i> Last minute price drop!</span>' +
'</div>' +
'</br>' +
'<div style="float:right">' +
'<div>' +
'<h5 style="font-size:17px;font-weight:600;"><s>Rs.4,843</s></h5>' +
'<h4 style="font-size:18px;font-weight:600;color:#DC3545">Rs. ' + price + '</h4>' +
'</div>' +
'</div>' +
'</td>' +
'<td height="300">' +
'<select class="form-control form-control-sm">' +
'<option selected>1</option>' +
'<option>2</option>' +
'<option>3</option>' +
'<option>4</option>' +
'</select>' +
'</td>' +
'<td style="border-right:none; height=300px">' +
'<div>' +
'<span class="badge badge-warning">Lowest Price Available!</span>' +
'</div>' +
'</br>' +
'<div>' +
'<a href="RoomBooking.html"><button type="button" class="btn btn-primary btn-lg">Book now <br>PAY LATER</br></button></a>' +
'</div>' +
'<div>' +
'<span class="tooltip">RISK FREE!</br>No Cancellation fee</span>' +
'</div>' +
'<div>' +
'<h6 style = "font-size:12px;"> This is a popular choice! </br> <span style = "color:green"> Limited availability</span></h6>' +
'</div>' +
'</td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'</div>' +
'</div>' +
'</div>';
}
// creats a single room entry
function createRoomEntry(room) {
var roomHtml = creationRoomWidgetHeader(room.name);
roomHtml += createImageWidget(room.images);
roomHtml += createRoomWidgetFooter(room.price);
// create room HTML
return roomHtml;
}
})();
|
var forms = require('forms')
var formFunctions = require('../../functions/forms/file');
var settings = require("../../models/settings")
const fileManager = require("../../models/fileManager");
exports.newsletter = async (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
//get uploaded file by admin
const files = { "": "" }
await fileManager.findAll(req, { "column": "path", "like": "image" }).then(result => {
result.forEach(res => {
let url = res.path.split(/(\\|\/)/g).pop()
files[res.path] = res.orgName
});
})
var reg_form = forms.create({
enable_newsletter: fields.string({
choices: { 1: 'Yes', 2: 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Enable Newsletter Functionality",
fieldsetClasses:"form_fieldset",
required: true,
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"enable_newsletter",1)
}),
newsletterlabel: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to create Mailchimp API key.', replace: [{ 0: '<a href="https://login.mailchimp.com/signup/" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
mailchimp_apikey: fields.string({
widget: widgets.text({"classes":["form-control"]}),
label:"Mailchimp API Key",
cssClasses: cssClasses,
value:req.loguserallowed ? "****" : settings.getSetting(req,"mailchimp_apikey",'')
}),
mailchimp_listId: fields.string({
widget: widgets.text({"classes":["form-control"]}),
label:"Mailchimp List ID",
cssClasses: cssClasses,
value:req.loguserallowed ? "****" : settings.getSetting(req,"mailchimp_listId",'')
}),
newsletter_background_image: fields.string({
label: "Newsletter Background Image",
choices: files,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"newsletter_background_image")
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
delete form.data['newsletterlabel']
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/index',{nav:url,reg_form:reg_form,title:"Settings"});
}
});
}
exports.settings = (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
var reg_form = forms.create({
maintanance: fields.string({
choices: { 0: 'Online', 1: 'Offline'},
widget: widgets.select({ "classes": ["select"] }),
label:"Site Mode",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"maintanance",0)
}),
maintanance_code: fields.string({
label : "Password" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"maintanance_code",'we3r')
}),
man_words_label: fields.string({
widget: widgets.label({content : 'Copy the password before putting site in offline mode.' }),
cssClasses:{"field" : ["form-group","form-description"]},
}),
site_title: fields.string({
widget: widgets.text({"classes":["form-control"]}),
label:"Website Title",
cssClasses: cssClasses,
value:settings.getSetting(req,"site_title",' My Community')
}),
censored_words: fields.string({
label : "Censored Words" ,
cssClasses:cssClasses,
widget: widgets.textarea({"classes":["form-control"]}),
value:settings.getSetting(req,"censored_words","")
}),
censored_words_label: fields.string({
widget: widgets.label({content : 'Separate words by commas.' }),
cssClasses:{"field" : ["form-group","form-description"]},
}),
restrict_ips: fields.string({
label : "Ban User with IP" ,
cssClasses:cssClasses,
widget: widgets.textarea({"classes":["form-control"]}),
value:settings.getSetting(req,"restrict_ips","")
}),
restrict_ips_label: fields.string({
widget: widgets.label({content : 'Separate IPs by commas.' }),
cssClasses:{"field" : ["form-group","form-description"]},
}),
google_translateapi_key: fields.string({
label: "Google Language Translate API key.",
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: req.loguserallowed ? "****" : settings.getSetting(req, "google_translateapi_key", '')
}),
googleAPIlabel: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to create Google Translate API key.', replace: [{ 0: '<a href="https://neliosoftware.com/blog/how-to-generate-an-api-key-for-google-translate/" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
image_upload_limit: fields.string({
label: "Maximum Upload Limit of Image. Enter value in MB (Enter 0 for unlimited.)",
validators: [validators.integer('Enter integer value only.')],
cssClasses: { "field": ["form-group"] },
widget: widgets.text({ "classes": ["form-control"] }),
value: settings.getSetting(req, "image_upload_limit", '50')
}),
site_cdn_url: fields.string({
label : "Site CDN URL for external storage",
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value: settings.getSetting(req,"site_cdn_url","")
}),
tinymceKey: fields.string({
label : "TinyMce Editor API key" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"tinymceKey","")
}),
tinymcelabel: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to create new TinyMce Editor API key.', replace: [{ 0: '<a href="https://www.tiny.cloud/auth/signup/" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
google_analytics_code: fields.string({
label : "Google Analytics Code" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"google_analytics_code","")
}),
google_analytics_code_label: fields.string({
widget: formFunctions.makeClickable({content : '[0] to create Google Analytics Profile ID.',replace: [{ 0: '<a href="https://analytics.google.com/analytics/web/" target="_blank">Click here</a>' }]}),
cssClasses:{"field" : ["form-group","form-description"]},
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
delete form.data["maintanance_label"]
delete form.data["maintanance_code_label"]
delete form.data["site_title_label"]
delete form.data["site_description_label"]
delete form.data["site_keywords_label"]
delete form.data["site_cdn_url_label"]
delete form.data["google_analytics_code_label"]
delete form.data['censored_words_label']
delete form.data['tinymcelabel']
delete form.data['restrict_ips_label']
delete form.data['googleAPIlabel']
if(!form.data.maintanance_code){
form.data.maintanance_code = Math.random().toString(36).slice(-5);
}
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/index',{nav:url,reg_form:reg_form,title:"Settings"});
}
});
}
exports.emails = async (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var validators = forms.validators;
var widgets = forms.widgets;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
const files = {"":""}
await fileManager.findAll(req,{"column":"path","like":"image"}).then(result => {
result.forEach(res => {
let url = res.path.split(/(\\|\/)/g).pop()
files[res.path] = res.orgName
});
})
var reg_form = forms.create({
contact_email_from: fields.string({
label:"Contact Form Email",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"contact_email_from",'')
}),
contact_from_name: fields.string({
label : "From Name" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_from_name",'Site Admin')
}),
contact_from_address: fields.string({
label : "From Address" ,
cssClasses:cssClasses,
widget: widgets.email({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_from_address","admin@site.com")
}),
welcome_email: fields.string({
choices: { '1':"Enabled",'0': 'Disabled'},
widget: widgets.select({ "classes": ["select"] }),
label:"Want to send welcome email to new signup users?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"welcome_email",'0')
}),
admin_signup_email: fields.string({
choices: { '1':"Enabled",'0': 'Disabled'},
widget: widgets.select({ "classes": ["select"] }),
label:"Notify Admin by email when user signs up?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"admin_signup_email",'0')
}),
email_logo: fields.string({
label: "Select Logo to send in all Emails",
choices: files,
required:false,
widget: widgets.select({"classes":["select"]}),
cssClasses: {"field" : ["form-group"],label:['select']},
value:settings.getSetting(req,"email_logo","").toString()
}),
email_type: fields.string({
choices: { 'smtp':"SMTP",'gmail': 'Gmail','gmailxauth2':"Gmail Auth2",'sendgrid':"SendGrid"},
widget: widgets.select({ "classes": ["select"] }),
label:"Email Types?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"email_type",'gmail')
}),
gmail_xauth_email: fields.string({
label : "Email Address" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"gmail_xauth_email","")
}),
gmail_xauth_clientid: fields.string({
label : "Client ID" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"gmail_xauth_clientid","")
}),
gmail_xauth_clientsecret: fields.string({
label : "Client Secret" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"gmail_xauth_clientsecret","")
}),
gmail_xauth_refreshtoken: fields.string({
label : "Refresh Token" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"gmail_xauth_refreshtoken","")
}),
sendgrid_username: fields.string({
label : "SendGrid Username" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"sendgrid_username","")
}),
sendgrid_password: fields.string({
label : "SendGrid Password" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"sendgrid_password",'')
}),
email_smtp_host: fields.string({
label : "SMTP Host" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"email_smtp_host","127.0.0.1")
}),
email_smtp_port: fields.string({
label : "SMTP Port" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"email_smtp_port",'25')
}),
email_smtp_username: fields.string({
label : "SMTP Username" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"email_smtp_username","")
}),
email_smtp_password: fields.string({
label : "SMTP Password" ,
cssClasses:cssClasses,
widget: widgets.password({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"email_smtp_password","")
}),
email_smtp_type: fields.string({
choices: { '0':"No",'1': 'Yes'},
widget: widgets.select({ "classes": ["select"] }),
label:"Use Secure Connection?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"email_smtp_type","1")
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
delete form.data["contact_email_from_label"]
delete form.data["contact_from_name_label"]
delete form.data["contact_from_address_label"]
delete form.data["email_smtp_port_label"]
delete form.data['gmailxauth2_label']
if(!form.data.maintanance_code){
form.data.maintanance_code = Math.random().toString(36).slice(-5);
}
if(!form.data['email_smtp_password'])
delete form.data['email_smtp_password']
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/index',{nav:url,reg_form:reg_form,title:"Email Settings"});
}
});
}
exports.login = async (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var widgets = forms.widgets;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
const files = { "": "" }
await fileManager.findAll(req, { "column": "path", "like": "p8" }).then(result => {
result.forEach(res => {
let url = res.path.split(/(\\|\/)/g).pop()
files[res.path] = res.orgName
});
})
var reg_form = forms.create({
social_login_fb: fields.string({
choices: { 1: 'Enabled', 0: 'Disabled'},
widget: widgets.select({ "classes": ["select"] }),
label:"Facebook Login",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"social_login_fb","0")
}),
facebooklabel: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to learn how to create Facebook API key.', replace: [{ 0: '<a href="'+process.env.PUBLIC_URL+'/Documentation/facebook" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
social_login_fb_apiid: fields.string({
label:"Facebook API ID",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"social_login_fb_apiid",'')
}),
social_login_fb_apikey: fields.string({
label : "Facebook App Secret" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"social_login_fb_apikey","")
}),
social_login_google: fields.string({
choices: { 1: 'Enabled', 0: 'Disabled'},
widget: widgets.select({ "classes": ["select"] }),
label:"Google Login",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value: settings.getSetting(req,"social_login_google","0")
}),
googlelabel: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to learn how to create Google API key.', replace: [{ 0: '<a href="'+process.env.PUBLIC_URL+'/Documentation/google" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
social_login_google_apiid: fields.string({
label:"Google client ID",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"social_login_google_apiid",'')
}),
social_login_google_apikey: fields.string({
label : "Google client secret" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"social_login_google_apikey","")
}),
social_login_twitter: fields.string({
choices: { 1: 'Enabled', 0: 'Disabled'},
widget: widgets.select({ "classes": ["select"] }),
label:"Twitter Login",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value: settings.getSetting(req,"social_login_twitter","0")
}),
twitterlabel: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to learn how to create Twitter API key.', replace: [{ 0: '<a href="'+process.env.PUBLIC_URL+'/Documentation/twitter" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
social_login_twitter_apiid: fields.string({
label:"Twitter App Consumer Key",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"social_login_twitter_apiid",'')
}),
social_login_twitter_apikey: fields.string({
label : "Twitter App Consumer Secret" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"social_login_twitter_apikey","")
}),
social_login_apple: fields.string({
choices: { 1: 'Enabled', 0: 'Disabled'},
widget: widgets.select({ "classes": ["select"] }),
label:"Apple Login",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value: settings.getSetting(req,"social_login_apple","0")
}),
applelabel: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to learn how to create Apple API keys.', replace: [{ 0: '<a href="https://github.com/ananay/apple-auth/blob/master/SETUP.md#create-a-new-app-id" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
social_login_apple_p8: fields.string({
label: "Private key",
choices: files,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"social_login_apple_p8")
}),
applep8: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to Download it.', replace: [{ 0: '<a href="https://developer.apple.com/account/resources/authkeys/list" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
social_login_apple_clientid: fields.string({
label:"Apple Client ID",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"social_login_apple_clientid",'')
}),
social_login_apple_teamid: fields.string({
label:"Apple Team ID",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"social_login_apple_teamid",'')
}),
social_login_apple_keyid: fields.string({
label:"Apple Key ID",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"social_login_apple_keyid",'')
})
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
delete form.data['facebooklabel']
delete form.data['googlelabel']
delete form.data['twitterlabel']
delete form.data["applelabel"]
delete form.data["applep8"]
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/index',{nav:url,reg_form:reg_form,title:"Social Login Settings"});
}
});
}
exports.pwa = async (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var widgets = forms.widgets;
var validators = forms.validators;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
const files = { "": "" }
await fileManager.findAll(req, { "column": "path", "like": "image" }).then(result => {
result.forEach(res => {
let url = res.path.split(/(\\|\/)/g).pop()
files[res.path] = res.orgName
});
})
var reg_form = forms.create({
pwa_app_name: fields.string({
label:"App Name",
required: true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"pwa_app_name",'')
}),
pwa_short_name: fields.string({
label:"Short Name",
required: true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"pwa_short_name",'')
}),
pwa_app_description: fields.string({
label:"App Description",
required: true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.textarea({"classes":["form-control"]}),
value:settings.getSetting(req,"pwa_app_description",'')
}),
pwa_app_theme_color: fields.string({
label:"App Theme Color",
required: true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control script_color"]}),
value:settings.getSetting(req,"pwa_app_theme_color",'')
}),
pwa_app_bg_color: fields.string({
label:"App Background Color",
required: true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control script_color"]}),
value:settings.getSetting(req,"pwa_app_bg_color",'')
}),
appicons: fields.string({
widget: formFunctions.makeClickable({ content: '<h2 style="text-align: center;margin: 40px;text-decoration: underline;">App PNG Icons only(* all icons must be of given sizes)</h2>', replace: [] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
pwa_icon_sizes_72: fields.string({
label: "Icon Size 72x72",
choices: files,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"pwa_icon_sizes_72")
}),
pwa_icon_sizes_96: fields.string({
label: "Icon Size 96X96",
choices: files,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"pwa_icon_sizes_96")
}),
pwa_icon_sizes_128: fields.string({
label: "Icon Size 128x128",
choices: files,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"pwa_icon_sizes_128")
}),
pwa_icon_sizes_144: fields.string({
label: "Icon Size 144x144",
choices: files,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"pwa_icon_sizes_144")
}),
pwa_icon_sizes_152: fields.string({
label: "Icon Size 152x152",
choices: files,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"pwa_icon_sizes_152")
}),
pwa_icon_sizes_192: fields.string({
label: "Icon Size 192x192",
choices: files,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"pwa_icon_sizes_192")
}),
pwa_icon_sizes_384: fields.string({
label: "Icon Size 384x384",
choices: files,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"pwa_icon_sizes_384")
}),
pwa_icon_sizes_512: fields.string({
label: "Icon Size 512x512",
choices: files,
required: true,
widget: widgets.select({ "classes": ["select"] }),
cssClasses: { "field": ["form-group"] },
value: settings.getSetting(req,"pwa_icon_sizes_512")
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/pwa',{nav:url,reg_form:reg_form,title:"PWA Settings"});
}
});
}
exports.otp = (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var widgets = forms.widgets;
var validators = forms.validators;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
var reg_form = forms.create({
twillio_enable: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Enable",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"twillio_enable","0")
}),
otplabel: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to create Twillio keys .', replace: [{ 0: '<a href="https://www.twilio.com/referral/hlLIcM" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
twillio_sid: fields.string({
label:"Account SID",
required:true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"twillio_sid",'')
}),
twillio_token: fields.string({
label:"Auth Token",
required:true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"twillio_token",'')
}),
twillio_phone_number: fields.string({
label:"Phone Number",
required:true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"twillio_phone_number",'')
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/index',{nav:url,reg_form:reg_form,title:"OTP Phone Verification"});
}
});
}
exports.recaptcha = (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var widgets = forms.widgets;
var validators = forms.validators;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
var reg_form = forms.create({
recaptcha_enable: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Enable",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"recaptcha_enable","0")
}),
otplabel: fields.string({
widget: formFunctions.makeClickable({ content: '[0] to create reCAPTCHA v3 keys .', replace: [{ 0: '<a href="https://www.google.com/recaptcha/intro/v3.html" target="_blank">Click here</a>' }] }),
cssClasses: { "field": ["form-group", "form-description"] },
}),
recaptcha_enterprise: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Enabling the reCAPTCHA Enterprise",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"recaptcha_enterprise","0")
}),
recaptcha_key: fields.string({
label:"Google reCaptcha Site Key",
required:true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"recaptcha_key",'')
}),
recaptcha_secret_key: fields.string({
label:"Google reCaptcha Secret Key",
required:true,
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"recaptcha_secret_key",'')
}),
recaptcha_login_enable: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Enable on Login Page",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"recaptcha_login_enable","0")
}),
recaptcha_signup_enable: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Enable on Signup Page",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"recaptcha_signup_enable","0")
}),
recaptcha_contactus_enable: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Enable on Contact Us Page",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"recaptcha_contactus_enable","0")
}),
recaptcha_forgotpassword_enable: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Enable on Forgot Password Page",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"recaptcha_forgotpassword_enable","0")
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/index',{nav:url,reg_form:reg_form,title:"Google reCAPTCHA v3 Settings"});
}
});
}
exports.signup = (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var widgets = forms.widgets;
var validators = forms.validators;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
var reg_form = forms.create({
signup_form_lastname: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Do you want to enable Last Name on signup form?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"signup_form_lastname","0")
}),
signup_form_username: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Do you want to enable Username on signup form?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"signup_form_username","0")
}),
signup_form_timezone: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Do you want to enable Timezone on signup form?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"signup_form_timezone","0")
}),
signup_phone_number: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Do you want to enable Phone Number on signup form?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"signup_phone_number","0")
}),
signup_phone_number_required: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Do you want to make Phone Number on signup required?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"signup_phone_number_required","0")
}),
signup_form_gender: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Do you want to enable Gender on signup form?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"signup_form_gender","0")
}),
signup_form_image: fields.string({
choices: { '1': 'Yes', '0': 'No'},
widget: widgets.select({ "classes": ["select"] }),
label:"Do you want to enable Image Upload on signup form?",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"signup_form_image","0")
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/index',{nav:url,reg_form:reg_form,title:"Signup Settings"});
}
});
}
exports.contact = (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var widgets = forms.widgets;
var validators = forms.validators;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
var reg_form = forms.create({
contact_map: fields.string({
label:"Google Map (* leave empty if you don't want to show map)",
cssClasses: {"field" : ["form-group"]},
widget: widgets.textarea({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_map",'')
}),
contact_address: fields.string({
label:"Contact Address.",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_address",'')
}),
contact_phone: fields.string({
label:"Contact Phone Number.",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_phone",'')
}),
contact_fax: fields.string({
label:"Contact Fax Number.",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_fax",'')
}),
contact_email: fields.string({
label:"Contact Email Address.",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_email",'')
}),
contact_facebook_url: fields.string({
label:"Facebook URL",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_facebook_url",'')
}),
contact_twitter_url: fields.string({
label:"Twitter URL",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_twitter_url",'')
}),
contact_whatsapp_url: fields.string({
label:"Whatsapp URL",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_whatsapp_url",'')
}),
contact_linkedin_url: fields.string({
label:"Linkedin URL",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_linkedin_url",'')
}),
contact_pinterest_url: fields.string({
label:"Pinterest URL",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:settings.getSetting(req,"contact_pinterest_url",'')
}),
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/index',{nav:url,reg_form:reg_form,title:"Contact Us Settings"});
}
});
}
exports.s3 = (req,res) => {
const url = req.originalUrl.replace(process.env.ADMIN_SLUG,'');
var fields = forms.fields;
var widgets = forms.widgets;
var cssClasses = {
label :[""],
field : ["form-group"],
classes : ["form-control"]
};
var reg_form = forms.create({
upload_system: fields.string({
choices: { 's3': 'S3 Storage','wisabi': 'Wasabi Storage', '0': 'Local Storage'},
widget: widgets.select({ "classes": ["select"] }),
label:"Storage Type",
fieldsetClasses:"form_fieldset",
cssClasses: {"field" : ["form-group"]},
value:settings.getSetting(req,"upload_system","0")
}),
s3_bucket: fields.string({
label:"Bucket Name",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"s3_bucket",'')
}),
s3_access_key: fields.string({
label : "S3 Key" ,
cssClasses:cssClasses,
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"s3_access_key","")
}),
s3_secret_access_key: fields.string({
label:"S3 Secret Key",
cssClasses: {"field" : ["form-group"]},
widget: widgets.text({"classes":["form-control"]}),
value:req.loguserallowed ? "****" : settings.getSetting(req,"s3_secret_access_key",'')
}),
s3_region: fields.string({
choices: { 'us-east-1': 'US East (N. Virginia)', 'us-west-2': 'US West (Oregon)','ap-northeast-2':'Asia Pacific (Seoul)','ap-south-1':'Asia Pacific (Mumbai)','ap-southeast-1':'Asia Pacific (Singapore)','ap-southeast-2':'Asia Pacific (Sydney)','ap-northeast-1':'Asia Pacific (Tokyo)','eu-central-1':'EU (Frankfurt)','eu-west-1':'EU (Ireland)'},
widget: widgets.select({"classes":["select"]}),
label:"S3 buket Region",
cssClasses: {"field" : ["form-group"],label:['select']},
value:req.loguserallowed ? "****" : settings.getSetting(req,"s3_region","us-east-1")
})
},{validatePastFirstError:true});
reg_form.handle(req, {
success: function (form) {
delete form.data.s3_bucket_name
delete form.data.s3_access_key_name
delete form.data.s3_secret_access_key_name
settings.setSettings(req,form.data)
res.send({success:1,message:"Setting Saved Successfully."})
},
error: function(form){
const errors = formFunctions.formValidations(form);
res.send({errors:errors});
},
other: function (form) {
res.render('admin/settings/index',{nav:url,reg_form:reg_form,title:"Storage Settings"});
}
});
}
|
function createEvent(event, post_id, tz, group_id) {
let event_start = event.start;
let formatted_event_start = moment(event.start).format('Y-MM-DD HH:mm:ss');
$.ajax({
type:"POST",
url:"/calendar/createEvent",
data:{"id":post_id,
"title":event.title,
"start":formatted_event_start,
"fulltext":event.extendedProps.fulltext,
"attachments":event.extendedProps.attachments,
"user_id":user_id,
"attachments_others":event.extendedProps.attachments_others,
"attachments_urls":event.extendedProps.attachments_urls,
"timezone":tz,
"group_id":group_id
},
traditional:true,
success:function(msg){
},
error:function(msg){
console.log(msg);
alert('Ошибка');
}
});
}
function updateEvent(event, tz) {
let event_start = event.start;
let formatted_event_start = moment(event.start).format('Y-MM-DD HH:mm:ss');
$.ajax({
type:"PUT",
url:"/calendar/updateEvent",
data:{"id":event.id,
"start":formatted_event_start,
"timezone":tz
},
traditional:true,
success:function(msg){
},
error:function(msg){
console.log(msg);
alert('Ошибка');
}
});
}
function viewPost(arg) {
window.post_text = $('#post_fulltext_calendar');
window.object_id = arg.event.id;
window.counter = $('#counter');
$.ajax({
type:"GET",
url:"/calendar/viewPostData",
data:{"object_id":object_id},
dataType: "json",
success:function(data){
window.post_pictures = $('#post_pictures_calendar').find('.fs-upload-target');
let start = data.start;
var arr_attachments_urls = data.attachments_urls;
var arr_attachments_others = data.attachments_others;
var arr_attachments = data.attachments;
var link = data.link;
var ad = data.ad;
var sign = data.sign;
var disable_comments = data.disable_comments;
var every = data.every;
var error = data.error;
var options = { "1": true, "0": false };
var time_interval = { day: '1', week: '2', month: '3', year: '4', none: '1'};
var every_option = [{ day: true, week: true, month: true, year: true, none: false}, {day: false, week: false, month: false, year: false, none: true}];
$('#alert').html('');
if(error == 'OK' && error != '') {
$('#alert').html('<div class="alert alert-success" role="alert"><a href="#" class="alert-link">Пост успешно опубликован!</a></div>');
}
if(error != 'OK' && error != '') {
$('#alert').html('<div class="alert alert-danger" role="alert"><a href="#" class="alert-link">' + error + '!</a></div>')
}
$('#link').prop('checked', options[link]);
$('#ad').prop('checked', options[ad]);
$('#sign').prop('checked', options[sign]);
$('#disable_comments').prop('checked', options[disable_comments]);
$('#every').prop('checked', every_option[0][every]);
$('#every_select').prop('disabled', every_option[1][every]);
$("#every_select option[value=" + time_interval[every] + "]").prop('selected', true);
if(arr_attachments_others == ''){
arr_sum = (arr_attachments.slice(0, -1) + arr_attachments_others).split(',');
}else{
arr_sum = (arr_attachments + arr_attachments_others.slice(0, -1)).split(',');
}
if(arr_attachments_others == '' && arr_attachments == ''){
arr_sum = '';
}
window.pic_counter = 10 - arr_sum.length;
counter.html("Можно добавить еще картинок:" + (pic_counter));
arr = [];
for (let i = 0; i < arr_attachments_urls.split(",").length; i++) {
arr.push({ vk: arr_attachments.split(",")[i], url: arr_attachments_urls.split(",")[i] });
}
if(data.text == 'Нет текста'){
data.text = '';
}
post_text.html(data.text + '<br>');
post_pictures.html('');
arr.forEach(makeImage);
function makeImage(item){
if(item.url !== '' && item.vk !== ''){
let pic = "<div class='item' data-url='"+ item.url +",' data-attachment='"+ item.vk +",' data-object_id='"+ object_id +"'><span class='close_pic' onclick='attachementDelete(this)'>×</span><a href='"+ item.url +"' data-lightbox='image-1'><div style='background: url("+ item.url +") #000 no-repeat center;' class='bg-img'></div></a></div>";
post_pictures.append(pic);
}
}
$('#datetimepicker').datetimepicker('destroy');
if(start < moment().format('Y-MM-DD HH:mm:ss')) {
$('#datetimepicker').datetimepicker({
date: start
});
$('#datetimepicker').datetimepicker('disable');
}
else {
$('#datetimepicker').datetimepicker({
format: 'Y-MM-DD HH:mm',
minDate: moment().format('LLLL'),
useCurrent: false,
locale: 'ru',
autoclose: true,
date: start,
locale: 'ru'
});
$('#datetimepicker').datetimepicker('enable');
}
}
});
$('button.fc-addEvent-button').prop('disabled', true);
$('#create').addClass('hide');
$('#update').removeClass('hide');
$('#delete').removeClass('hide');
$('#calendar-events-dialog').dialog('open');
};
function viewCreateDialog() {
window.post_pictures = $('#post_pictures_calendar').find('.fs-upload-target');
window.counter = $('#counter');
counter.html("Можно добавить еще картинок:" + '10');
$('#calendar-events-dialog').dialog('open');
$('#datetimepicker').datetimepicker('destroy');
$('#datetimepicker').datetimepicker({
format: 'Y-MM-DD HH:mm',
minDate: moment().format('LLLL'),
useCurrent: true,
locale: 'ru',
autoclose: true
});
$('#datetimepicker').datetimepicker('enable');
$('#create').removeClass('hide');
$('#update').addClass('hide');
$('#delete').addClass('hide');
}
function createOrUpdate(object_id, group_id) {
var text = $('#post_fulltext_calendar').text();
var items = $('div.item').filter(function() {
return $(this).data('url') !== undefined;
});
var attachments = [];
$(items).each(function() {
attachments.push({ url: $(this).data('url'), attachment: $(this).data('attachment')});
})
var link = '0';
var ad = '0';
var sign = '0';
var disable_comments = '0';
var every = 'none';
var tz = moment.tz.guess(true);
var start = $('#start').val();
let formatted_event_start = moment(start).format('Y-MM-DD HH:mm:ss');
var rename = { 'Каждый день': 'day', 'Каждую неделю': 'week', 'Каждый месяц': 'month', 'Каждый год': 'year'};
if ($('#link').is(':checked')) {
var link = '1';
}
if ($('#ad').is(':checked')) {
var ad = '1';
}
if ($('#sign').is(':checked')) {
var sign = '1';
}
if ($('#disable_comments').is(':checked')) {
var disable_comments = '1';
}
if ($('#every').is(':checked')) {
var every_text = $('#every_select option:selected').text();
var every = rename[every_text];
}
if(object_id != '0') {
var data = {"object_id":object_id, "attachments":attachments, "timezone":tz, "start":formatted_event_start, "text":text, "link":link, "ad":ad, "sign":sign, "disable_comments":disable_comments, "every":every};
}
else {
var data = {"group_id":group_id, "attachments":attachments, "timezone":tz, "start":formatted_event_start, "text":text, "link":link, "ad":ad, "sign":sign, "disable_comments":disable_comments, "every":every};
}
return data;
}
function attachementDelete(item) {
$(item).parent().remove();
attachment = $(item).parent().data('attachment');
url = $(item).parent().data('url');
let items = $('div.item').filter(function() {
return $(this).data('url') !== undefined;
});
counter.html("Можно добавить еще картинок:" + (10 - items.length));
if(items.length == '0') {
$('#post_pictures_calendar div:first').addClass('fs-upload-target');
}
}
function icon(type, el, view){
let icons = { 'waiting' : 'far fa-clock', 'success' : 'fas fa-check', 'fail' : 'fas fa-times' };
if(view !== 'dayGridMonth'){
$(el).find('div.fc-time').append("<span> <i class='" + icons[type] + "'></i></span>");
}
else{
$(el).find('div.fc-content').prepend("<span> <i class='" + icons[type] + "'></i></span>");
}
}
function tooltip(description, type, el) {
if(type == 'fail') {
$(el).attr('data-toggle', 'tooltip').attr('data-placement', 'top').attr('title', description);
$(function() {
$('[data-toggle="tooltip"]').tooltip();
});
}
}
function round(date, duration, method) {
return moment(Math[method]((+date) / (+duration)) * (+duration));
}
function addPicture(url, attachment, object_id, pic_counter) {
const pic = "<div class='item' data-url='"+ url +"' data-attachment='"+ attachment +"' data-object_id='"+ object_id +"'><span class='close_pic' onclick='attachementDelete(this)'>×</span><a href='"+ url +"' data-lightbox='image-1'><div style='background: url("+ url +") #000 no-repeat center;' class='bg-img'></div></a></div>";
post_pictures.append(pic);
let items = $('div.item').filter(function() {
return $(this).data('url') !== undefined;
});
counter.html("Можно добавить еще картинок:" + (10 - items.length));
}
|
//set env variable to test to access the test database
process.env.NODE_ENV = 'test';
const db = require('../../server/models');
// import book model
const Genre = require('../../server/models').Genre;
const Book = require('../../server/models').Book;
const User = require('../../server/models').User;
//import needed data for testing
const genreData = require('../unit/models/test-data').Genres;
const bookData = require('../unit/models/test-data').Books;
//Require the dev-dependencies
let chai = require('chai');
let chaiHttp = require('chai-http');
let app = require('../../app');
let should = chai.should();
chai.use(chaiHttp);
let token, userId;
let agent = chai.request.agent(app);
describe('REGISTER USER', () => {
//create test admin user data to mock admin object
let admin = {
username: 'Daramola',
email: 'tobi_daramola@yahoo.com',
password: 'admin',
confirmPassword: 'admin',
admin: true,
createdAt: new Date(),
updatedAt: new Date()
};
before(function(done) {
this.timeout(20000);
db.sequelize.sync({ force: true, logging: false }).then(() => {
User.create(admin);
Genre.bulkCreate(genreData).then(() => {
Book.bulkCreate(bookData).then((book) => {
if (book) {
done();
}
});
});
});
});
let user = {
username: 'Philip',
email: 'philip2017@gmail.com',
password: 'phil17',
confirmPassword: 'phil17',
createdAt: new Date(),
updatedAt: new Date()
};
it('it should register user', (done) => {
chai.request(app)
.post('/api/v1/users/register')
.send(user)
.end((err, res) => {
res.should.have.status(200);
res.type.should.equal('application/json');
res.body.should.have.all.keys('message', 'user');
res.body['message'].should.equal('Authentication successful');
done();
});
}).timeout(3000);
});
//sign in a user to test the protected routes from seeders entries
describe('USER SHOULD LOGIN TO BORROW BOOK', () => {
it('it should signin user and generate token to access routes', (done) => {
agent.post('/api/v1/users/signin')
.send({ username: 'Philip', password: 'phil17' })
.end((err, res) => {
res.should.have.status(200);
res.body['user'].should.have.property('token').not.be.empty;
token = res.body['user'].token;
// get user id from login
userId = res.body['user'].userId;
done();
});
}).timeout(5000);
});
describe('BORROW AND RETURN BOOKS', () => {
it('it should borrow first book', (done) => {
try {
//User with userId borrows two book with id equals 1 and id equals 2
let bookId = 1;
agent.post('/api/v1/users/' + userId + '/books/' + bookId)
.set({ 'x-access-token': token })
.end((err, res) => {
// it should be successful
res.status.should.equals(201);
res.type.should.equal('application/json');
res.body['message'].should.equals('You have successfully borrowed this book');
res.body['borrowedBook'].should.have.property('returned').to.be.equal(false);
res.body['borrowedBook'].should.have.all.keys('borrowId', 'userId', 'bookId', 'createdAt', 'updatedAt', 'returned');
done();
});
} catch (e) { console.log(e); }
}).timeout(17000);
it('it should borrow second book', (done) => {
try {
//....borrow second book with id equals 2
let bookId = 2;
agent.post('/api/v1/users/' + userId + '/books/' + bookId)
.set({ 'x-access-token': token })
.end((err, res) => {
// it should be successful
res.status.should.equals(201);
res.type.should.equal('application/json');
res.body['borrowedBook'].should.have.property('returned').to.be.equal(false);
res.body['borrowedBook'].bookId.should.equal(2);
res.body['borrowedBook'].should.have.all.keys('borrowId', 'userId', 'bookId', 'createdAt', 'updatedAt', 'returned');
done();
});
} catch (e) { console.log(e); }
}).timeout(17000);
it('it should get unreturned book by a user before return of any', (done) => {
agent.get('/api/v1/users/' + userId + '/books')
.set({ 'x-access-token': token })
.query('returned=false')
.end((err, res) => {
res.should.have.status(200);
should.not.exist(err);
res.type.should.equal('application/json');
res.body.should.be.a('object');
res.body['borrowedBooks'].Books.should.be.a('array');
//Two of the books yet to be returned
res.body['borrowedBooks'].Books.length.should.be.eql(2);
done();
});
});
it('it should return books borrowed by user', (done) => {
//returned properties to true for user to return book
let book = {
returned: true
};
let bookId = 1;
agent.put('/api/v1/users/' + userId + '/books/' + bookId)
.set({ 'x-access-token': token })
.send(book)
.end((err, res) => {
res.should.have.status(200);
should.not.exist(err);
res.type.should.equal('application/json');
res.body.should.be.a('object');
res.body['message'].should.equal('You have succesfully returned this book');
res.body['returnedBook'].should.have.property('returned').to.be.equal(true);
done();
});
});
it('it should get unreturned book by a user', (done) => {
agent.get('/api/v1/users/' + userId + '/books')
.set({ 'x-access-token': token })
.query('returned=false')
.end((err, res) => {
res.should.have.status(200);
should.not.exist(err);
res.type.should.equal('application/json');
res.body.should.be.a('object');
res.body['borrowedBooks'].Books.should.be.a('array');
//one book has been returned from two borrowed
res.body['borrowedBooks'].Books.length.should.be.equal(1);
done();
});
});
});
|
// Particles are statically allocated in a big array so that creating a
// new particle doesn't need to allocate any memory (for speed reasons).
// To create one, call Particle(), which will return one of the elements
// in that array with all values reset to defaults. To change a property
// use the function with the name of that property. Some property functions
// can take two values, which will pick a random number between those numbers.
// Example:
//
// Particle().position(center).color(0.9, 0, 0, 0.5).mixColor(1, 0, 0, 1).gravity(1).triangle()
// Particle().position(center).velocity(velocity).color(0, 0, 0, 1).gravity(0.4, 0.6).circle()
var PE = PE || {};
PE.random = Math.random;
PE.lerp = function (a, b, percent) { return a + (b - a) * percent; }
PE.randInRange = function (a, b) { return PE.lerp(a, b, PE.random()); }
PE.randInt = function (a, b, n) { return PE.lerp(a, b, PE.random()).toFixed(n || 0)*1;}
PE.PI = 3.141592653589793;
PE.PI90 = 1.570796326794896;
PE.PI270 = 4.712388980384689;
PE.TwoPI = 6.283185307179586;
PE.ToRad = 0.0174532925199432957;
PE.ToDeg = 57.295779513082320876;
PE.PARTICLE_CIRCLE = 0;
PE.PARTICLE_TRIANGLE = 1;
PE.PARTICLE_LINE = 2;
PE.PARTICLE_CUSTOM = 3;
// class Particle
PE.ParticleInstance = function () {
}
PE.ParticleInstance.prototype = {
constructor: PE.ParticleInstance,
init : function() {
// must use 'm_' here because many setting functions have the same name as their property
this.m_speed = 0.001;
this.m_time = 0;
this.m_bounces = 0;
this.m_color = new THREE.Vector4();
this.m_type = 0;
this.m_radius = 0;
this.m_radiusBase = 0;
this.m_expand = 1;
this.m_gravity = new THREE.Vector3();
this.m_elasticity = 0;
this.m_decay = 1;
this.m_uvpos = new THREE.Vector2();
this.m_pos = new THREE.Vector3();
this.m_basepos = new THREE.Vector3();
this.m_velocity = new THREE.Vector3();
this.m_angle = 0;
this.m_angularVelocity = 0;
this.m_drawFunc = null;
this.ntiles = 4;
this.m_animuv = false;
},
tick : function(seconds) {
//if(this.m_bounces < 0) return false;
/*if(this.m_animuv){
this.m_uvpos.x ++;
if(this.m_uvpos.x>this.ntiles){
this.m_uvpos.x = 0;
this.m_uvpos.y ++;
if(this.m_uvpos.y>this.ntiles) this.m_uvpos.y = 0;
}
}*/
//this.m_color.w *= Math.pow(this.m_decay, seconds);// alpha
//this.m_radius *= Math.pow(this.m_expand, seconds);
this.m_radius = PE.lerp( this.m_radiusBase, this.m_expand, this.m_time );
//
//if(this.m_gravity.x!==0)this.m_velocity.x -= this.m_gravity.x * seconds;
//if(this.m_gravity.y!==0)this.m_velocity.y -= this.m_gravity.y * seconds;
//if(this.m_gravity.z!==0)this.m_velocity.z -= this.m_gravity.z * seconds;
this.m_velocity.sub(this.m_gravity.clone());
//this.m_pos.add(this.m_velocity.clone().multiplyScalar(seconds));
this.m_pos.lerpVectors( this.m_basepos, this.m_velocity, this.m_time );
//this.m_pos.x += this.m_velocity.x * seconds;
//this.m_pos.y += this.m_velocity.y * seconds;
//this.m_pos.z += this.m_velocity.z * seconds;
//this.m_angle += this.m_angularVelocity * seconds;
//if(this.m_alpha < 0.05) this.m_bounces = -1;
if( this.m_time > 1 ){
this.m_time = -this.m_decay;
//this.m_pos.copy( this.m_basepos );
//this.m_radius= this.m_radiusBase ;
} else {
this.m_time += this.m_speed
}
//this.m_time = 0;
//this.m_pos.copy( this.m_basepos )
//this.m_bounces = -1;
// return false;
//} else {
// return true;
//}
//if(this.m_color.w < 0.05) this.m_bounces = -1;
//return (this.m_bounces >= 0);
return (this.m_time < 1)
//this.m_time
},
randOrTakeFirst : function (min, max) {
return (typeof max !== 'undefined') ? PE.randInRange(min, max) : min;
},
cssRGBA : function (r, g, b, a) {
return 'rgba(' + Math.round(r * 255) + ', ' + Math.round(g * 255) + ', ' + Math.round(b * 255) + ', ' + a + ')';
},
// all of these functions support chaining to fix constructor with 200 arguments
fixangle : function(){
var v1 = this.m_pos;
var v2 = this.m_pos.clone().add(this.m_velocity.clone().multiplyScalar(10));
this.m_angle = -(Math.atan2((v2.y-v1.y) , (v2.x-v1.x))+Math.PI);
return this;
},
bounces : function(min, max) { this.m_bounces = Math.round(this.randOrTakeFirst(min, max)); return this; },
type:function(t) {
var x = 0, y = 0;
switch(t){
case 'R': case 0: x=1; y=1; break;
case 'N': case 1: x=2; y=1; break;
case 'B': case 2: x=3; y=1; break;
//case 'custom': x=6; y=1; break;
}
this.m_uvpos.set(x,y);
return this;
},
setuv:function(x,y){this.m_uvpos.set(x,y); return this;},
animuv: function(){ this.m_animuv=true; return this;},
circle : function() { this.m_type = PE.PARTICLE_CIRCLE; return this; },
triangle : function() { this.m_type = PE.PARTICLE_TRIANGLE; return this; },
line : function() { this.m_type = PE.PARTICLE_LINE; return this; },
custom : function(drawFunc) { this.m_type = PE.PARTICLE_CUSTOM; this.m_drawFunc = drawFunc; return this; },
customSprite : function(sprite) { /*this.m_type = PE.PARTICLE_CUSTOM; this.m_drawFunc = drawFunc; */return this; },
color : function(r, g, b, a) { this.m_color.set(r||0, g||0, b||0, a||0); return this; },
mixColor : function(r, g, b, a) { var percent = Math.random(); this.m_color.lerp(new THREE.Vector4(r, g, b, a), percent); return this; },
radius : function(min, max) { this.m_radius = this.randOrTakeFirst(min, max); this.m_radiusBase = this.m_radius; return this; },
gravity : function(min, max, axe) { this.m_gravity[axe || 'y'] = this.randOrTakeFirst(min, max); return this; },
elasticity : function(min, max) { this.m_elasticity = this.randOrTakeFirst(min, max); return this; },
decay : function(min, max) { this.m_decay = this.randOrTakeFirst(min, max); return this; },
expand : function(min, max) { this.m_expand = this.randOrTakeFirst(min, max); return this; },
angle : function(min, max) { this.m_angle = this.randOrTakeFirst(min, max); return this; },
angularVelocity : function(min, max) { this.m_angularVelocity = this.randOrTakeFirst(min, max); return this; },
speed : function( s ) { this.m_speed = s*0.01; return this; },
position : function(pos) { this.m_pos.set( pos.x || 0, pos.y || 0, pos.z || 0); this.m_basepos.set( pos.x || 0, pos.y || 0, pos.z || 0); return this; },
velocity : function(vel) { this.m_velocity.set( vel.x || 0, vel.y || 0, vel.z || 0); return this; }
};
// wrap in anonymous function for private variables
PE.Particle = ( function() {
var emiters = [];
var particleMaterial = null;
var geometry = null;
var positions = null;
var angles = null;
var sizes = null;
var uvpos = null;
var colors = null;
var values_size = null;
//this.scene.add( this.particlesCloud );
// particles is an array of ParticleInstances where the first count are in use
//var particles = new Array(3000);
var particles = new Array(25000);
var maxCount = particles.length;
var count = 0;
var i = maxCount;
while(i--){
particles[i] = new PE.ParticleInstance();
}
/*for(var i = 0; i < particles.length; i++) {
particles[i] = new PE.ParticleInstance();
}*/
PE.Particle = function() {
var particle = (count < maxCount) ? particles[count++] : particles[maxCount - 1];
particle.init();
return particle;
}
PE.Particle.reset = function() {
count = 0;
var v = 25000;
while(v--){
positions[v*3+0] = 0.0;
positions[v*3+1] = 0.0;
positions[v*3+2] = 0.0;
colors[v*4+3] = 0.0;
}
};
PE.Particle.Emiter = function( pos, r1, r2, d1, d2, s1, s2 ){
this.count = 0;
this.frequency = 10;
this.speed = 0.5;
this.multyply = 1;
this.position = pos || new THREE.Vector3();
this.randBase = 0.5;
this.randEnd = 0.5;
this.angle1 = r1 || 0;
this.angle2 = r2 || 45;
this.distance1 = d1 || 10;
this.distance2 = d2 || 20;
this.size1 = s1 || 0.1;
this.size2 = s2 || 0.5;
emiters.push(this);
};
PE.Particle.Emiter.prototype = {
up:function(){
if(this.frequency === 0) return;
this.count++;
if(this.count < 10 - this.frequency) return;
var i = this.multyply;
while(i--){
var vv = new THREE.Vector3( PE.randInRange( -this.randBase , this.randBase ), PE.randInRange( -this.randBase , this.randBase ), PE.randInRange( -this.randBase , this.randBase ) );
var vv2 = new THREE.Vector3( PE.randInRange( -this.randEnd , this.randEnd ), PE.randInRange( -this.randEnd , this.randEnd ), PE.randInRange( -this.randEnd , this.randEnd ) );
var angle = PE.randInRange( this.angle1 * PE.ToRad , this.angle2 * PE.ToRad );
var distance = PE.randInRange(this.distance1, this.distance2);
var velocity = new THREE.Vector3( Math.cos( angle ), Math.sin( angle ), PE.randInRange(-0.3, 0.3)).multiplyScalar(distance);
var t = PE.randInt(0,2);
PE.Particle()
.type(t)// triangle, circle, line, custom
.position( this.position.clone().add(vv) )
.velocity( velocity.add(vv2) )
.radius( this.size1 )
.expand( this.size2 )
.gravity(0.0)// (min, max, axe) axe:"x", "y", "z"
//.bounces(0, 4)
//.elasticity(0.05, 0.9)
.decay(0.01, 0.5)
.speed(this.speed)
.color(1, 1, 1, 1)
.mixColor(1, 1, 1, 1)
.fixangle()
this.count = 0;
}
}
};
PE.Particle.init3d = function(scene, mapping) {
geometry = new THREE.BufferGeometry();
var n = 25000;
var blending = THREE.NormalBlending;//THREE.AdditiveBlending;
/*THREE.NoBlending
THREE.NormalBlending
THREE.AdditiveBlending
THREE.SubtractiveBlending
THREE.MultiplyBlending
THREE.CustomBlending*/
positions = new Float32Array( n * 3 );
uvpos = new Float32Array( n * 2 );
colors = new Float32Array( n * 4 );
angles = new Float32Array( n );
sizes = new Float32Array( n );
var v = n;
while(v--){
sizes[v] = 0.3;
uvpos[v*2+1] = 1.0;
}
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
geometry.addAttribute( 'colors', new THREE.BufferAttribute( colors, 4 ) );
geometry.addAttribute( 'uvPos', new THREE.BufferAttribute( uvpos, 2 ) );
geometry.addAttribute( 'angle', new THREE.BufferAttribute( angles, 1 ) );
geometry.addAttribute( 'size', new THREE.BufferAttribute( sizes, 1 ) );
particleMaterial = new THREE.ShaderMaterial( {
//attributes:[ 'size', 'colors', 'uvPos', 'angle' ],
uniforms:{
ntiles : { type: 'f', value: 4.0 },
scale : { type: 'f', value: 800.0 },
map: { type: 't', value: null },
alphaTest : { type:'f', value: 0.0 }
},
fragmentShader:[
'uniform sampler2D map;',
'uniform float ntiles;',
'uniform float alphaTest;',
'varying vec4 vColor;',
'varying vec2 vPos;',
'varying float vAngle;',
// map tile position see Shader.js
PE.tileUV,
// map tile rotation see Shader.js
PE.rotUV,
'void main(){',
' vec2 uv = rotUV(vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ), vAngle);',
' vec2 coord = tileUV(uv, vPos, ntiles);',
' vec4 texture = texture2D( map, coord );',
' gl_FragColor = texture * vColor;',
' if ( gl_FragColor.a <= alphaTest ) discard;',
'}'
].join('\n'),
vertexShader:[
'attribute float angle;',
'attribute vec4 colors;',
'attribute vec2 uvPos;',
'attribute float size;',
'uniform float scale;',
'varying vec2 vPos;',
'varying vec4 vColor;',
'varying float vAngle;',
'void main(){',
' vPos = uvPos;',
' vColor = colors;',
' vAngle = angle;',
' vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );',
//' gl_PointSize = size * scale;',
' gl_PointSize = size * ( scale / length( mvPosition.xyz ) );',
' gl_Position = projectionMatrix * mvPosition;',
'}'
].join('\n'),
//vertexColors: THREE.VertexColors,
depthTest: false,
depthWrite: true,
transparent: true,
blending:blending
});
particleMaterial.uniforms.map.value = mapping;
var particlesCloud = new THREE.Points( geometry, particleMaterial );
// particlesCloud.position.set(0,0,0.01);
particlesCloud.frustumCulled = false;
scene.add( particlesCloud );
};
PE.Particle.tick = function( ) {
var i;
for( i = 0; i < emiters.length; i++) {
emiters[i].up();
}
for( i = 0; i < count; i++) {
var isAlive = particles[i].tick();
//
positions[i * 3 + 0] = particles[i].m_pos.x;//.toFixed(3);
positions[i * 3 + 1] = particles[i].m_pos.y;//.toFixed(3);
positions[i * 3 + 2] = particles[i].m_pos.z;//.toFixed(3);
//if(i===0) console.log(positions[i * 3 + 0], positions[i * 3 + 1]);
colors[i * 4 + 0] = particles[i].m_color.x;
colors[i * 4 + 1] = particles[i].m_color.y;
colors[i * 4 + 2] = particles[i].m_color.z;
colors[i * 4 + 3] = particles[i].m_color.w;
if(particles[i].m_uvpos.x!==0 && particles[i].m_uvpos.y!==0){
uvpos[i * 2 + 0] = particles[i].m_uvpos.x;
uvpos[i * 2 + 1] = particles[i].m_uvpos.y;
} else {
uvpos[i * 2 + 0] = particles[i].m_type*2;
}
angles[i] = particles[i].m_angle;
sizes[i] = particles[i].m_radius * 3;
if (!isAlive) {
// swap the current particle with the last active particle (this will swap with itself if this is the last active particle)
var temp = particles[i];
//
particles[i] = particles[count - 1];
colors[(count - 1) * 4 + 3] = 0.0;
particles[count - 1] = temp;
// forget about the dead particle that we just moved to the end of the active particle list
count--;
// don't skip the particle that we just swapped in
i--;
}
}
};
PE.Particle.dispersion = function(z) {
particleMaterial.uniforms.scale.value = z;
}
PE.Particle.scalemat = function(z) {
particleMaterial.uniforms.scale.value = z;
}
PE.Particle.update = function( seconds ) {
this.tick( seconds );
geometry.attributes.position.needsUpdate = true;
geometry.attributes.colors.needsUpdate = true;
geometry.attributes.uvPos.needsUpdate = true;
geometry.attributes.angle.needsUpdate = true;
geometry.attributes.size.needsUpdate = true;
}
return PE.Particle;
})();
PE.tileUV = [
'vec2 tileUV(vec2 uv, vec2 pos, float ntile){',
' pos.y = ntiles-pos.y-1.0;',
' vec2 sc = vec2(1.0/ntile, 1.0/ntile);',
' return vec2(uv*sc)+(pos*sc);',
'}',
].join("\n");
// tile rotation
// angle in radian
PE.rotUV = [
'vec2 rotUV(vec2 uv, float angle){',
' float s = sin(angle);',
' float c = cos(angle);',
' mat2 r = mat2( c, -s, s, c);',
' r *= 0.5; r += 0.5; r = r * 2.0 - 1.0;',
' uv -= 0.5; uv = uv * r; uv += 0.5;',
' return uv;',
'}',
].join("\n");
PE.decalUV = [
'vec2 decalUV(vec2 uv, float pix, float max){',
' float ps = uv.x / max;',
' float mx = uv.x / (uv.x-(ps*2.0));',
' vec2 decal = vec2( (ps*pix), - (ps*pix));',
' vec2 sc = vec2(uv.x*mx,uv.y*mx);',
//' uv -= ((2.0*pix)*ps);',
' return (uv);',
'}',
].join("\n");
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Loader } from 'semantic-ui-react';
import { Route, Redirect } from 'react-router-dom';
import Layout from '../Layouts/Back';
const Private = ({ component, hasSession, user, authenticated, ...rest }) => {
if (hasSession) {
return (
<Route
{...rest}
render={
props => (authenticated === true
? <Layout user={user} component={component} props={props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }
}
/>)} // eslint-disable-line react/prop-types
/>
);
}
return (<Loader active />);
};
Private.propTypes = {
component: PropTypes.func.isRequired,
authenticated: PropTypes.bool,
hasSession: PropTypes.bool.isRequired,
user: PropTypes.shape({
username: PropTypes.string.isRequired,
thumb: PropTypes.string.isRequired,
}).isRequired,
};
Private.defaultProps = {
authenticated: false,
};
const mapStateToProps = state => ({
authenticated: state.app.user && Object.keys(state.app.user).length > 0,
hasSession: state.app.getSessionSuccess,
user: state.app.user,
});
export default connect(mapStateToProps)(Private);
|
//Classes
var solarian = new Classe('Solarien', 'Solarian', 7, 7, 30, true, false, true, true, 4, 'Cha');
solarian.addClassCompetence('Accrobatie');
solarian.addClassCompetence('Athlétisme');
solarian.addClassCompetence('Bluff');
solarian.addClassCompetence('Diplomatie');
solarian.addClassCompetence('Discrétion');
solarian.addClassCompetence('Déguisement');
solarian.addClassCompetence('Intimidation');
solarian.addClassCompetence('Mysticisme');
solarian.addClassCompetence('Perception');
solarian.addClassCompetence('Profession');
solarian.addClassCompetence('Psychologie');
solarian.addClassCompetence('Sciences physiques');
starfinder.addClasse(solarian);
|
const config = require('./webpack.main.config');
new_config = {
mode: "production",
devtool: ""
};
module.exports = Object.assign(config, new_config)
|
$(window).load(function() {
$("#portImageOne").animate({
marginLeft: "0px",
opacity: "1.0"
}, 500, "swing", function() {
$("#portImageTwo").animate({
marginLeft: "0px",
opacity: "1.0"
}, 500, "swing", function() {
$("#portImageThree").animate({
marginLeft: "0px",
opacity: "1.0"
}, 500, "swing", function() {
$("#portImageFour").animate({
marginLeft: "0px",
opacity: "1.0"
}, 500, "swing", function() {
$("#portImageFive").animate({
marginLeft: "0px",
opacity: "1.0"
}, 500, "swing");
});
});
});
});
var mq = window.matchMedia( "(min-width: 992px)" );
var toggle = [0, 0, 0, 0, 0];
var globalThis = false;
var globalThisVal = -1;
$(".portImg").hover(function() {
if(this.getAttribute('val') != globalThisVal)
{
$(this).find('.portItemDesc').animate({
opacity: "1.0"
}, 100);
}
}, function() {
if(this != globalThis)
{
$(this).find('.portItemDesc').animate({
opacity: "0.0"
}, 100);
}
});
$(".portImg").on("click", function() {
//if the clicked tab is closed
if(toggle[$(this).attr("val")] == 0)
{
$(this).find('.portItemDesc').animate({
opacity: "0.0"
}, 100);
$(this).find('.portItemDescLong').animate({
opacity: "1.0"
}, 100);
//if another tab is already open
if(globalThis)
{
//go through all tabs toggle values
for(var i = 0; i < toggle.length; i++)
{
//only for tabs below the opened tab
if(i > globalThis.attr("val"))
{
//move those tabs up
if(mq.matches)
{
$(".portImg[val='" + i + "']").animate({
top: "-=50%"
}, 150, "swing");
}
else {
$(".portImg[val='" + i + "']").animate({
top: "-=30%"
}, 150, "swing");
}
}
}
//close the currently opened tab
if(mq.matches)
{
globalThis.animate({
height: "50%"
}, 150, "swing", function() {
globalThis.css({"z-index": "0"});
});
}
else {
if($(this).attr("val") == 4)
{
$(this).css({"margin-bottom": "100px"});
}
globalThis.animate({
height: "30%"
}, 150, "swing", function() {
globalThis.css({"z-index": "0"});
});
}
globalThis.find('.portItemDescLong').animate({
opacity: "0.0"
}, 100);
//change the tabs toggled state to closed
toggle[globalThis.attr("val")] = 0;
}
//assign the just clicked tab to be the currently open tab
globalThis = $(this);
globalThisVal = globalThis['context'].getAttribute('val');
//go through all tabs toggle values
for(var i = 0; i < toggle.length; i++)
{
//only for tabs below the clicked tab
if(i > $(this).attr("val"))
{
//move those tabs down to make room
if(mq.matches)
{
$(".portImg[val='" + i + "']").animate({
top: "+=50%"
}, 150, "swing");
}
else {
$(".portImg[val='" + i + "']").animate({
top: "+=30%"
}, 150, "swing");
}
}
}
//change the tabs toggled state to open
toggle[$(this).attr("val")] = 1;
//open the clicked tab
if(mq.matches)
{
$(this).css({"z-index": "3"}).animate({
height: "100%",
scrollTo: "0"
}, 150, "swing", function() {
$("html, body").animate({
scrollTop: $(this).offset().top - 50,
}, 150, "swing");
});
}
else {
if($(this).attr("val") == 4)
{
$(this).css({"margin-bottom": "30%"});
}
$(this).find(".portItemDescLong").css({"z-index": "4"});
$(this).css({"z-index": "3"}).animate({
height: "60%",
scrollTo: "0"
}, 150, "swing", function() {
$("html, body").animate({
scrollTop: $(this).offset().top - 80,
}, 150, "swing");
});
}
}
//if the clicked tab is open
else
{
$(this).find('.portItemDescLong').animate({
opacity: "0.0"
}, 100);
if(mq.matches)
{
$(this).find('.portItemDesc').animate({
opacity: "1.0"
}, 100);
}
//go through all tabs toggle values
for(var i = 0; i < toggle.length; i++)
{
//if the tab is lower than the clicked tab
if(i > $(this).attr("val"))
{
//move those tabs up
if(mq.matches)
{
$(".portImg[val='" + i + "']").animate({
top: "-=50%"
}, 150, "swing");
}
else {
$(".portImg[val='" + i + "']").animate({
top: "-=30%"
}, 150, "swing");
}
}
}
//close the tab and set globalThis false, meaning no tabs are open
if(mq.matches)
{
globalThis.animate({
height: "50%"
}, 150, "swing", function() {
globalThis.css({"z-index": "0"});
globalThis = false;
});
}
else {
globalThis.animate({
height: "30%"
}, 150, "swing", function() {
globalThis.css({"z-index": "0"});
globalThis = false;
});
if($(this).attr("val") == 4)
{
$(this).css({"margin-bottom": "100px"});
}
}
//set this tabs toggle value to closed
toggle[$(this).attr("val")] = 0;
globalThisVal = -1;
}
});
$('.navicon').on('click', function(){
$('.mainNavDropDown').slideToggle(500);
});
});
|
export function path (object, path, defaultValue) {
if (!path || path === '') {
return object || defaultValue
}
let list = path.split('.')
let value = object
for (let i = 0; i < list.length; i++) {
if (list[i] === '') {
continue
}
value = value[list[i]]
if (value === undefined) {
return defaultValue
}
}
return value
}
|
var searchData=
[
['matching2trees_2ecpp',['Matching2Trees.cpp',['../_matching2_trees_8cpp.html',1,'']]]
];
|
var program = require('commander');
var cradle = require('cradle');
var nano = require('nano');
program
.option('-u, --url <url>', 'DB URL')
.option('-d, --database <database>', 'Database')
.action(function() {
var connection = nano(program.url),
db = connection.use(program.database),
updated_docs = []
errors = [];
db.list({}, function(err, body) {
if (!err) {
console.log('start deleting docs from '+program.database);
body.rows.forEach(function(doc) {
db.insert({ _id: doc.id, _rev: doc.value.rev, "_deleted": true}, function(err, body) {
if (!err)
console.log('deleted: '+doc.id)
else{
console.log(err)
}
})
});
}else{
console.log(err);
}
});
console.log(db);
console.log('url: %s database: %s',
program.url, program.database);
})
.parse(process.argv);
|
define("elements/wb-video-review.js", [], function() {
"use strict";
function e(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
}
var t = function() {
function e(e, t) {
for (var i = 0; i < t.length; i++) {
var n = t[i];
n.enumerable = n.enumerable || !1, n.configurable = !0, "value" in n && (n.writable = !0), Object.defineProperty(e, n.key, n)
}
}
return function(t, i, n) {
return i && e(t.prototype, i), n && e(t, n), t
}
}(),
i = function() {
function i() {
e(this, i)
}
return t(i, [{
key: "beforeRegister",
value: function() {
this.is = "wb-video-review", this.properties = {
file: {
type: Object,
observer: "_fileChanged"
}
}
}
}, {
key: "ready",
value: function() {
this._updateVideoState()
}
}, {
key: "share",
value: function() {
this.$.video.pause();
//this.$.shareYoutubeDialog.open()
console.log("Share URL", this.$);
}
}, {
key: "download",
value: function() {
var e = document.createElement("a");
e.setAttribute("href", this._url), e.setAttribute("download", "video.webm"), e.dispatchEvent(new MouseEvent("click"))
}
}, {
key: "delete",
value: function() {
this.fire("wb-review-discard"), this.file = null
}
}, {
key: "_updateVideoState",
value: function() {
this.videoEnded = this.$.video.ended || this.$.video.paused
}
}, {
key: "_isChrome",
value: function() {
return !!window.chrome
}
}, {
key: "_replay",
value: function() {
var e = this.$.video;
e.currentTime = 0, e.pause(), e.play()
}
}, {
key: "_fileChanged",
value: function(e) {
this._url && URL.revokeObjectURL(this._url), e ? (this._url = URL.createObjectURL(e), this.$.video.src = this._url, this.$.video.play(), this.$.video.paused && this._updateVideoState()) : (this.$.video.pause(), this.$.video.src = "")
}
}]), i
}();
Polymer(i)
});
Polymer({
is: "google-js-api",
behaviors: [Polymer.IronJsonpLibraryBehavior],
properties: {
libraryUrl: {
type: String,
value: "https://apis.google.com/js/api.js?onload=%%callback%%"
},
notifyEvent: {
type: String,
value: "js-api-load"
}
},
get api() {
return gapi
}
});
! function() {
"use strict";
var e = !1,
i = {},
t = {};
Polymer({
is: "google-client-loader",
properties: {
name: String,
version: String,
appId: String,
apiRoot: String,
successEventName: {
type: String,
value: "google-api-load"
},
errorEventName: {
type: String,
value: "google-api-load-error"
}
},
hostAttributes: {
hidden: !0
},
_waiting: !1,
get api() {
return window.gapi && window.gapi.client && window.gapi.client[this.name] ? window.gapi.client[this.name] : void 0
},
get auth() {
return gapi.auth
},
ready: function() {
this._loader = document.createElement("google-js-api"), this.listen(this._loader, "js-api-load", "_loadClient")
},
detached: function() {
this.unlisten(this._loader, "js-api-load", "_loadClient")
},
_loadClient: function() {
gapi.load("client", this._doneLoadingClient.bind(this))
},
_handleLoadResponse: function(e) {
e && e.error ? (i[this.name] = "error", this._fireError(e)) : (i[this.name] = "loaded", this._fireSuccess())
},
_fireSuccess: function() {
this.fire(this.successEventName, {
name: this.name,
version: this.version
})
},
_fireError: function(e) {
e && e.error ? this.fire(this.errorEventName, {
name: this.name,
version: this.version,
error: e.error
}) : this.fire(this.errorEventName, {
name: this.name,
version: this.version
})
},
_doneLoadingClient: function() {
e = !0, this._waiting || this._loadApi()
},
_createSelfRemovingListener: function(e) {
var i = function() {
t[this.name].removeEventListener(e, i), this._loadApi()
}.bind(this);
return i
},
_loadApi: function() {
if (e && this.name && this.version)
if (this._waiting = !1, "loaded" == i[this.name]) this._fireSuccess();
else if ("loading" == i[this.name]) this._waiting = !0, t[this.name].addEventListener(this.successEventName, this._createSelfRemovingListener(this.successEventName)), t[this.name].addEventListener(this.errorEventName, this._createSelfRemovingListener(this.errorEventName));
else if ("error" == i[this.name]) this._fireError(null);
else {
var n;
this.apiRoot ? n = this.apiRoot : this.appId && (n = "https://" + this.appId + ".appspot.com/_ah/api"), i[this.name] = "loading", t[this.name] = this, gapi.client.load(this.name, this.version, this._handleLoadResponse.bind(this), n)
}
}
})
}();
! function() {
var e = {
appPackageName: "apppackagename",
clientId: "clientid",
cookiePolicy: "cookiepolicy",
hostedDomain: "hostedDomain",
openidPrompt: "prompt",
requestVisibleActions: "requestvisibleactions"
},
t = {
_clientId: null,
get clientId() {
return this._clientId
},
set clientId(e) {
if (this._clientId && e && e != this._clientId) throw new Error("clientId cannot change. Values do not match. New: " + e + " Old:" + this._clientId);
e && e != this._clientId && (this._clientId = e, this.initAuth2())
},
_cookiePolicy: "single_host_origin",
get cookiePolicy() {
return this._cookiePolicy
},
set cookiePolicy(e) {
e && (this._cookiePolicy = e)
},
_appPackageName: "",
get appPackageName() {
return this._appPackageName
},
set appPackageName(e) {
if (this._appPackageName && e && e != this._appPackageName) throw new Error("appPackageName cannot change. Values do not match. New: " + e + " Old: " + this._appPackageName);
e && (this._appPackageName = e)
},
_requestVisibleActions: "",
get requestVisibleactions() {
return this._requestVisibleActions
},
set requestVisibleactions(e) {
if (this._requestVisibleActions && e && e != this._requestVisibleActions) throw new Error("requestVisibleactions cannot change. Values do not match. New: " + e + " Old: " + this._requestVisibleActions);
e && (this._requestVisibleActions = e)
},
_hostedDomain: "",
get hostedDomain() {
return this._hostedDomain
},
set hostedDomain(e) {
if (this._hostedDomain && e && e != this._hostedDomain) throw new Error("hostedDomain cannot change. Values do not match. New: " + e + " Old: " + this._hostedDomain);
e && (this._hostedDomain = e)
},
_openidPrompt: "",
get openidPrompt() {
return this._openidPrompt
},
set openidPrompt(e) {
if ("string" != typeof e) throw new Error("openidPrompt must be a string. Received " + typeof e);
if (e) {
var t = e.split(" ");
t = t.map(function(e) {
return e.trim()
}), t = t.filter(function(e) {
return e
});
var i = {
none: 0,
login: 0,
consent: 0,
select_account: 0
};
t.forEach(function(e) {
if ("none" == e && t.length > 1) throw new Error("none cannot be combined with other openidPrompt values");
if (!(e in i)) throw new Error("invalid openidPrompt value " + e + ". Valid values: " + Object.keys(i).join(", "))
})
}
this._openidPrompt = e
},
_offline: !1,
get offline() {
return this._offline
},
set offline(e) {
this._offline = e, this.updateAdditionalAuth()
},
_offlineAlwaysPrompt: !1,
get offlineAlwaysPrompt() {
return this._offlineAlwaysPrompt
},
set offlineAlwaysPrompt(e) {
this._offlineAlwaysPrompt = e, this.updateAdditionalAuth()
},
offlineGranted: !1,
_apiLoader: null,
_requestedScopeArray: [],
get requestedScopes() {
return this._requestedScopeArray.join(" ")
},
_signedIn: !1,
_grantedScopeArray: [],
_needAdditionalAuth: !0,
_hasPlusScopes: !1,
signinAwares: [],
init: function() {
this._apiLoader = document.createElement("google-js-api"), this._apiLoader.addEventListener("js-api-load", this.loadAuth2.bind(this))
},
loadAuth2: function() {
gapi.load("auth2", this.initAuth2.bind(this))
},
initAuth2: function() {
if ("gapi" in window && "auth2" in window.gapi && this.clientId) {
var e = gapi.auth2.init({
client_id: this.clientId,
cookie_policy: this.cookiePolicy,
scope: this.requestedScopes,
hosted_domain: this.hostedDomain
});
e.currentUser.listen(this.handleUserUpdate.bind(this)), e.then(function() {}, function(e) {
console.error(e)
})
}
},
handleUserUpdate: function(e) {
var t = e.isSignedIn();
if (t != this._signedIn) {
this._signedIn = t;
for (var i = 0; i < this.signinAwares.length; i++) this.signinAwares[i]._setSignedIn(t)
}
this._grantedScopeArray = this.strToScopeArray(e.getGrantedScopes()), this.updateAdditionalAuth();
for (var n = e.getAuthResponse(), i = 0; i < this.signinAwares.length; i++) this.signinAwares[i]._updateScopeStatus(n)
},
setOfflineCode: function(e) {
for (var t = 0; t < this.signinAwares.length; t++) this.signinAwares[t]._updateOfflineCode(e)
},
strToScopeArray: function(e) {
if (!e) return [];
for (var t = e.replace(/\ +/g, " ").trim().split(" "), i = 0; i < t.length; i++) t[i] = t[i].toLowerCase(), "https://www.googleapis.com/auth/userinfo.profile" === t[i] && (t[i] = "profile"), "https://www.googleapis.com/auth/userinfo.email" === t[i] && (t[i] = "email");
return t.filter(function(e, t, i) {
return i.indexOf(e) === t
})
},
isPlusScope: function(e) {
return e.indexOf("/auth/games") > -1 || e.indexOf("auth/plus.") > -1 && e.indexOf("auth/plus.me") < 0
},
hasGrantedScopes: function(e) {
for (var t = this.strToScopeArray(e), i = 0; i < t.length; i++)
if (this._grantedScopeArray.indexOf(t[i]) === -1) return !1;
return !0
},
requestScopes: function(e) {
for (var t = this.strToScopeArray(e), i = !1, n = 0; n < t.length; n++) this._requestedScopeArray.indexOf(t[n]) === -1 && (this._requestedScopeArray.push(t[n]), i = !0);
i && (this.updateAdditionalAuth(), this.updatePlusScopes())
},
updateAdditionalAuth: function() {
var e = !1;
if (!this.offlineAlwaysPrompt && !this.offline || this.offlineGranted) {
for (var t = 0; t < this._requestedScopeArray.length; t++)
if (this._grantedScopeArray.indexOf(this._requestedScopeArray[t]) === -1) {
e = !0;
break
}
} else e = !0;
if (this._needAdditionalAuth != e) {
this._needAdditionalAuth = e;
for (var t = 0; t < this.signinAwares.length; t++) this.signinAwares[t]._setNeedAdditionalAuth(e)
}
},
updatePlusScopes: function() {
for (var e = !1, t = 0; t < this._requestedScopeArray.length; t++)
if (this.isPlusScope(this._requestedScopeArray[t])) {
e = !0;
break
}
if (this._hasPlusScopes != e) {
this._hasPlusScopes = e;
for (var t = 0; t < this.signinAwares.length; t++) this.signinAwares[t]._setHasPlusScopes(e)
}
},
attachSigninAware: function(e) {
this.signinAwares.indexOf(e) == -1 ? (this.signinAwares.push(e), e._setNeedAdditionalAuth(this._needAdditionalAuth), e._setSignedIn(this._signedIn), e._setHasPlusScopes(this._hasPlusScopes)) : console.warn("signinAware attached more than once", e)
},
detachSigninAware: function(e) {
var t = this.signinAwares.indexOf(e);
t != -1 ? this.signinAwares.splice(t, 1) : console.warn("Trying to detach unattached signin-aware")
},
getMissingScopes: function() {
return this._requestedScopeArray.filter(function(e) {
return this._grantedScopeArray.indexOf(e) === -1
}.bind(this)).join(" ")
},
assertAuthInitialized: function() {
if (!this.clientId) throw new Error("AuthEngine not initialized. clientId has not been configured.");
if (!("gapi" in window)) throw new Error("AuthEngine not initialized. gapi has not loaded.");
if (!("auth2" in window.gapi)) throw new Error("AuthEngine not initialized. auth2 not loaded.")
},
signIn: function() {
this.assertAuthInitialized();
var i = {
scope: this.getMissingScopes()
};
Object.keys(e).forEach(function(t) {
this[t] && "" !== this[t] && (i[e[t]] = this[t])
}, this);
var n, o = gapi.auth2.getAuthInstance().currentUser.get();
this.offline || this.offlineAlwaysPrompt ? (i.redirect_uri = "postmessage", this.offlineAlwaysPrompt && (i.approval_prompt = "force"), n = gapi.auth2.getAuthInstance().grantOfflineAccess(i)) : n = o.getGrantedScopes() ? o.grant(i) : gapi.auth2.getAuthInstance().signIn(i), n.then(function(e) {
var i;
e.code ? (t.offlineGranted = !0, i = gapi.auth2.getAuthInstance().currentUser.get(), t.setOfflineCode(e.code)) : i = e;
i.getAuthResponse()
}, function(e) {
"Access denied." !== e.reason && this.signinAwares.forEach(function(t) {
t.errorNotify(e)
})
}.bind(this))
},
signOut: function() {
this.assertAuthInitialized(), gapi.auth2.getAuthInstance().signOut().then(function() {}, function(e) {
console.error(e)
})
}
};
t.init(), Polymer({
is: "google-signin-aware",
properties: {
appPackageName: {
type: String,
observer: "_appPackageNameChanged"
},
clientId: {
type: String,
observer: "_clientIdChanged"
},
cookiePolicy: {
type: String,
observer: "_cookiePolicyChanged"
},
requestVisibleActions: {
type: String,
observer: "_requestVisibleActionsChanged"
},
hostedDomain: {
type: String,
observer: "_hostedDomainChanged"
},
offline: {
type: Boolean,
value: !1,
observer: "_offlineChanged"
},
offlineAlwaysPrompt: {
type: Boolean,
value: !1,
observer: "_offlineAlwaysPromptChanged"
},
scopes: {
type: String,
value: "profile",
observer: "_scopesChanged"
},
openidPrompt: {
type: String,
value: "",
observer: "_openidPromptChanged"
},
signedIn: {
type: Boolean,
notify: !0,
readOnly: !0
},
isAuthorized: {
type: Boolean,
notify: !0,
readOnly: !0,
value: !1
},
needAdditionalAuth: {
type: Boolean,
notify: !0,
readOnly: !0
},
hasPlusScopes: {
type: Boolean,
value: !1,
notify: !0,
readOnly: !0
}
},
attached: function() {
t.attachSigninAware(this)
},
detached: function() {
t.detachSigninAware(this)
},
signIn: function() {
t.signIn()
},
signOut: function() {
t.signOut()
},
errorNotify: function(e) {
this.fire("google-signin-aware-error", e)
},
_appPackageNameChanged: function(e, i) {
t.appPackageName = e
},
_clientIdChanged: function(e, i) {
t.clientId = e
},
_cookiePolicyChanged: function(e, i) {
t.cookiePolicy = e
},
_requestVisibleActionsChanged: function(e, i) {
t.requestVisibleActions = e
},
_hostedDomainChanged: function(e, i) {
t.hostedDomain = e
},
_offlineChanged: function(e, i) {
t.offline = e
},
_offlineAlwaysPromptChanged: function(e, i) {
t.offlineAlwaysPrompt = e
},
_scopesChanged: function(e, i) {
t.requestScopes(e), this._updateScopeStatus(void 0)
},
_openidPromptChanged: function(e, i) {
t.openidPrompt = e
},
_updateScopeStatus: function(e) {
var i = this.signedIn && t.hasGrantedScopes(this.scopes);
i !== this.isAuthorized && (this._setIsAuthorized(i), i ? this.fire("google-signin-aware-success", e) : this.fire("google-signin-aware-signed-out", e))
},
_updateOfflineCode: function(e) {
e && this.fire("google-signin-offline-success", {
code: e
})
}
})
}();
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import {Redirect} from 'react-router-dom'
import FacebookLogin from 'react-facebook-login'
import * as actionTypes from '../../store/actions'
import classes from './login.module.scss'
class Login extends Component {
loginResponse = (response) => {
this.props.history.push({
pathname: '/posts'
});
console.log('res', response)
this.props.loginResponse(response);
}
render() {
console.log(this.props.login);
const page = this.props.login ?
(<Redirect to='/posts' />) :
(<FacebookLogin
appId="566899433790128"
autoLoad={false}
fields="name,picture"
callback={this.loginResponse} />);
return (<div className={classes.Login}>{page}</div>);
}
}
const mapStateToProps = state => {
return {
login: state.login
}
}
const mapDispatchToProps = dispatch => {
return {
loginResponse: (loginData) => dispatch({type: actionTypes.LOGIN, loginData: loginData})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
|
describe('Course Controller', () => {
before((done) => {
done();
});
it('Should fetch all the courses', (done) => {
done();
});
it('Should fetch all concepts associated with the course', (done) => {
done();
});
it('Should fetch all the contents associated with the course', (done) => {
done();
});
after((done) => {
done();
});
});
|
import React from 'react';
import {
FaFacebookF,
FaTwitter,
} from 'react-icons/fa';
import '../global.css';
import * as styles from './submitted.module.css';
const Submitted = () => {
const text = encodeURIComponent(
`I\'ve nominated movies for The Shoppies award! Share your favourite movies too:`,
);
const url = 'https://dariatsvetkova.github.io/shoppies-by-daria/';
return (
<section className={`${styles.submitted} gridContainer appear`}>
<h2>Thank you!</h2>
<article>
<p>Your Shoppies nominations have been submitted.</p>
<p>Share on social media:</p>
<div>
<button className={`${styles.socialButton} iconButton`}>
<a
href={`https://www.facebook.com/sharer/sharer.php?u=${url}`}
target="_blank"
rel="noreferrer"
title="Share on Facebook"
>
<FaFacebookF />
</a>
</button>
<button className={`${styles.socialButton} iconButton`}>
<a
href={`https://twitter.com/intent/tweet?url=${url}&text=${text}`}
target="_blank"
rel="noreferrer"
title="Share on Twitter"
>
<FaTwitter />
</a>
</button>
</div>
</article>
</section>
);
};
export default Submitted;
|
import React from "react";
import { Route, Switch } from "react-router";
// import slugify from "react-slugify";
/*** Styles ***/
import "./App.css";
/*** Components ***/
import CandyDetail from "./components/CandyDetail";
import CandyList from "./components/CandyList";
import Home from "./components/Home";
import BakeryList from "./components/bakeries/BakeryList";
import BakeryDetail from "./components/bakeries/BakeryDetail";
import candyStore from "./stores/candyStore";
const Routes = () => {
return (
<Switch>
<Route path="/candies/:candySlug">
<CandyDetail />
</Route>
<Route path="/candies">
<CandyList candies={candyStore.candies} />
</Route>
<Route path="/bakeries/:bakerySlug">
<BakeryDetail />
</Route>
<Route path="/bakeries">
<BakeryList />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
);
};
export default Routes;
|
function getCleanUser(user) {
if (!user) return {}
var u = user.toJSON()
return {
userid: u.id,
email: u.email,
admin: u.admin,
contactwin: u.contactwin,
contactlose: u.contactlose,
isEmailVerified: u.isEmailVerified,
createdAt: u.createdAt,
updatedAt: u.updatedAt,
image: u.image,
isEmailVerified: u.isEmailVerified
}
}
module.exports = getCleanUser
|
if (typeof Global === "undefined") {
Global = {};
}
//当前登陆人所在机构的栏目树
Global.mySendDocOrgDirLoader = new Disco.Ext.MemoryTreeLoader({
iconCls: 'disco-tree-node-icon',
varName: "Global.MY_SEND_DOC_ORG_LOADER",//缓存Key
url: "newsDir.java?cmd=getDirTreeByCurrentUserOrg&pageSize=-1&treeData=true&all=false&orgdir=true",
listeners: {
'beforeload': function(treeLoader, node) {
treeLoader.baseParams.id = (node.id.indexOf('root') < 0 ? node.id : "");
if (typeof node.attributes.checked !== "undefined") {
treeLoader.baseParams.checked = false;
}
}
}
});
//分行栏目树
Global.mySendDocBranchDirLoader = new Disco.Ext.MemoryTreeLoader({
iconCls: 'disco-tree-node-icon',
varName: "Global.MY_SEND_DOC_BRANCH_DIR_LOADER",//缓存Key
url: "newsDir.java?cmd=getBranchDirTree&pageSize=-1&treeData=true&all=false&orgType=null",
listeners: {
'beforeload': function(treeLoader, node) {
treeLoader.baseParams.id = (node.id.indexOf('root') < 0 ? node.id : "");
if (typeof node.attributes.checked !== "undefined") {
treeLoader.baseParams.checked = false;
}
}
}
});
/**
* 文档暂存箱
* @class MyStorageDocManagePanel
* @extends Disco.Ext.CrudPanel
*/
MyStorageDocManagePanel = Ext.extend(Disco.Ext.CrudPanel, {
gridSelModel: 'checkbox',
id: "myStorageDocManagePanel",
baseUrl: "newsDoc.java",
autoLoadGridData: true,
autoScroll: false,
totalPhoto: 0,
pageSize: 20,
showAdd: false,
showView: false,
batchRemoveMode: true,
defaultsActions: {
create: 'save',
list: 'getMyStorage',
view: 'view',
update: 'update',
remove: 'remove'
},
baseQueryParameter: {
//查询暂存文档
state: 4
},
gridViewConfig: {
forceFit: true,
enableRowBody: true,
showPreview: true
},
//记录用户的上次操作记录
tempCookie: {
dir: null
},
edit: function() {
var me = this;
if (!this.editWin) {
Disco.Ext.Util.listObject('NewsDocEditManagePanel', function(obj) {
this.editWin = obj;
this.editWin.show();
this.editWin.refurbishParentGrid = function() {
//保存之后刷新grid
me.grid.store.reload();
};
this.initWinFormData(this.editWin);
}.createDelegate(this), 'cms/doc/NewsDocEditManagePanel.js')
} else {
this.editWin.show();
this.initWinFormData(this.editWin);
}
},
initWinFormData: function(_this) {
var record = this.grid.getSelectionModel().getSelected();
if (!record) {
return Ext.Msg.alert("提醒", "请选择需编辑的数据");
}
Ext.Ajax.request({
scope: this,
url: this.baseUrl + "?cmd=getContent&id=" + record.get('id'),
success: function(response) {
var data = Ext.decode(response.responseText);
data != null || (data = "");
_this.editor.html(data);
_this.editor.sync();
}
});
//编辑回显时如果有父级栏目及回显数据
var dirObj = record.get('dir');
var newsDir = _this.fp.form.findField('dir');
if (dirObj) {
dirObj.title || (dirObj.title = dirObj.name);
newsDir.setOriginalValue(dirObj);
}
var branchDirObj = record.get('branchDir');
var branchDir = _this.fp.form.findField('branchDir');
if (branchDirObj) {
branchDirObj.title || (branchDirObj.title = branchDirObj.name);
branchDir.setOriginalValue(branchDirObj);
}
_this.fp.form.loadRecord(record);
},
view: function() {
var record = this.grid.getSelectionModel().getSelected();
if (!record)
return Ext.Msg.alert("$!{lang.get('Prompt')}", "$!{lang.get('Select first')}");
window.open("news.java?cmd=show&id=" + record.get("id"));
},
moveNewsDocToDir: function() {
var record = this.grid.getSelectionModel().getSelected();
if (!record) {
this.alert("请先选择要操作的数据!", "提示信息");
return false;
}
if (!this.viewWinPanel) {
this.viewWinPanel = this.createViewWinPanel();
}
this.viewWinPanel.show();
var form = this.viewWinPanel.getComponent(0).form;
form.clearData();
form.reset();
this.onView(form, record.data);
form.findField('branchDir').setValue({
id: record.get('branchDir').id,
title: record.get('branchDir').name
})
},
createViewWinPanel: function() {
var win = new Ext.Window({
width: 300,
height: 110,
modal: true,
closeAction: 'hide',
buttonAlign: "center",
title: "选择栏目后发表",
buttons: [{
text: "发表(<u>K</u>)",
handler: function() {
var me = this;
var form = me.viewWinPanel.getComponent(0).form;
if (!form.isValid()) {
Ext.Msg.alert('提醒', '请先选择一个栏目后再发表');
return;
};
var vals = me.getViewFormObj();
me.executeUrl('newsDoc.java', {
cmd: 'moveNewsDocToDir',
mulitId: vals.mulitId,
branchDirId: vals.branchDirId
}, function() {
me.grid.store.reload()
me.viewWinPanel.hide();
})();
},
iconCls: 'save',
scope: this
}]
});
win.add(this.createForm());
return win;
},
createForm: function() {
var formPanel = new Ext.form.FormPanel({
frame: true,
labelWidth: 70,
fileUpload: true,
autoScroll: true,
labelAlign: 'right',
defaults: {
xtype: 'textfield'
},
items: [{
name: "id",
xtype: "hidden"
}, {
name: 'branchDir',
fieldLabel: '文章栏目',
xtype: "treecombo",
valueField: "id",
allowBlank: false,
blankText: '文章栏目不能为空',
hiddenName: "branchDirId",
displayField: "title",
tree: new Ext.tree.TreePanel({
rootVisible: false,
autoScroll: true,
root: new Ext.tree.AsyncTreeNode({
id: "root",
text: "所有栏目",
expanded: true,
iconCls: 'treeroot-icon',
loader: Global.mySendDocBranchDirLoader
})
})
}]
});
return formPanel;
},
getViewFormObj: function() {
var mulitId = "";
var rs = this.grid.getSelectionModel().getSelections();
for (var i = 0; i < rs.length; i++) {
mulitId += rs[i].get("id") + ",";
}
var form = this.viewWinPanel.getComponent(0).form;
var obj = {};
obj.mulitId = mulitId;
obj.branchDirId = form.findField('branchDir').getValue();
return obj;
},
topicRender: function(value, p, record) {
return String.format('{1}<b><a style="color:green" href="news.java?cmd=show&id={0}" target="_blank"> 查看</a></b><br/>', record.id, value)
},
stateRender: function(v) {
if (v == 0) {
return "逻辑删除";
} else if (v == 1) {
return "发表";
} else if (v == 2) {
return "退回";
} else if (v == 3) {
return "待审核";
} else if (v == 4) {
return "暂存";
} else {
return "未知状态";
}
},
toggleDetails: function(btn, pressed) {
var view = this.grid.getView();
view.showPreview = pressed;
view.refresh();
},
storeMapping: ["id", "title", "keywords", 'iconPath', "createDate", "author", "source", "putDate", "dir", "toBranch", "branchDir", "state", "branchState", {
name: "branchDirId",
mapping: "branchDir"
}, {
name: "dirId",
mapping: "dir"
}],
initComponent: function() {
this.cm = new Ext.grid.ColumnModel([{
header: "主题",
dataIndex: 'title',
width: 200,
renderer: this.topicRender
}, {
header: "栏目",
sortable: true,
width: 70,
dataIndex: "dir",
renderer: this.objectRender("name")
}, {
width: 70,
sortable: true,
header: "发布到分行",
dataIndex: "toBranch",
renderer: this.booleanRender
}, {
width: 70,
sortable: true,
header: "分行栏目",
dataIndex: "branchDir",
renderer: this.objectRender("name")
}, {
header: "作者",
sortable: true,
width: 50,
dataIndex: "author"
}, {
header: "撰稿日期",
sortable: true,
width: 90,
dataIndex: "createDate",
renderer: this.dateRender()
}, {
width: 60,
sortable: true,
header: "当前状态",
dataIndex: "state",
renderer: this.stateRender
}]);
var user = Global.getCurrentUser;
if (user.branchAdmin) {
this.gridButtons = [{
text: '批量发布',
cls: "x-btn-text-icon",
icon: "img/core/up.gif",
handler: this.executeCmd("batchPublish")
}, {
text: '批量发布到指定栏目',
cls: "x-btn-text-icon",
icon: "img/core/up.gif",
handler: this.moveNewsDocToDir
}]
}
MyStorageDocManagePanel.superclass.initComponent.call(this);
}
});
|
import {useParam, useParams} from 'react-router-dom';
import React, { useState, useEffect } from 'react';
const Thought =() =>{
const [articles,setArticles]=([])
const [term,setTerm] =useState('everything')
const [isLoading,setIsLoading] = useState(true)
const {_id:_id}=useParams()
useEffect(()=>{
const fetchArticles = async () =>{
try{
const res = await fetch(`https://api.nytimes.com/svc/search/v2/articlesearch.json?q=${term}&api-key=hgGZ9Qf26H4JZSuum97ZdjfSvdrM1GG0 ` + _id
)
const articles = await res.json()
console.log(articles)
setArticles(articles.response.docs.abstract)
setIsLoading(false)
}
catch (err) {
console.log(err)
}
}
fetchArticles()
},[term])
return(
<>
</>
)
}
export default Thought
|
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
function autorefresh(){
window.onload = timedRefresh(60000);
}
|
// @flow strict
import * as React from 'react';
import { graphql, createFragmentContainer } from '@kiwicom/mobile-relay';
import Timeline from './Timeline';
import type { OneWayTimeline as OneWayTimelineType } from './__generated__/OneWayTimeline.graphql';
type Props = {|
+data: OneWayTimelineType,
|};
function OneWayTimeline(props: Props) {
return <Timeline data={[props.data.trip]} />;
}
export default createFragmentContainer(
OneWayTimeline,
graphql`
fragment OneWayTimeline on BookingOneWay {
trip {
...Timeline
}
}
`,
);
|
const { expect } = require('chai');
const rewire = require('rewire');
const { uuidSchema, tagsSchema,
checkSchema, performValidation } = require('../../lib/utils/validation');
const validationRewire = rewire('../../lib/utils/validation');
const timeoutMin = validationRewire.__get__('TIMEOUT_MIN');
const timeoutMax = validationRewire.__get__('TIMEOUT_MAX');
describe('Validation Util Tests', () => {
let result;
/*
* Properties in an health check object
* that requires string validation.
*/
const stringProps = [
'name',
'tags',
'desc',
'schedule',
'tz',
'channels',
];
/*
* Properties in an health check object
* that requires integer validation.
*/
const integerProps = ['timeout', 'grace'];
context('#performValidation()', () => {
it('should validate a valid uuid as true', () => {
result = performValidation(
'3c1169a0-7b50-11ea-873d-3c970e75c219', uuidSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
});
it('should validate an invalid uuid as false', () => {
result = performValidation(
'not a valid uuid', uuidSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The 'uuid' must be a valid UUID string`
});
result = performValidation(888, uuidSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The 'uuid' must be a string`
});
result = performValidation('', uuidSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The 'uuid' cannot be empty`
});
result = performValidation(undefined, uuidSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The 'uuid' is a required value`
});
});
it(`should validate a valid 'tags' value as true`, () => {
result = performValidation(['prod', 'app'], tagsSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
result = performValidation([], tagsSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
});
it(`should validate an invalid 'tags' value as false`, () => {
result = performValidation({}, tagsSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The 'tags' must be an array of strings`
});
result = performValidation([25, 50], tagsSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The 'tags' must be an array of strings`
});
});
it(`should validate a valid health check value as true`, () => {
// Iterate through the properties.
stringProps.forEach((prop) => {
result = performValidation({ [prop]: 'some string' }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
result = performValidation({ [prop]: '' }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
result = performValidation({ [prop]: null }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
});
// Iterate through the properties.
integerProps.forEach((prop) => {
result = performValidation({ [prop]: 200 }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
result = performValidation({ [prop]: null }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
});
result = performValidation({ unique: [ 'name' ] }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
result = performValidation({ unique: [ 'name', 'grace' ] }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
result = performValidation({ unique: null }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
result = performValidation({ unique: [] }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({ valid: true });
});
it(`should validate a valid health check value as false`, () => {
// Iterate through the properties.
stringProps.forEach((prop) => {
result = performValidation({ [prop]: 45 }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The '${prop}' value must be a string`
});
result = performValidation({ [prop]: {} }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The '${prop}' value must be a string`
});
});
// Iterate through the properties.
integerProps.forEach((prop) => {
result = performValidation({ [prop]: 'not an integer' }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The '${prop}' value must be an integer between ` +
`${timeoutMin} and ${timeoutMax}`
});
result = performValidation({ [prop]: 99.9 }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The '${prop}' value must be an integer between ` +
`${timeoutMin} and ${timeoutMax}`
});
result = performValidation({ [prop]: 32 }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The '${prop}' value must be larger than or equal to ${timeoutMin}`
});
result = performValidation({ [prop]: timeoutMax + 100 }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The '${prop}' value must be smaller than or equal to ${timeoutMax}`
});
});
result = performValidation({ unique: {} }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The 'unique' value must be an array of strings`
});
result = performValidation({ unique: 25 }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `The 'unique' value must be an array of strings`
});
result = performValidation({ unique: [ 88 ] }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `A 'unique' item must be a string that equals either 'name', ` +
`'tags', 'timeout', or 'grace'`
});
result = performValidation({ unique: [ '' ] }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `A 'unique' item must be a string that equals either 'name', ` +
`'tags', 'timeout', or 'grace'`
});
result = performValidation({ unique: [ 45, 88, {} ] }, checkSchema);
expect(result).to.be.an('object');
expect(result).to.eql({
valid: false,
errors: `A 'unique' item must be a string that equals either 'name', ` +
`'tags', 'timeout', or 'grace'`
});
});
});
});
|
import React from 'react';
import "./ProjectTasks.css"
import PTask from "./PTask/PTask"
import { useState } from 'react'
import { useSpring, animated } from 'react-spring'
const ProjectTasks = (props) => {
let data = JSON.parse(localStorage.getItem('projects'));
const animateToDo = useSpring({ from: { opacity: 0 }, to: { opacity: 1 }, config: { duration: 200 } })
const [taskState, setTaskState] = useState(props.tasksData.project_todos);
const [progressState, setProgressState] = useState(props.tasksData.project_inProgress);
const [stuckState, setStuckState] = useState(props.tasksData.project_stuck);
const [completeState, setCompleteState] = useState(props.tasksData.project_complete);
const [newTask, setNewTask] = useState(0);
const [clearState, setClearState] = useState(0);
const [buttonStyle, setButtonStyle] = useState("create-task-button-off");
const [emptySubmit, setEmptySubmit] = useState(0);
const [emptyStyle, setEmptyStyle] = useState("task-title-creation");
function clearPopUps() {
setClearState(0);
console.log(clearState)
return 0;
}
function errorStyle() {
if (emptySubmit === 0) {
return <span></span>
}
else {
return <i class="fas fa-exclamation-circle"></i>
}
}
function submitError() {
if (emptySubmit === 0) {
return "Task Title"
}
else {
return "Please Enter A Title"
}
}
function plusState() {
if (buttonStyle === "create-task-button-on") {
return <span>-</span>
}
else {
return <span>+</span>
}
}
function addTaskDrop() {
if (newTask === 1) {
setNewTask(0)
setButtonStyle("create-task-button-off");
setEmptyStyle("task-title-creation")
setEmptySubmit(0)
}
else {
setNewTask(1);
setButtonStyle("create-task-button-on")
}
}
function changeInputStyle() {
setEmptySubmit(0);
setEmptyStyle("task-title-creation")
}
function renderTaskCreation() {
if (newTask === 1) {
return (<div className="task-creation">
<input className={emptyStyle} placeholder={submitError()} onClick={changeInputStyle} />{errorStyle()}
<input className="task-description-creation" placeholder="Task Description" />
<select className="task-category-selection">
<option value="Development">Development</option>
<option value="Design">Design</option>
<option value="Engineering">Engineering</option>
<option value="Bussiness">Bussiness</option>
</select>
<button className="add-task-button" onClick={addTask}>Add Task</button>
</div>)
}
else if (newTask === 0) {
return null
}
}
function addTask() {
let taskTitle = document.querySelector('.task-title-creation').value;
let taskDescription = document.querySelector('.task-description-creation').value;
let taskCategory = document.querySelector('.task-category-selection').value;
let newTask = {
category: taskCategory,
todo_description: taskDescription,
todo_title: taskTitle,
taskID: Math.floor(Math.random() * 20000)
}
if (taskTitle === "" || taskTitle === null || taskDescription === null || taskDescription === "") {
setEmptySubmit(1);
setEmptyStyle("task-title-creation-error task-title-creation")
}
else {
let i;
for (i = 0; i < data.length; i++) {
if (data[i].projectID === props.tasksData.projectID) {
data[i].project_todos.push(newTask);
localStorage.setItem('projects', JSON.stringify(data));
setTaskState(data[i].project_todos)
}
}
setNewTask(0)
setButtonStyle("create-task-button-off");
}
props.update(props.updateData + 1)
}
function deleteTask(taskID) {
let dataSet = JSON.parse(localStorage.getItem('projects'))
let i, j;
for (i = 0; i < data.length; i++) {
if (dataSet[i].projectID === props.tasksData.projectID) {
for (j = 0; j < dataSet[i].project_todos.length; j++) {
if (dataSet[i].project_todos[j].taskID === taskID) {
dataSet[i].project_todos.splice(j, 1);
console.log(dataSet[i].project_todos)
localStorage.setItem('projects', JSON.stringify(dataSet));
setTaskState(dataSet[i].project_todos)
}
}
}
}
props.update(props.updateData + 1)
}
function deleteTaskP(taskID) {
let dataSet = JSON.parse(localStorage.getItem('projects'))
let i, j;
for (i = 0; i < data.length; i++) {
if (dataSet[i].projectID === props.tasksData.projectID) {
for (j = 0; j < dataSet[i].project_inProgress.length; j++) {
if (dataSet[i].project_inProgress[j].taskID === taskID) {
dataSet[i].project_inProgress.splice(j, 1);
console.log(dataSet[i].project_inProgress)
localStorage.setItem('projects', JSON.stringify(dataSet));
setProgressState(dataSet[i].project_inProgress)
}
}
}
}
props.update(props.updateData + 1)
}
function deleteTaskS(taskID) {
let dataSet = JSON.parse(localStorage.getItem('projects'))
let i, j;
for (i = 0; i < data.length; i++) {
if (dataSet[i].projectID === props.tasksData.projectID) {
for (j = 0; j < dataSet[i].project_stuck.length; j++) {
if (dataSet[i].project_stuck[j].taskID === taskID) {
dataSet[i].project_stuck.splice(j, 1);
console.log(dataSet[i].project_stuck)
localStorage.setItem('projects', JSON.stringify(dataSet));
setStuckState(dataSet[i].project_stuck)
}
}
}
}
props.update(props.updateData + 1)
}
function deleteTaskC(taskID) {
let dataSet = JSON.parse(localStorage.getItem('projects'))
let i, j;
for (i = 0; i < data.length; i++) {
if (dataSet[i].projectID === props.tasksData.projectID) {
for (j = 0; j < dataSet[i].project_complete.length; j++) {
if (dataSet[i].project_complete[j].taskID === taskID) {
dataSet[i].project_complete.splice(j, 1);
console.log(dataSet[i].project_complete)
localStorage.setItem('projects', JSON.stringify(dataSet));
setCompleteState(dataSet[i].project_complete)
}
}
}
}
props.update(props.updateData + 1)
}
function moveToP(childData) {
//Find Current Task and splice it from array
let dataSet = JSON.parse(localStorage.getItem('projects'))
let theNew;
let theFinal;
let i, j;
for (i = 0; i < dataSet.length; i++) {
if (dataSet[i].projectID === props.tasksData.projectID) {
for (j = 0; j < dataSet[i].project_todos.length; j++) {
if (dataSet[i].project_todos[j].taskID === childData) {
theNew = dataSet[i].project_todos.splice(j, 1);
theFinal = {
inProgress_title: theNew[0].todo_title,
taskID: theNew[0].taskID,
inProgress_description: theNew[0].todo_description,
category: theNew[0].category,
time: theNew[0].time
}
dataSet[i].project_inProgress.push(theFinal);
localStorage.setItem('projects', JSON.stringify(dataSet))
setProgressState(dataSet[i].project_inProgress)
setTaskState(dataSet[i].project_todos)
console.log(theNew[0].todo_title)
}
}
}
}
for (i = 0; i < dataSet.length; i++) {
if (dataSet[i].projectID === props.tasksData.projectID) {
for (j = 0; j < dataSet[i].project_stuck.length; j++) {
if (dataSet[i].project_stuck[j].taskID === childData) {
theNew = dataSet[i].project_stuck.splice(j, 1);
theFinal = {
inProgress_title: theNew[0].stuck_title,
taskID: theNew[0].taskID,
inProgress_description: theNew[0].stuck_description,
category: theNew[0].category,
time: theNew[0].time
}
dataSet[i].project_inProgress.push(theFinal);
localStorage.setItem('projects', JSON.stringify(dataSet))
setProgressState(dataSet[i].project_inProgress)
setStuckState(dataSet[i].project_stuck)
}
}
}
}
props.update(props.updateData + 1)
}
function moveToStuck(childData) {
//Find Current Task and splice it from array
let dataSet = JSON.parse(localStorage.getItem('projects'))
let theNew;
let theFinal;
let i, j;
for (i = 0; i < dataSet.length; i++) {
if (dataSet[i].projectID === props.tasksData.projectID) {
for (j = 0; j < dataSet[i].project_todos.length; j++) {
if (dataSet[i].project_todos[j].taskID === childData) {
theNew = dataSet[i].project_todos.splice(j, 1);
theFinal = {
stuck_title: theNew[0].todo_title,
taskID: theNew[0].taskID,
stuck_description: theNew[0].todo_description,
category: theNew[0].category,
time: theNew[0].time
}
dataSet[i].project_stuck.push(theFinal);
localStorage.setItem('projects', JSON.stringify(dataSet));
setStuckState(dataSet[i].project_stuck);
setProgressState(dataSet[i].project_inProgress);
setTaskState(dataSet[i].project_todos);
}
}
for (j = 0; j < dataSet[i].project_inProgress.length; j++) {
if (dataSet[i].project_inProgress[j].taskID === childData) {
theNew = dataSet[i].project_inProgress.splice(j, 1);
theFinal = {
stuck_title: theNew[0].inProgress_title,
taskID: theNew[0].taskID,
stuck_description: theNew[0].inProgress_description,
category: theNew[0].category,
time: theNew[0].time
}
dataSet[i].project_stuck.push(theFinal);
localStorage.setItem('projects', JSON.stringify(dataSet));
setStuckState(dataSet[i].project_stuck);
setProgressState(dataSet[i].project_inProgress);
setTaskState(dataSet[i].project_todos);
}
}
}
}
props.update(props.updateData + 1)
}
function moveToComplete(childData) {
let dataSet = JSON.parse(localStorage.getItem('projects'))
let theNew;
let theFinal;
let i, j;
for (i = 0; i < dataSet.length; i++) {
if (dataSet[i].projectID === props.tasksData.projectID) {
for (j = 0; j < dataSet[i].project_todos.length; j++) {
if (dataSet[i].project_todos[j].taskID === childData) {
theNew = dataSet[i].project_todos.splice(j, 1);
theFinal = {
complete_title: theNew[0].todo_title,
taskID: theNew[0].taskID,
complete_description: theNew[0].todo_description,
category: theNew[0].category,
time: theNew[0].time
}
dataSet[i].project_complete.push(theFinal);
localStorage.setItem('projects', JSON.stringify(dataSet));
setStuckState(dataSet[i].project_stuck);
setProgressState(dataSet[i].project_inProgress);
setTaskState(dataSet[i].project_todos);
setCompleteState(dataSet[i].project_complete);
}
}
for (j = 0; j < dataSet[i].project_inProgress.length; j++) {
if (dataSet[i].project_inProgress[j].taskID === childData) {
theNew = dataSet[i].project_inProgress.splice(j, 1);
theFinal = {
complete_title: theNew[0].inProgress_title,
taskID: theNew[0].taskID,
complete_description: theNew[0].inProgress_description,
category: theNew[0].category,
time: theNew[0].time
}
dataSet[i].project_complete.push(theFinal);
localStorage.setItem('projects', JSON.stringify(dataSet));
setStuckState(dataSet[i].project_stuck);
setProgressState(dataSet[i].project_inProgress);
setTaskState(dataSet[i].project_todos);
setCompleteState(dataSet[i].project_complete);
}
}
for (j = 0; j < dataSet[i].project_stuck.length; j++) {
if (dataSet[i].project_stuck[j].taskID === childData) {
theNew = dataSet[i].project_stuck.splice(j, 1);
theFinal = {
complete_title: theNew[0].stuck_title,
taskID: theNew[0].taskID,
complete_description: theNew[0].stuck_description,
category: theNew[0].category,
time: theNew[0].time
}
dataSet[i].project_complete.push(theFinal);
localStorage.setItem('projects', JSON.stringify(dataSet));
setStuckState(dataSet[i].project_stuck);
setProgressState(dataSet[i].project_inProgress);
setTaskState(dataSet[i].project_todos);
setCompleteState(dataSet[i].project_complete);
}
}
}
}
props.update(props.updateData + 1)
}
function clearHandle(childData) {
if (childData === 1) {
setClearState(1)
}
else {
setClearState(0)
}
}
return (
<animated.div style={animateToDo} className="project-tasks-container" onClick={clearPopUps}>
<div className="project-title">{props.projectTitle} - To Do List</div>
<div className="main-task-wrapper">
<div className="project-task-container todo-list">
<p>To Do </p>
{taskState.map((task) => <PTask title={task.todo_title} description={task.todo_description} category={task.category} time={task.time} taskID={task.taskID} key={task.taskID} deleteTask={deleteTask} clearPopUp={clearState} clearHandle={clearHandle} moveToP={moveToP} moveToStuck={moveToStuck} moveToComplete={moveToComplete} />)}
<button className={buttonStyle} onClick={addTaskDrop}>Create Task {plusState()}</button>
{renderTaskCreation()}
</div>
<div className="project-task-container in-progress-list">
<p>In-Progress</p>
{progressState.map((task) => <PTask title={task.inProgress_title} description={task.inProgress_description} category={task.category} time={task.time} taskID={task.taskID} key={task.taskID} clearPopUp={clearState} deleteTask={deleteTaskP} clearHandle={clearHandle} moveToStuck={moveToStuck} moveToComplete={moveToComplete} />)}
</div>
<div className="project-task-container stuck-list">
<p>Stuck / Incomplete</p>
{stuckState.map((task) => <PTask title={task.stuck_title} description={task.stuck_description} category={task.category} time={task.time} taskID={task.taskID} key={task.taskID} clearPopUp={clearState} deleteTask={deleteTaskS} clearHandle={clearHandle} moveToStuck={moveToStuck} moveToP={moveToP} moveToComplete={moveToComplete} />)}
</div>
<div className="project-task-container completed-list">
<p>Completed</p>
{completeState.map((task) => <PTask title={task.complete_title} description={task.complete_description} category={task.category} time={task.time} taskID={task.taskID} key={task.taskID} clearPopUp={clearState} deleteTask={deleteTaskC} clearHandle={clearHandle} moveToStuck={moveToStuck} moveToP={moveToP} moveToComplete={moveToComplete} complete={1} />)}
</div>
</div>
</animated.div>
);
}
export default ProjectTasks;
|
$(function() {
$('.carousel').carousel(function(){
interval: 2000;
});
$('#myTab a:first').tab('show');
});
// Accordion no funciona
|
'use strict';
angular.module('banetApp')
.controller('HeaderCtrl', function ($scope,$location) {
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path().match('[/]+([A-z]*)')[0];
};
});
|
function hasBlacklistKeywords(bio) {
const blacklist = [
'trans',
'Tgirl',
'travesti',
'litrão',
'sigilo',
'cdzinha',
'pix',
'body positivity',
'sou mãe',
'bencong',
'f1',
'gay',
'lady boy',
'not a lady',
'not lady',
'not a girl',
'not girl',
'shemale',
];
for (item of blacklist) {
if (bio.toLowerCase().indexOf(item) !== -1) {
console.warn(`*** Skipping profile, matched blacklist keyword ${item} ***`);
return true;
}
}
return false;
}
function hasValidProfile() {
try {
return hasValidBiografy() && hasValidGender();
} catch (e) {
// console.log(e);
return true; // possible empty bio
}
}
function hasValidGender(){
const genderContainer = document.querySelector("#t1836739397 > div > div.App__body.H\\(100\\%\\).Pos\\(r\\).Z\\(0\\) > div > div > main > div > div > div.Pos\\(r\\)--ml.Z\\(1\\).Bgc\\(\\#fff\\).Ov\\(h\\).Expand.profileContent.Bdrs\\(8px\\)--ml.Bxsh\\(\\$bxsh-card\\)--ml > div > div.Bgc\\(\\#fff\\).Fxg\\(1\\).Z\\(1\\).Pb\\(100px\\) > div.D\\(f\\).Jc\\(sb\\).Us\\(n\\).Px\\(16px\\).Py\\(10px\\) > div > div.Fz\\(\\$ms\\) > div:nth-child(1) > div.Us\\(t\\).Va\\(m\\).D\\(ib\\).My\\(2px\\).NetWidth\\(100\\%\\,20px\\).C\\(\\$c-secondary\\)")
if (!genderContainer){
const LIKE_PROFILES_WITHOUT_GENDER = true
//console.log(`PERFIL SEM BIO ${LIKE_PROFILES_WITHOUT_BIO ? "LIKE": "DISLIKE"}`)
return LIKE_PROFILES_WITHOUT_GENDER;
}
const gender = genderContainer.text
return !hasBlacklistKeywords(gender)
}
function hasValidBiografy(){
const bioContainer = document.querySelector("#t1836739397 > div > div.App__body.H\\(100\\%\\).Pos\\(r\\).Z\\(0\\) > div > div > main > div > div > div.Pos\\(r\\)--ml.Z\\(1\\).Bgc\\(\\#fff\\).Ov\\(h\\).Expand.profileContent.Bdrs\\(8px\\)--ml.Bxsh\\(\\$bxsh-card\\)--ml > div > div.Bgc\\(\\#fff\\).Fxg\\(1\\).Z\\(1\\).Pb\\(100px\\) > div.P\\(16px\\).Us\\(t\\).C\\(\\$c-secondary\\).BreakWord.Whs\\(pl\\).Fz\\(\\$ms\\) > div");
if (!bioContainer){
const LIKE_PROFILES_WITHOUT_BIO = true
//console.log(`PERFIL SEM BIO ${LIKE_PROFILES_WITHOUT_BIO ? "LIKE": "DISLIKE"}`)
return LIKE_PROFILES_WITHOUT_BIO;
}
const bio = bioContainer.textContent;
openInstagramFromBio(bio);
return !hasBlacklistKeywords(bio)
}
function openInstagramFromBio(biografy){
const Reg = /[@].*/gm
const matchList = Reg.exec(biografy)
if(matchList.length){
const links = matchList.map( item => `https://www.instagram.com/${item.substring(1)}`)
links.forEach(link=> console.log(link))
}
}
function checkTinder() {
const base = "https://tinder.com/";
return window.location.href.startsWith(base + "app/recs") || window.location.href.startsWith(base + "app/matches");
}
function isMatch() {
return document.querySelector('a.active');
}
// prevent async execution
function pause(milliseconds) {
const dt = new Date();
while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}
function trickTinder() {
// Open profile bio
const infoButton = document.querySelector("#c464932099 > div > div.App__body.H\\(100\\%\\).Pos\\(r\\).Z\\(0\\) > div > div > main > div > div > div > div > div.Toa\\(n\\).Bdbw\\(--recs-gamepad-height\\).Bdbc\\(t\\).Bdbs\\(s\\).Bgc\\(\\#000\\).Wc\\(\\$transform\\).Prs\\(1000px\\).Bfv\\(h\\).Ov\\(h\\).W\\(100\\%\\).StretchedBox.Bdrs\\(8px\\) > div.Pos\\(a\\).D\\(f\\).Jc\\(sb\\).C\\(\\#fff\\).Ta\\(start\\).W\\(100\\%\\).Ai\\(fe\\).B\\(0\\).P\\(8px\\)--xs.P\\(16px\\).P\\(20px\\)--l.Cur\\(p\\).focus-button-style > button");
if (infoButton) {
infoButton.click();
}
pause(600);
// Like or deslike depending on validation
if (hasValidProfile()) {
try{
const likeButton = document.querySelector("#c464932099 > div > div.App__body.H\\(100\\%\\).Pos\\(r\\).Z\\(0\\) > div > div > main > div > div > div.Pos\\(f\\).W\\(100\\%\\).B\\(0\\).Z\\(1\\).Pe\\(n\\).Pos\\(a\\)--ml.Bdrsbend\\(8px\\)--ml.Bdrsbstart\\(8px\\)--ml.Bg\\(\\$transparent-white-gradient\\) > div > div > div:nth-child(4) > button");
likeButton.click();
} catch(er){
console.log(er, "Erro ao dar like")
}
const thereIsMatch = isMatch();
if (thereIsMatch) {
console.log('------------- IT\'S A MATCH ! -------------');
thereIsMatch.click();
}
} else {
const dislikeButton = document.querySelector("#t1836739397 > div > div.App__body.H\\(100\\%\\).Pos\\(r\\).Z\\(0\\) > div > div > main > div > div > div.Pos\\(f\\).W\\(100\\%\\).B\\(0\\).Z\\(1\\).Pe\\(n\\).Pos\\(a\\)--ml.Bdrsbend\\(8px\\)--ml.Bdrsbstart\\(8px\\)--ml.Bg\\(\\$transparent-white-gradient\\) > div > div > div:nth-child(2) > button");
dislikeButton.click();
}
// If reached max likes per day then show modal and get it's content...
// Check if there is any subscription button...
if (document.getElementsByClassName('productButton__subscriptionButton').length > 0) {
// We get the counter thing
const hms = document.getElementsByClassName('Fz($ml)')[0].textContent;
// Split it at the colons
const a = hms.split(':');
// Minutes are worth 60 seconds. Hours are worth 60 minutes. 1 second = 1kmilliseconds.
// Genius... rocket science...
const seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2])
return seconds * 1000;
}
}
// There is a lot more fun that can be achieved
// Need to add socket puppetry (VPNs solutions? several accounts?) - :D
// TODO: Need to accept automatically permissions except for
// TODO: Need to add ANN for fake pics
// TODO: Need to add RNN for fake messages
function getRandomPeriod() {
return Math.round(Math.random() * (2000 - 500)) + 500;
}
(function loopSasori() {
// A random period between 500ms and 2secs
let randomPeriod = getRandomPeriod();
setTimeout(function () {
randomPeriod = undefined;
if (checkTinder()) {
const delay = trickTinder();
if (delay) {
console.log('Too many likes for now, have to wait: ' + delay + ' ms');
randomPeriod = delay;
}
}
if (!randomPeriod) {
loopSasori();
} else {
setTimeout(loopSasori, randomPeriod);
}
}, randomPeriod);
}());
|
import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import common from './common'
import auth from './auth'
import home from './home'
import article from './article'
import articleList from './articleList'
export default combineReducers({
common,
auth,
home,
article,
articleList,
router: routerReducer
})
|
const {
ChoiceFactory,
ChoicePrompt,
ComponentDialog,
TextPrompt,
WaterfallDialog,
} = require('botbuilder-dialogs');
const fetch = require("node-fetch");
const CONFIRM_PROMPT_FINAL = 'CONFIRM_PROMPT_FINAL';
const FIRST_NAME_PROMPT = 'FIRST_NAME_PROMPT';
const SECOND_NAME_PROMPT = 'SECOND_NAME_PROMPT';
const WATERFALL_DIALOG = 'WATERFALL_DIALOG';
class LoveApiDialog extends ComponentDialog{
constructor(id) {
super(id || 'loveApiDialog')
this.addDialog(new TextPrompt(FIRST_NAME_PROMPT));
this.addDialog(new TextPrompt(SECOND_NAME_PROMPT));
this.addDialog(new ChoicePrompt(CONFIRM_PROMPT_FINAL));
this.addDialog(new WaterfallDialog(WATERFALL_DIALOG, [
this.firstNameStep.bind(this),
this.SecondNameStep.bind(this),
this.confirmStep.bind(this),
this.finalStep.bind(this)
]));
this.initialDialogId = WATERFALL_DIALOG;
}
async firstNameStep(step){
const apiDetails = step.options;
if (!apiDetails.firstName) {
// const promptOptions = { prompt: 'Por favor insira o primeiro nome: ', retryPrompt: 'Nome não foi encontrado na base de dados do IBGE. Digite novamente:' };
return await step.prompt(FIRST_NAME_PROMPT, 'Por favor insira o primeiro nome: ');
}
return await step.next(apiDetails.firstName);
}
async SecondNameStep(step){
const apiDetails = step.options;
step.values.firstName = step.result;
if (!apiDetails.secondName) {
// const promptOptions = { prompt: 'Por favor insira o segundo nome: ', retryPrompt: 'Nome não foi encontrado na base de dados do IBGE. Digite novamente:' };
return await step.prompt(SECOND_NAME_PROMPT, 'Por favor insira o segundo nome: ');
}
return await step.next(apiDetails.secondName);
}
async confirmStep(step) {
step.values.secondName = step.result;
return await step.prompt(CONFIRM_PROMPT_FINAL, {
prompt: 'Confirma as informações enviadas: ',
choices: ChoiceFactory.toChoices(['Sim', 'Não'])
});
}
async finalStep(step) {
if (step.result.value.toLowerCase() == 'sim') {
const data = {};
const dataApi = await this.runApi(step.values.firstName,step.values.secondName);
data.firstName = step.values.firstName;
data.secondName = step.values.secondName;
data.percentage = dataApi.percentage
data.result = dataApi.result
let msg = `O resultado de ${ data.firstName } e ${ data.secondName } para combitiblidade no amor é de: ${ data.percentage}%
\n ${data.result}`;
msg += '.';
await step.context.sendActivity(msg);
return await step.endDialog( data);
}
return await step.endDialog();
}
async runApi(first,second){
let myHeaders = new fetch.Headers({
"x-rapidapi-key": "eab655801dmsh640300e5ef6208cp159a46jsne85f2ecacb6c",
"x-rapidapi-host": "love-calculator.p.rapidapi.com",
"useQueryString": true
});
let options = {
method:'GET',
headers: myHeaders
}
let result = {}
await fetch(`https://love-calculator.p.rapidapi.com/getPercentage?fname=${first}&sname=${second}`,options)
.then(res => res.json())
.then(data => {
result.percentage = data.percentage;
result.result = data.result;
})
.catch(erro =>{
throw new Error(erro)
});
return result;
}
}
module.exports.LoveApiDialog = LoveApiDialog;
|
import React, {
Component
} from 'react';
import fetchMethod from '../../getdataCom';
import {
ListView,
List,
SearchBar
} from 'antd-mobile';
const {
Item
} = List;
class Song extends Component {
render() {
let {
list
} = this.props.resdata;
// console.log(list);
return (
<List>
{list.map((item)=>{
return (
<div className='list-rankitem' key = {item.imgurl}>
<Item
thumb={item.imgurl.replace('{size}',400)}
arrow="horizontal"
wrap
onClick={() => {}}
>
<div className='song-info'>
<span>{item.specialname}</span>
<span><i className='iconfont icon-erji'></i>{item.playcount}</span>
</div>
</Item>
</div>
)
})}
</List>
)
}
}
export default fetchMethod('getSong', Song);
|
/**
* Created by griga on 11/30/15.
*/
import React from 'react'
import axios from 'axios'
import {SubmissionError} from 'redux-form'
import {connect} from 'react-redux'
import moment from 'moment'
import contextmenu from 'ui-contextmenu'
import Loader, {Visibility as LoaderVisibility} from '../../../../components/Loader/Loader'
import WidgetGrid from '../../../../components/widgets/WidgetGrid'
import JarvisWidget from '../../../../components/widgets/JarvisWidget'
import Datatable from '../../../../components/tables/Datatable'
import Msg from '../../../../components/i18n/Msg'
import LanguageStore from '../../../../components/i18n/LanguageStore'
import Moment from '../../../../components/utils/Moment'
import StudentForm from './StudentForm'
import StudentDocumentsForm from './StudentDocumentsForm'
import EditGeneralInfo from './EditGeneralInfo'
import PreviousSchoolsForm from './PreviousSchoolsForm'
import SiblingDetailsForm from './SiblingDetailsForm'
import RelativesForm from './RelativesForm'
import ParentsForm from './ParentsForm'
import EmergencyContactsForm from './EmergencyContactsForm'
import SpecialServicesForm from './SpecialServicesForm'
import MedicalDetailsForm from './MedicalDetailsForm'
import submit, {remove, submitPreviousSchool, submitSiblingDetail, submitStudentRelative, submitStudentParent, submitStudentEmergencyContactDetail, submitStudentSpecialSevices, submitStudentMedicalDetails } from './submit'
import mapForCombo, {renderDate, getWebApiRootUrl, instanceAxios} from '../../../../components/utils/functions'
//http://live.datatables.net/caderego/1/edit
//https://github.com/mar10/jquery-ui-contextmenu
class StudentsPage extends React.Component {
constructor(props){
super(props);
this.state = {
studentId: 0,
singleEditMode: 0,
nationalities: [],
countries: [],
popupPageName: '',
refreshGrid: false
}
this.handleClick = this.handleClick.bind(this);
this.renderModalBody = this.renderModalBody.bind(this);
}
componentWillMount() {
LoaderVisibility(true);
}
renderModalBody(popupPageName, studentId){
//console.log('this.state.popupPageName ==> ', this.state.popupPageName);
var modalBody;
//LoaderVisibility(true);
// this.setState({refreshGrid:false});
if(popupPageName == "EditText"){
//this.setState({refreshGrid:true});
modalBody = <EditGeneralInfo studentId={studentId}
//nationalities={this.state.nationalities}
//genderOptions={this.state.genderOptions}
//countries={this.state.countries}
onSubmit={submit} />
}
else if(popupPageName == "DocumentsText"){
modalBody = <StudentDocumentsForm
studentId={studentId}
//onSubmitPreviousSchool={submitPreviousSchool}
/>
}
else if(popupPageName == "PreviousSchoolDetailsText"){
modalBody = <PreviousSchoolsForm
studentId={studentId}
onSubmitPreviousSchool={submitPreviousSchool} />
}
else if(popupPageName == "SiblingDetailsText"){
modalBody = <SiblingDetailsForm
studentId={studentId}
onSubmitSiblingDetail={submitSiblingDetail} />
}
else if(popupPageName == "RelativesDetailsText"){
modalBody = <RelativesForm
studentId={studentId}
onSubmitStudentRelative={submitStudentRelative} />
}
else if(popupPageName == "ParentsDetailsText"){
modalBody = <ParentsForm
studentId={studentId}
onSubmitStudentParent={submitStudentParent} />
}
else if(popupPageName == "EmergencyContactsText"){
modalBody = <EmergencyContactsForm
studentId={studentId}
onSubmitStudentEmergencyContactDetail={submitStudentEmergencyContactDetail} />
}
else if(popupPageName == "SpecialServicesText"){
modalBody = <SpecialServicesForm
studentId={studentId}
onSubmitStudentSpecialSevices={submitStudentSpecialSevices} />
}
else if(popupPageName == "MedicalDetailsText"){
modalBody = <MedicalDetailsForm
studentId={studentId}
onSubmitStudentMedicalDetails={submitStudentMedicalDetails} />
}
// console.log('hellloooooooooooooooooooooooooooo ', studentId);
//LoaderVisibility(false);
//this.setState({popupPageName:''});
return modalBody;
}
componentDidMount(){
console.log('componentDidMount --> StudentPage');
//let messageText = LanguageStore.getData().phrases["AddNewText"]
$('#StudentsGrid').contextmenu({
delegate: "td",
autoFocus: true,
preventContextMenuForPopup: true,
preventSelect: true,
taphold: true,
menu: [
{title: LanguageStore.getData().phrases["EditText"], cmd: "EditText", uiIcon: "ui-icon-pencil"},
{title: LanguageStore.getData().phrases["DocumentsText"], cmd: "DocumentsText", uiIcon: "ui-icon-document"},
{title: LanguageStore.getData().phrases["ParentsDetailsText"], cmd: "ParentsDetailsText", uiIcon: "ui-icon-person"},
{title: LanguageStore.getData().phrases["EmergencyContactsText"], cmd: "EmergencyContactsText", uiIcon: "ui-icon-contact"},
{title: "----"},
{title: LanguageStore.getData().phrases["PreviousSchoolDetailsText"], cmd: "PreviousSchoolDetailsText", uiIcon: "ui-icon-disk"},
{title: LanguageStore.getData().phrases["SiblingDetailsText"], cmd: "SiblingDetailsText", uiIcon: " ui-icon-home"}, //, disabled: true
{title: LanguageStore.getData().phrases["RelativesDetailsText"], cmd: "RelativesDetailsText", uiIcon: "ui-icon-folder-collapsed"},
{title: LanguageStore.getData().phrases["SpecialServicesText"], cmd: "SpecialServicesText", uiIcon: "ui-icon-star"},
{title: LanguageStore.getData().phrases["MedicalDetailsText"], cmd: "MedicalDetailsText", uiIcon: "ui-icon-tag"},
// {title: "More", children: [
// {title: "Use an 'action' callback", action: function(event, ui) {
// alert("action callback sub1");
// } },
// {title: "Tooltip (static)", cmd: "sub2", tooltip: "Static tooltip"},
// {title: "Tooltip (dynamic)", tooltip: function(event, ui){ return "" + Date(); }},
// {title: "Custom icon", cmd: "browser", uiIcon: "ui-icon custom-icon-firefox"},
// {title: "Disabled (dynamic)", disabled: function(event, ui){
// return false;
// }}
// ]}
],
select: function(event, ui) {
var coltext = ui.target.text();
var colvindex = ui.target.parent().children().index(ui.target);
var rowindex = ui.target.parent().index();
var colindex = $('table thead tr th:eq('+colvindex+')').data('column-index');
var id = $('table tbody tr:eq('+rowindex+') td:last-child a').data('tid');
//alert(colvindex);
//alert(rowindex);
//alert(id);
//id = 55;
//console.log(ui.cmd);
this.setState({popupPageName:ui.cmd, studentId:id, refreshGrid:(ui.cmd=='EditText'?true:false)});
$('#StudentPopup').modal('show');
// switch(ui.cmd){
// case "EditGeneralInfo":
// this.setState({popupPageName:'', studentId:id})
// //alert('^' + coltext + '$ ' + colindex);
// break;
// case "PreviousSchoolsForm":
// alert('PreviousSchoolsForm');
// break;
// }
}.bind(this),
beforeOpen: function(event, ui) {
var $menu = ui.menu,
$target = ui.target,
extraData = ui.extraData;
//ui.menu.zIndex( $(event.target).zIndex() + 1);
//ui.menu.zIndex(9999);
}
});
$('#StudentsGrid').on('click', 'td', function(event) {
if ($(this).find('#dele').length > 0) {
var id = $(this).find('#dele').data('tid');
remove(id, $(this));
}
});
// call before modal open
$('#StudentPopup').on('show.bs.modal', function (e) {
//LoaderVisibility(true);
var button = $(e.relatedTarget); // Button that triggered the modal
var studentId = button.data('id'); // Extract info from data-* attributes
// console.log('button.data(single-edit)', button.data('single-edit'));
this.setState({singleEditMode: button.data('single-edit')});
this.setState({studentId});
// just for checking ????
//this.setState({studentId:5});
}.bind(this));
// call on modal close
$('#StudentPopup').on('hidden.bs.modal', function (e) {
this.setState({studentId : 0, popupPageName:''});
if(this.state.refreshGrid){
var table = $('#StudentsGrid').DataTable();
table.clear();
table.ajax.reload( null, false ); // user paging is not reset on reload
}
}.bind(this));
//https://jsonplaceholder.typicode.com/posts
instanceAxios.get('/api/nationalities/')
.then(res=>{
const nationalities = mapForCombo(res.data);
this.setState({nationalities});
});
instanceAxios.get('/api/countries/')
.then(res=>{
const countries = mapForCombo(res.data);
this.setState({countries});
});
LoaderVisibility(false);
}
handleClick(e, data) {
console.log(data);
}
render() {
const { studentId, popupPageName } = this.state;
const { isLoading } = this.props;
var self = this;
return (
<div id="content">
<WidgetGrid>
{/* START ROW */}
<div className="row">
{/* NEW COL START */}
<article className="col-sm-12 col-md-12 col-lg-12">
{/* Widget ID (each widget will need unique ID)*/}
<JarvisWidget colorbutton={false} editbutton={false} color="blueLight"
custombutton={false} deletebutton={false} >
<header>
<span className="widget-icon"> <i className="fa fa-edit"/> </span>
<h2><Msg phrase="Students" /></h2>
</header>
{/* widget div*/}
<div>
{/* widget content */}
<div className="widget-body no-padding">
<div className="widget-body-toolbar">
<div className="row">
<div className="col-xs-9 col-sm-5 col-md-5 col-lg-5">
</div>
<div className="col-xs-3 col-sm-7 col-md-7 col-lg-7 text-right">
<button className="btn btn-primary" data-toggle="modal"
data-target="#StudentPopup">
<i className="fa fa-plus"/>
<span className="hidden-mobile"><Msg phrase="Add New" /></span>
</button>
</div>
</div>
</div>
<Loader isLoading={isLoading} />
{/* */}
<Datatable id="StudentsGrid"
options={{
ajax: {"url": getWebApiRootUrl() +'/api/Students', "dataSrc": ""},
//1. PAGING-SETTING SAMPLE lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
//createdRow: function ( row, data, index ) {
//if ( data[5].replace(/[\$,]/g, '') * 1 > 150000 ) {
// $('td', row).eq(2).addClass('text-success');
//}
//},
columnDefs: [
{
"type": "date",
"render": function ( data, type, row ) {
//return moment(data).format('Do MMM YYYY' || 'llll')
return renderDate(data);
},
"targets": 6
}/*,
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return '<a data-toggle="modal" data-single-edit="1" title="Edit" data-id="' + data + '" data-target="#StudentPopup"><i id="edi" class=\"glyphicon glyphicon-edit\"></i><span class=\"sr-only\">Edit</span></a>';
},
"className": "dt-center",
"sorting": false,
"targets": 7
},
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return '<a data-toggle="modal" data-single-edit="0" title="Manage" data-id="' + data + '" data-target="#StudentPopup"><i id="edi" class=\"glyphicon glyphicon-list-alt\"></i><span class=\"sr-only\">Edit</span></a>';
},
"className": "dt-center",
"sorting": false,
"targets": 8
}*/
,{
"render": function ( data, type, row ) {
return '<a id="dele" data-tid="' + data + '"><i class=\"glyphicon glyphicon-trash\"></i><span class=\"sr-only\">Edit</span></a>';
}.bind(self),
"className": "dt-center",
"sorting": false,
"targets": 7
}
],
columns: [
//{
// "className": 'details-control',
// "orderable": false,
// "data": null,
// "defaultContent": ''
//},
{data: "Code"},
{data: "FullName"},
{data: "FullNameAr"},
{data: "Email"},
{data: "StudentIDNo"},
{data: "Gender"},
{data: "DOB"},
/*{data: "StudentId"},
{data: "StudentId"},*/
{data: "StudentId"}
],
buttons: [
'copy', 'excel', 'pdf'
]
}}
paginationLength={true}
//refresh={this.state.refresh}
className="table table-striped table-bordered table-hover"
width="100%">
<thead>
<tr>
<th data-hide="mobile-p"><Msg phrase="CodeText"/></th>
<th data-hide="mobile-p"><Msg phrase="FullNameText"/></th>
<th data-class="expand"><Msg phrase="FullNameArText"/></th>
<th data-hide="mobile-p"><Msg phrase="EmailAddressText"/></th>
<th data-hide="mobile-p"><Msg phrase="IdentityCardNumberText"/></th>
<th data-hide="mobile-p"><Msg phrase="GenderText"/></th>
<th data-hide="mobile-p"><Msg phrase="DOBText"/></th>
{/* <th data-hide="mobile-p"></th>
<th data-hide="mobile-p"></th> */}
<th data-hide="mobile-p"></th>
</tr>
</thead>
{/* <tbody>
<tr>
<td >a</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td >a12</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody> */}
</Datatable>
</div>
{/* end widget content */}
</div>
{/* end widget div */}
</JarvisWidget>
{/* end widget */}
</article>
{/* END COL */}
</div>
{/* END ROW */}
</WidgetGrid>
{/* end widget grid */}
<div className="modal fade" id="StudentPopup" tabIndex="-1" role="dialog"
data-backdrop="static" data-keyboard="false"
aria-labelledby="StudentPopupLabel" aria-hidden="true">
<div className="modal-dialog modal-lg">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 className="modal-title" id="StudentPopupLabel">
{ popupPageName != '' ? <Msg phrase={popupPageName} /> : <Msg phrase="Add New Student"/> }
</h4>
</div>
<div className="modal-body">
{
popupPageName != '' ?
this.renderModalBody(popupPageName, studentId)
:
<StudentForm studentId={0}
nationalities={this.state.nationalities}
countries={this.state.countries}
onSubmit={submit} />
}
</div>
</div>
{/* /.modal-content */}
</div>
{/* /.modal-dialog */}
</div>
{/* /.modal */}
</div>
)
}
}
export default StudentsPage;
|
var utils = {
getLink(link) {
return link.substring(link.indexOf("<")+1,link.indexOf(">"));
}
};
export default utils;
|
App.Day = DS.Model.extend({
date : DS.attr('string'),
title : DS.attr('object')
});
App.Day.FIXTURES = [
{id: 1, title: {id:1, SV: 'Idag', EN: 'Today'}, date: '2014-01-01'},
{id: 2, title: {id:2, SV: 'Imorgon', EN: 'Tomorrow'}, date: '2014-01-03'},
{id: 3, title: {id:3, SV: 'Torsdag 2014-01-04', EN: 'Thursday 2014-01-04'}, date: '2014-01-04'},
{id: 4, title: {id:4, SV: 'Fredag 2014-01-04', EN: 'Friday 2014-01-04'}, date: '2014-01-04'}
];
|
/**
* @param {number[]} nums
* @return {number[]}
*/
var findDuplicates = function(nums) {
let duplicates = [];
let numObj = {};
for (let num of nums) {
numObj[num] = numObj[num] + 1 || 1;
}
for (let key in numObj) {
if (numObj[key] === 2) {
duplicates.push(key);
}
}
return duplicates;
};
|
import * as PropTypes from 'prop-types';
import * as React from 'react';
import Label from '../label/label';
import { uuid4 } from '../../../utils/utils';
/**
* @uxpincomponent
*/
export default class NumberInput extends React.Component {
constructor(props) {
super(props);
this.state = { id: uuid4() };
}
componentDidMount() {
const numberInput = document.getElementById(`${this.state.id}`);
if (numberInput) {
numberInput.addEventListener('chiChange', () => {
this.props.valueChange();
});
setTimeout(() => {
const input = numberInput.querySelector('input');
const self = this;
if (input) {
input.addEventListener('focus', () => {
self.props.focus();
});
input.addEventListener('blur', () => {
self.props.focusLost();
});
input.addEventListener('input', () => {
self.props.input();
});
}
}, 1000);
}
}
render() {
console.log(this.props.required);
const label = this.props.label
? (
<Label
htmlFor={this.state.id}
className="chi-label"
required={this.props.required}
label={this.props.label}>
</Label>
)
: null;
const size = this.props.size ? this.props.size.split(' ')[0] : null;
return (
<div className="chi-form__item">
{label}
<chi-number-input
id={this.state.id}
disabled={this.props.disabled}
expanded={this.props.expanded}
size={size}
min={this.props.min}
max={this.props.max}
onClick={this.props.click}
onMouseEnter={this.props.mouseOver}
onMouseLeave={this.props.mouseLeave}
onMouseDown={this.props.mouseDown}
onMouseUp={this.props.mouseUp}
value={this.props.startValue}>
</chi-number-input>
</div>
);
}
}
/* eslint-disable */
NumberInput.propTypes = {
size: PropTypes.oneOf(['sm (24px)', 'md (32px)', 'lg (40px)', 'xl (48px)']),
expanded: PropTypes.bool,
label: PropTypes.string,
required: PropTypes.oneOf(['none', 'required', 'optional']),
disabled: PropTypes.bool,
startValue: PropTypes.string,
min: PropTypes.number,
max: PropTypes.number,
click: PropTypes.func,
focus: PropTypes.func,
focusLost: PropTypes.func,
input: PropTypes.func,
mouseDown: PropTypes.func,
mouseLeave: PropTypes.func,
mouseOver: PropTypes.func,
mouseUp: PropTypes.func,
valueChange: PropTypes.func,
};
/* eslint-enable */
NumberInput.defaultProps = {
disabled: false,
expanded: false,
size: 'md',
label: 'Label',
required: 'none',
startValue: '0',
};
|
import React, { PureComponent } from 'react'
import { Col, Row } from 'antd'
import GithubEmoji from '../../../components/GithubEmoji'
const text = '🤣🙌💚💛👏😉💯💕💞💘💙💙🖤💜❤️😍😻💓💗😋😇😂😹😘💖😁😀🤞😲😄😊👍😌😃😅✌️🤗💋😗😽😽🤠😙😺👄😸😏😼👌😎😆😛🙏🤝🙂🤑😝😐😑🤤😤🙃🤡😶😪😴😵😓👊😦😷🤐😜🤓👻😥🙄🤔🤒🙁😔😯☹️☠️😰😩😖😕😒😣😢😮😿🤧😫🤥😞😬👎💀😳😨🤕🤢😱😭😠😈😧💔😟🙀💩👿😡😾🖕'
const emojis = []
for (let i = 0; i < text.length; i += 1) {
if (text.codePointAt(i) > 0xffff) {
emojis.push(text.codePointAt(i))
}
}
export default class Index extends PureComponent {
render() {
const { aa } = this.props
return (
<div
style={ {
textAlign: 'center',
} }
>
emoji
<hr/>
<Row>
<Col>
{
emojis.map(emoji => <GithubEmoji codePoint={ emoji }/>)
}
</Col>
<hr/>
<Col>{ text }</Col>
</Row>
</div>
)
}
}
|
/*
* This javascript file is necessary for the functioning of the theme
*/
$(document).ready(function(){
$("ul.sf-menu").superfish(); // Superfish Menus!
$(".sortable").sortable({ // Makes a list sortable
revert: true
});
$("#loginarrow").click(function() {
$("#logindrop").toggle("slow");
return false;
});
$("#search").click(function() {
$("#searchdrop").toggle("slow");
return false;
});
$(".notification").click(function() {
$(this).fadeOut("slow");
});
});
|
exports.menu = (id, BotName, tampilTanggal, tampilWaktu, instagram, whatsapp, kapanbotaktif) => {
return ` 🤖 *${BotName}* 🤖
*${tampilTanggal}*
*${tampilWaktu}*
*Command*
!sticker
_${BotName}_ akan membuatkan sticker dari gambar yang kamu kirimkan
Pengggunaan : Kirimkan gambarmu dengan caption !sticker
!igstalk
_${BotName}_ untuk mengambil data instagram Full Info
!ocr
_${BotName}_ untuk melihat text dari gambar yang kamu kirimkan
Pengggunaan : Kirimkan gambarmu dengan caption !ocr
!pantun
_${BotName}_ akan mengirimkanmu pantun secara random
!animepict
_${BotName}_akan mengirimkanmu gambar anime secara random
!nulis <teks>
_${BotName}_ akan menuliskan teks yang kamu kirimkan
Contoh: !nulis pasti nana bangka dadang ko bang jamping jamping
!quotes
_${BotName}_ akan mencarikanmu quotes secara random
!pict <cewek/cowok>
_${BotName}_ akan mengirimkanmu gambar cewek/cowok secara random
Contoh: !pict cowok
!say <teks>
_${BotName}_ akan mengirimkan kembali teks yang kamu kirimkan
Contoh: !say buset bang
!lirik <penyanyi-judul lagu>
_${BotName}_ akan mengirimkanmu lirik lagu yang kamu inginkan
contoh : !lirik Lisa-Gurenge
!alay <teks>
_${BotName}_ akan mengubah teks yang kamu kirimkan menjadi alay
contoh : !alay ampun bang jago
*Islam*
!sholat <daerah>
_${BotName}_ akan mengirimkan jadwal sholat sesuai dengan daerah yang kamu kirimkan
Penggunaan : !sholat + daerah kamu
Contoh : !sholat Bekasi
!quran
_${BotName}_ akan mengirimkanmu ayat Al-Quran secara random
*Downloader*
!ytmp4 <link>
_${BotName}_ akan mendownloadkan video youtube sesuai dengan link yang kamu kirimkan.
Contoh: !ytmp4 https://youtu.be/linkamu
!ytmp3 <link>
_${BotName}_ akan mengubah video youtube menjadi audio sesuai dengan link yang kamu kirimkan
Contoh: !ytmp3 https://youtu.be/linkamu
!twt <link>
_${BotName}_ akan mengirimkanmu foto/video dari link ig yang kamu kirimkan
Contoh: !twt https://twitter.com/linkamu
!tiktok <link>
_${BotName}_ akan mengirimkanmu video dari link tiktok yang kamu kirimkan
*Education*
!wiki <yang kamu cari>
Contoh: !wiki Adolf Hitler
!covid
menampilkan data tentang COVID-19 di Indonesia
*Primbon*
!nama <namakamu>
Contoh : !nama Adit
!pasangan <namamu & pasangan>
Contoh : !pasangan covad & covid
Instagram : ${instagram}
WhatsApp : ${whatsapp}
`
}
|
exports.name = 'Bill';
exports.test = function(){
console.log('test')
};
console.log(exports);
|
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
const encodingAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"; //must be length 2^6 = 64
function encode(booleans) {
const bits = booleans.map(Number).join('')
.padEnd(Math.ceil(booleans.length / 6.0) * 6, "0"); // pad with 0's make sure the length is a multiple of 6
const bitGroups = Array.from(bits.matchAll(/[01]{6}/g)); // groups of 6 bits
const indexes = bitGroups.map(sixBits => parseInt(sixBits, 2)); // parse each 6 bits to a number (used as index)
const letters = indexes.map(index => encodingAlphabet[index]); // get the letter corresponding to each index
return letters.join('');
}
function decode(string) {
const letters = string.split('');
const indexes = letters.map(letter => encodingAlphabet.indexOf(letter));
const bitGroups = indexes.map(index => index.toString(2).padStart(6, "0"));
const bits = bitGroups.join('');
const booleans = bits.split('').map(b => b == '1');
return booleans;
}
const workingSaveId = "__working__";
function saveCheckboxes(name) {
let toSave = encode(Array.from(checkboxes, c => c.checked));
if (!name) parent.location.hash = toSave;
localStorage.setItem(name || workingSaveId, toSave);
}
function loadCheckboxes(name) {
let encodedBooleans;
if (!name) {
// try hash first, then local storage
encodedBooleans = parent.location.hash.substr(1) || localStorage.getItem(workingSaveId);
}
else {
encodedBooleans = localStorage.getItem(name);
}
if (encodedBooleans != null) {
let booleans = decode(encodedBooleans);
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = booleans[i];
checkboxes[i].dispatchEvent(new Event("change"));
}
}
}
// listen to any changes
const onCheckboxChanged = debounce(() => saveCheckboxes(), 50);
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("change", onCheckboxChanged);
}
loadCheckboxes();
|
public var sprayAmount : float;
// Attach this script to a camera and it will paint black pixels in 3D
// on whatever the user clicks. Make sure the mesh you want to paint
// on has a mesh collider attached.
function Start () {
sprayAmount = 0;
}
function Update () {
// Only when we press the mouse
if (!Input.GetMouseButton (0) || !(sprayAmount > 0))
return;
// Only if we hit something, do we continue
var hit : RaycastHit;
if (!Physics.Raycast(camera.ScreenPointToRay(Vector3(Screen.width * 0.5, Screen.height * 0.5,0)),hit,7.0f)) {
Debug.Log("Raycast Missed!");
return;
}
// Just in case, also make sure the collider also has a renderer
// material and texture. Also we should ignore primitive colliders.
var renderer : Renderer = hit.collider.renderer;
var boxCollider = hit.collider as MeshCollider;
if (renderer == null || renderer.sharedMaterial == null ||
renderer.sharedMaterial.mainTexture == null || boxCollider == null) {
return;
}
// Now draw a pixel where we hit the object
var tex : Texture2D = renderer.material.mainTexture;
var pixelUV = hit.textureCoord;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
tex.SetPixel(pixelUV.x, pixelUV.y, Color.red);
tex.Apply();
sprayAmount -= 1;
Debug.Log(sprayAmount);
}
|
// pages/admin/demand_look/demand_look.js
Page({
/**
* 页面的初始数据
*/
data: {
lookDemand:{}
},
//点击选择
stateDemand: function (e) {
let state = e.detail.value.state
console.log(state)
let lookDemand = wx.getStorageSync('look')
// 如果在需求点通过,则添加素材表
const db = wx.cloud.database();
if(state == 'passed'){
console.log(lookDemand._id)
db.collection('material').add({
data: {
demandID: lookDemand.demandID,
userID: lookDemand.userID,
username: lookDemand.username,
ader_name: lookDemand.ader_name,
platform: lookDemand.platform,
age: lookDemand.age,
amount: lookDemand.amount,
city: lookDemand.city,
note: lookDemand.note,
product: lookDemand.product,
sex: lookDemand.male,
state: lookDemand.state,
total: lookDemand.total,
unit:lookDemand.unit,
date:lookDemand.date,
state:''
}
})
}
db.collection('demand').doc(lookDemand._id).update({
data: {
state: state
},
success: function (res) {
wx.showToast({
title: '审核完成!',
icon: 'success',
duration: 2000
})
}
})
wx: wx.removeStorageSync('look')
wx.reLaunch({
url: '../demand_manage/demand_manage'
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
//获取刚刚点击的需求表的缓存所有信息
let lookDemand = wx.getStorageSync('look')
this.setData({
lookDemand: lookDemand
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
import { play, render } from '../crude-wilderness-dom'
import { shape, timeline } from '../../src'
const from = {
type: 'g',
shapes: [
{
type: 'rect',
x: 0,
y: 0,
width: 10,
height: 10,
fill: 'yellow'
},
{
type: 'rect',
x: 90,
y: 0,
width: 10,
height: 10,
fill: 'red'
},
{
type: 'rect',
x: 0,
y: 90,
width: 10,
height: 10,
fill: 'blue'
},
{
type: 'rect',
x: 90,
y: 90,
width: 10,
height: 10,
fill: 'green'
}
]
}
const to = {
type: 'rect',
x: 40,
y: 40,
width: 20,
height: 20,
fill: '#3C9632'
}
const morph = shape(from, to)
const animation = timeline(morph, {
alternate: true,
duration: 3000,
iterations: Infinity
})
render(document.querySelector('svg'), animation)
play(animation)
|
const express = require('express')
app = express()
firebase = require("firebase");
app.set('view engine', 'ejs')
app.use(express.static('public'))
// FIREBASE
const config = {
apiKey: "AIzaSyB1LDDiAPPx1VMdhaU3aS3xKmIkZupXgC4",
authDomain: "expressblog-2ea6a.firebaseapp.com",
databaseURL: "https://expressblog-2ea6a.firebaseio.com",
projectId: "expressblog-2ea6a",
storageBucket: "expressblog-2ea6a.appspot.com",
messagingSenderId: "608350661426"
};
const defaultApp = firebase.initializeApp(config);
const defaultDatabase = firebase.database();
console.log(defaultDatabase)
// ROUTES
app.get('/', (req, res) => {
res.render('pages/index')
})
app.post('/search', (req, res) => {
})
app.listen(3000, () => {
console.log("Server started on 3000")
})
|
import React, { memo } from 'react';
import PropTypes from 'prop-types';
import { Route } from 'react-router-dom';
import { useAuthDataContext } from '../../auth/AuthDataProvider';
import { SignIn } from '../../containers/SignIn';
const PrivateRoute = ({ component, ...options }) => {
const { user } = useAuthDataContext();
const finalComponent = user ? component : SignIn;
return <Route {...options} component={finalComponent} />;
};
PrivateRoute.propTypes = {
component: PropTypes.any.isRequired,
};
export default memo(PrivateRoute);
|
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const BudgetSchema = new Schema({
createdAt: Date,
updatedAt: Date,
author: { type: String, default: "None" },
housingName: { type: String, default: "housing" },
housingAmount: { type: String, default: 0 },
housingCategory: { type: String, default: "None" },
foodName: { type: String, default: "food" },
foodAmount: { type: String, default: 0 },
foodCategory: { type: String, default: "None" },
transportationName: { type: String, default: "transportation" },
transportationAmount: { type: Number, default: 0 },
transportationCategory: { type: String, default: "None" },
insuranceName: { type: String, default: "insurance" },
insuranceAmount: { type: Number, default: 0 },
insuranceCategory: { type: String, default: "None" },
clothingName: { type: String, default: "clothing" },
clothingAmount: { type: Number, default: 0 },
clothingCategory: { type: String, default: "None" },
entertainmentName: { type: String, default: "entertainment" },
entertainmentAmount: { type: Number, default: 0 },
entertainmentCategory: { type: String, default: "None" },
savingName: { type: String, default: "saving" },
savingAmount: { type: Number, default: 0 },
savingCategory: { type: String, default: "None" }
});
BudgetSchema.pre("save", function(next) {
// SET createdAt AND updatedAt
const now = new Date();
this.updatedAt = now;
if (!this.createdAt) {
this.createdAt = now;
}
next();
});
module.exports = mongoose.model("Budget", BudgetSchema);
|
let managers = [
{ id: 1, name: "Jürgen Klopp" },
{ id: 2, name: "Mauricio Pochettino" },
{ id: 3, name: "Ralf Rangnick" },
{ id: 4, name: "Bruno Lage" },
{ id: 5, name: "Maurizio Sarri" },
{ id: 6, name: "Massimiliano Allegri" },
{ id: 7, name: "Peter Bosz" },
{ id: 8, name: "Paulo Fonseca" },
{ id: 9, name: "Ernesto Valverde" },
{ id: 10, name: "Carlo Ancelotti" },
{ id: 11, name: "Thomas Tuchel" },
{ id: 12, name: "Philippe Clement" },
{ id: 13, name: "Diego Simeone" },
{ id: 14, name: "Gian Piero Gasperini" },
{ id: 15, name: "Christophe Galtier" },
{ id: 16, name: "Fatih Terim" },
{ id: 17, name: "Marcelino García Toral" },
{ id: 18, name: "Niko Kovač" },
{ id: 19, name: "Sergei Semak" },
{ id: 20, name: "Pep Guardiola" },
{ id: 21, name: "Lucien Favre" },
{ id: 22, name: "Yuri Semin" },
{ id: 23, name: "Marco Rose" }
];
const getManagers = () => {
return managers;
};
module.exports = {
getManagers
};
|
//app.js
App({
onLaunch: function() {
},
onLogin: function(cb) {
var that = this;
wx.checkSession({
success: function(res) {
if (wx.getStorageSync('openid')) {
that.onRefresh(cb);
} else {
wx.login({
success: res => {
if (res.code) {
wx.getUserInfo({
withCredentials: true,
success: function(res_user) {
wx.request({
url: that.globalData.base_url + 'wechat/login/',
data: {
code: res.code,
encryptedData: res_user.encryptedData,
iv: res_user.iv
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function(res) {
console.log(3,res)
that.globalData.userInfo = res.data.userinfo;
wx.setStorageSync('session', res.data.hash);
wx.setStorageSync('openid', res.data.openid);
typeof cb == "function" && cb(that.globalData.userInfo)
}
})
},
fail: function(e) {
typeof cb == "function" && cb(false)
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
},
})
}
},
fail: function() {
wx.login({
success: res => {
if (res.code) {
wx.getUserInfo({
withCredentials: true,
success: function(res_user) {
wx.request({
url: that.globalData.base_url + 'wechat/login/',
data: {
code: res.code,
encryptedData: res_user.encryptedData,
iv: res_user.iv
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function(res) {
console.log('fail',res)
that.globalData.userInfo = res.data.userinfo;
wx.setStorageSync('session', res.data.hash);
wx.setStorageSync('openid', res.data.openid);
typeof cb == "function" && cb(that.globalData.userInfo)
}
})
},
fail: function(e) {
typeof cb == "function" && cb(false)
}
})
} else {}
}
})
}
})
},
onRefresh: function(cb) {
var that = this;
wx.checkSession({
success: function(res) {
if (!that.globalData.userInfo) {
if (wx.getStorageSync('openid')) {
wx.request({
url: that.globalData.base_url + 'wechat/login_info/',
data: {
openid: wx.getStorageSync('openid'),
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function(res) {
that.globalData.userInfo = res.data.userinfo;
typeof cb == "function" && cb(that.globalData.userInfo)
}
})
} else {
that.onLogin(cb);
}
} else {
typeof cb == "function" && cb(that.globalData.userInfo)
}
},
fail: function(res) {
that.onLogin(cb);
},
})
},
globalData: {
base_url: "https://www.1537u.cn/admin/",
userInfo: null,
},
})
|
/*!@preserve
* OnceDoc
*/
var config = global.CONFIG
var ONCEIO_CONFIG = config.ONCEIO_CONFIG
var MAIN_CONFIG = config.MAIN_CONFIG
global.ONCEOS_DESKTOP_MENU.push({
text : LOCAL.ASK
, icon : '/ask/img/ask.png'
, href : '/ask'
, target : '_blank'
})
global.ONCEOS_SUB_MENU_APP.nodes.push({
text : LOCAL.ASK
, icon : '/ask/img/ask.png'
, href : '/ask'
})
app.mod('ask', '../web')
app.pre('ask', '.tmpl')
OnceDoc.on('ready', function() {
oncedb.extend('article', {
replies : 'array'
, replyNum : 'int'
, private : "int;index('article_private');default(1)"
})
OnceDB.addExtension({
schema : 'article',
columns : [{
type : 'select',
field : 'private',
title : LOCAL.PRIVATE,
options : [
{ title : LOCAL.NO, value : 0 },
{ title : LOCAL.YES, value : 1 }
]
}]
})
app.map('/blog/view/:id', '/ask/view/:id')
})
require('./ask.article')
|
//服务层
app.service('seckillGoodsService',function($http){
//读取列表数据绑定到表单中
this.findList=function(){
return $http.get('seckillGoods/findList.do');
}
////从缓存里获取id实体,秒杀详情页
this.findOne=function(id){
return $http.get('seckillGoods/findoneredis.do?id='+id);
}
//提交订单
this.submitOrder=function(seckillId){
return $http.get('submitOrder/submitOrder.do?seckillId='+seckillId);
}
});
|
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { AppBar, Toolbar, Typography, IconButton } from "@material-ui/core";
import { ExitToAppRounded, PersonRounded } from "@material-ui/icons";
import "../styles/header.css";
export default function Header({ authentication, isLoggedIn }) {
console.log(isLoggedIn);
const [loggedIn, setLoggedIn] = useState(isLoggedIn);
useEffect(() => {
setLoggedIn(() => isLoggedIn);
}, [isLoggedIn, loggedIn]);
const handleLogout = () => {
setLoggedIn(() => false);
localStorage.clear();
console.log(loggedIn);
authentication();
};
return (
<div className="navbarWrapper">
<AppBar id="navbarContainer" position="static">
<Toolbar id="navbar">
<Link id="mainLogo" to="/">
<Typography variant="h6">ConfessTime</Typography>
</Link>
<div>
<Link to="/user">
<IconButton>
<PersonRounded />
</IconButton>
</Link>
{loggedIn ? (
<IconButton onClick={handleLogout}>
<ExitToAppRounded />
</IconButton>
) : null}
</div>
</Toolbar>
</AppBar>
</div>
);
}
|
import React, { Component } from 'react';
import About from './components/About';
import Experience from './components/Experience';
import Education from './components/Education';
import Certificate from './components/Certificate';
import Skills from './components/Skills';
import LightboxGallery from './components/Gallery';
class App extends Component {
constructor(){
super();
this.state = {
resume: []
};
}
componentDidMount(){
console.log('componentDidMount')
fetch('http://resumeapi-env.fp5zraupj7.us-east-2.elasticbeanstalk.com/resume/barry')
// fetch('http://resumeapi.knapp.work/resume/barry')
// fetch('http://localhost:8080/resume/barry')
.then(results => {
console.log(results)
return results.json();
}).then(data => {
//let Store = [];
//Store.push(data);
this.setState({resume: data});
})
console.log(this.state.resume);
}
render() {
let r = this.rendered();
return r;
}
rendered(){
let res = this.state.resume;
if(res.avatar==null){
return <header><div></div></header>
}
return (
<header>
<div className='wrapper'>
<div>
<div className='sidebar'>
<About
avatar={res.avatar}
name={res.name}
profession={res.profession}
bio={res.bio}
address={res.address}
social={res.social} />
</div>
<div className='content-wrapper'>
<div className='content'>
<LightboxGallery
images={[
{ src: '../media/knapp_work_arch.png'}
]}
/>
<Experience experience={res.experience} />
<Education education={res.education} />
<Certificate certificate={res.certificate} />
<Skills skills={res.skills} />
Resume Architecture Links
<ul>
<li><a href='http://resumeapi.knapp.work/resume/barry'>JSON - http://resumeapi.knapp.work/resume/barry</a></li>
<li><a href='https://github.com/barryrknapp/resume-api'>GITHUB Resume Api Spring-boot- https://github.com/barryrknapp/resume-api</a></li>
<li><a href='https://github.com/barryrknapp/resumeapi-ui'>GITHUB Resume UI React.js- https://github.com/barryrknapp/resumeapi-ui</a></li>
<li><a href='https://hub.docker.com/r/barryknapp/work.knapp.public/tags/'>DOCKER - https://hub.docker.com/r/barryknapp/work.knapp.public/tags/</a></li>
</ul>
Thanks to <a href='https://github.com/gndx/gresume-react'>gresume</a> for the react template used as a baseline for the UI
</div>
</div>
</div>
</div>
</header>
);
}
}
export default App;
|
X.define("model.userModel", function () {
//临时测试数据
var query = X.config.user.api.userlistByPage;
var find = X.config.user.api.getUserById;
var status = X.config.user.api.status;
var audit = X.config.user.api.audit;
var register = X.config.user.api.register;
var userModel = X.model.create("model.userModel", {idAttribute: "userId", service: {query: query, find: find}});
//获取用户信息列表
userModel.getList = function (callback) {
return X.loadData({
"url": X.config.user.uri.getList, "type": "GET", callback: function (data) {
callback(data);
}
});
};
userModel.checkLogin = function (callback) {
var isLogin = $.cookie("isLogin");
if (isLogin) {
callback({statusCode: "2000000"});
}
else {
callback({statusCode: "2000001"});
}
//return X.loadData({"url":X.config.user.uri.checkLogin,"type":"GET",callback:function (data) {
// callback(data);
//}});
};
//前台注册提交
userModel.register = function (data, callback) {
var option = {
data: data, url: register, type: "POST", callback: function (result) {
if (result.statusCode == "2000000") {
callback && callback();
}
}
};
X.loadData(option);
};
//短信验证码
userModel.msgCode = function (data, callback) {
var option = {
url: X.config.user.api.msgCode, type: "POST", callback: function () {
console.log("发送短信验证码");
callback && callback();
}
};
X.loadData(option);
};
//新增用户信息提交
userModel.addUser = function (data, callback) {
var option = {
url: X.config.user.api.addUser, type: "POST", success: function () {
console.log("提交成功");
callback && callback();
}
};
X.loadData(option);
};
//用户状态
userModel.StatusChange = function (data, callback) {
var option = {
url: status, type: "PUT", data: data, callback: function () {
console.log("提交成功");
callback && callback();
}
};
X.loadData(option);
};
userModel.validateTel = function (callback) {
setTimeout(1000, function () {
callback({statusCode: 2000000});
})
};
userModel.getUserById = function (option) {
var callback = option.callback;
var success = function (model) {
var data = model.attributes;
data.gender_text = (data.gender == userModel.const.gender.MALE.key) ? userModel.const.gender.MALE.text : userModel.const.gender.FEMALE.text;
callback(model)
};
option.callback = success;
this.find(option);
};
userModel.userAudit = function (data,callback) {
var option = {url:audit, type:"POST", data:data, callback: function(result){
callback && callback(result);
}};
X.loadData(option);
};
userModel.const = {
gender: {
FEMALE: {key: "0", text: "女"},
MALE: {key: "1", text: "男"}
}
};
userModel.statusconst = {
status: {
PENDING: {key: "0", text: "待审核"},
PASS: {key: "1", text: "通过"},
REJECT: {key: "1", text: "驳回"}
},
cases: [
{key: "", value: "全部"},
{key: 0, value: "待审核"},
{key: 1, value: "通过"},
{key: 2, value: "驳回"}
]
};
return userModel;
});
|
var interface_c1_connector_user_group_action =
[
[ "ID", "interface_c1_connector_user_group_action.html#aafec9cc20be5457febad926663b1484e", null ],
[ "type", "interface_c1_connector_user_group_action.html#aaacc8a70acd56c8814bd74a98d7030ee", null ]
];
|
import defaultSettings from './defaultSettings' // https://umijs.org/config/
import slash from 'slash2'
import webpackPlugin from './plugin.config'
const { pwa, primaryColor } = defaultSettings // preview.pro.ant.design only do not use in your production ;
// preview.pro.ant.design 专用环境变量,请不要在你的项目中使用它。
const { ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION } = process.env
const isAntDesignProPreview = ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site'
const plugins = [
[
'umi-plugin-react',
{
antd: true,
dva: {
hmr: true,
},
locale: {
// default false
enable: true,
// default zh-CN
default: 'zh-CN',
// default true, when it is true, will use `navigator.language` overwrite default
baseNavigator: true,
},
dynamicImport: {
loadingComponent: './components/PageLoading/index',
webpackChunkName: true,
level: 3,
},
pwa: pwa
? {
workboxPluginMode: 'InjectManifest',
workboxOptions: {
importWorkboxFrom: 'local',
},
}
: false, // default close dll, because issue https://github.com/ant-design/ant-design-pro/issues/4665
// dll features https://webpack.js.org/plugins/dll-plugin/
// dll: {
// include: ['dva', 'dva/router', 'dva/saga', 'dva/fetch'],
// exclude: ['@babel/runtime', 'netlify-lambda'],
// },
},
],
[
'umi-plugin-pro-block',
{
moveMock: false,
moveService: false,
modifyRequest: true,
autoAddMenu: true,
},
],
] // 针对 preview.pro.ant.design 的 GA 统计代码
if (isAntDesignProPreview) {
plugins.push([
'umi-plugin-ga',
{
code: 'UA-72788897-6',
},
])
plugins.push([
'umi-plugin-pro',
{
serverUrl: 'https://ant-design-pro.netlify.com',
},
])
}
export default {
plugins,
block: {
defaultGitUrl: 'https://github.com/ant-design/pro-blocks',
},
hash: true,
targets: {
ie: 11,
},
devtool: isAntDesignProPreview ? 'source-map' : false,
// umi routes: https://umijs.org/zh/guide/router.html
routes: [
// oauth 登录
{
path: '/oauth',
component: '../layouts/BlankLayout',
routes: [
{
path: '/oauth/callbackPage',
component: './oauth/CallbackPage',
},
],
},
// 登录后首页
{
path: '/home',
component: '../layouts/BlankLayout',
routes: [
{
path: '/home',
component: './aMenu',
},
],
},
// 不需要登录的
{
path: '/public',
routes: [
{
path: '/public/viewBlog',
component: '../layouts/BasicLayout',
routes: [
{
name: 'Blog List',
icon: 'unordered-list',
path: '/public/blogList',
},
{
path: '/public/viewBlog/blogId/:blogId',
component: './viewBlog/ViewBlog',
},
{
path: '/public/viewBlog/testMockArticleComments/blogId/:blogId',
component: './viewBlog/ViewBlogTestMockArticleComments',
},
{
path: '/public/viewBlog/test',
component: './viewBlog/ViewBlogTest',
},
{
path: '/public/viewBlog/testEmoji',
component: './viewBlog/ViewBlogEmojiTest',
},
{
path: '/public/viewBlog/testInfo',
component: './viewBlog/ViewBlogArticleInfoTest',
},
{
path: '/public/viewBlog/testBase64',
component: './viewBlog/ViewBlogBase64Test',
},
],
},
{
path: '/public/blogList',
component: '../layouts/BasicLayout',
routes: [
{
path: '/public/blogList',
component: './blog-list',
},
],
},
],
},
// 测试
{
path: '/test',
routes: [
{
path: '/test',
redirect: '/test/dva/emoji',
},
{
path: '/test/dva',
component: '../layouts/BasicLayout',
routes: [
{
path: '/test/dva/emoji',
component: './test/dva/emoji',
},
{
path: '/test/dva/dva01',
component: './test/dva/dva01',
},
{
path: '/test/dva/dva02',
component: './test/dva/dva02',
},
{
path: '/test/dva/dva03',
component: './test/dva/dva03',
},
{
name: 'dva menu',
path: '/test/dva/menu',
component: './test/dva/menu',
},
],
},
],
},
{
path: '/',
hideInMenu: true,
routes: [
// 根路由重定向
{
path: '/',
redirect: '/public/blogList',
},
{
path: '/:username',
routes: [
{
path: '/:username',
redirect: '/:username/index',
},
{
path: '/:username/index',
component: '../layouts/BasicLayout',
routes: [
{
path: '/:username/index',
component: './first/index',
routes: [
{
path: '/:usernaem/index',
component: './block/search-list-articles',
},
],
},
],
},
{
path: '/:username/editor',
component: './markdown/Editor',
},
{
path: '/:username/editor2',
component: './markdown/Editor2',
},
{
path: '/:username/editor3',
component: './markdown/Editor3',
},
{
path: '/:username/editor4',
component: './markdown/Editor4',
},
{
path: '/:username/editor5',
component: './markdown/Editor5',
},
{
path: '/:username/newBlog',
component: '../layouts/BasicLayout',
routes: [
{
path: '/:username/newBlog',
component: './newBlog/NewBlog',
},
],
},
{
path: '/:username/viewBlog',
component: '../layouts/BasicLayout',
routes: [
// 查看文章, 带 :username
{
path: '/:username/viewBlog/blogId/:blogId',
component: './viewBlog/ViewBlog',
},
],
},
{
path: '/:username/signature',
component: '../layouts/BasicLayout',
routes: [
{
path: '/:username/signature',
component: './signature',
},
],
},
{
path: '/:username/files',
component: '../layouts/BasicLayout',
routes: [
{
path: '/:username/files',
component: './files',
},
],
},
{
path: '/:username/seals',
component: '../layouts/BasicLayout',
routes: [
{
path: '/:username/seals',
component: './seals',
},
],
},
],
},
{
component: './404',
},
],
},
],
// Theme for antd: https://ant.design/docs/react/customize-theme-cn
// theme: {
// 'primary-color': primaryColor,
// },
define: {
ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION:
ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION || '', // preview.pro.ant.design only do not use in your production ; preview.pro.ant.design 专用环境变量,请不要在你的项目中使用它。
},
ignoreMomentLocale: true,
lessLoaderOptions: {
javascriptEnabled: true,
},
disableRedirectHoist: true,
cssLoaderOptions: {
modules: true,
getLocalIdent: (context, _, localName) => {
if (
context.resourcePath.includes('node_modules') ||
context.resourcePath.includes('ant.design.pro.less') ||
context.resourcePath.includes('global.less')
) {
return localName
}
const match = context.resourcePath.match(/src(.*)/)
if (match && match[1]) {
const antdProPath = match[1].replace('.less', '')
const arr = slash(antdProPath)
.split('/')
.map(a => a.replace(/([A-Z])/g, '-$1'))
.map(a => a.toLowerCase())
return `antd-pro${ arr.join('-') }-${ localName }`.replace(/--/g, '-')
}
return localName
},
},
manifest: {
basePath: '/',
},
chainWebpack: webpackPlugin,
proxy: {
'/blog/**': {
target: 'http://blog.loc:20000/',
changeOrigin: false,
},
},
// 如果项目要发布到非根目录下
// 以下 (base/publicPath/outputPath) 几个参数如何配置
// 是与反向代理嗠器nginx配置相关的
// 方式一
// nginx:
// location /antd/ {
// proxy_pass http://dev.local:5000/;
// }
// umi:
// base: '/antd/',
// publicPath: '/antd/',
// //
// 方式二
// nginx:
// location /antd/ {
// proxy_pass http://dev.local:5000/antd/;
// }
// umi:
base: '/blog-web/',
// cdn 用的
// publicPath: 'http://q08cdx8dh.bkt.clouddn.com/blog/',
publicPath: '/blog-web/',
outputPath: 'dist/blog-web/',
// //
history: 'hash',
}
|
'use strict';
angular.module('crm')
.controller('addEditSmtpServer', function ($scope, ModalService, DataStorage, data, close, $rootScope) {
$scope.smtpServer = {};
$scope.data = data;
var defaultSmtp
if ($scope.data.smtpServer && $scope.data.smtpServer.id)
DataStorage.emailAutorespondersApi.getSmtpById().query({smtpId: $scope.data.smtpServer.id}, function(resp){
if (resp && resp.SmtpServer){
resp.SmtpServer.ID = data.smtpServer.id
defaultSmtp = angular.copy(resp.SmtpServer);
$scope.smtpServer = angular.copy(resp.SmtpServer);
}
});
$scope.$watch('smtpServer', function(newObj){
$scope.changedSmtp = !angular.equals(newObj, defaultSmtp)
}, true);
$scope.confirmSmtp = function(){
ModalService.showModal({
templateUrl: "components/modals/COMMON/sure.html",
controller: "DataModalCtrl",
inputs: {
data: {
modalTitle: $rootScope.translate('modals.campaigns.email.smtp.addeditsmtpserver.confirm-smtp'),
modalTxt: $rootScope.translate('modals.campaigns.email.smtp.addeditsmtpserver.all-unsaved-changes-will-be-saved.-continue?')
}
}
}).then(function (modal) {
modal.element.modal();
modal.close.then(function (result) {
if (result == 'false') return;
$scope.data.confirmSmtp($scope.data.smtpServer.id)
})
});
};
$scope.authenticateSmtp = function(){
$scope.errorMessage = false;
$scope.authenticatedSmtp = {
submitted: false
};
$scope.processing = true;
DataStorage.emailAutorespondersApi.authSmtp().post($scope.smtpServer, function(resp){
$scope.processing = false;
$scope.authenticatedSmtp = {
success: resp && resp.Status == 0,
submitted: true,
errors: resp.ErrorMessage
}
})
};
$scope.createOrEdit = function(smtpModForm){
if (smtpModForm.$invalid) return false
$scope.smtpServer.ClientID = data.clientID
var method = 'addSmtp';
if ($scope.smtpServer.ID) method = 'editSmtp';
DataStorage.emailAutorespondersApi[method]().post($scope.smtpServer, function(resp){
close(resp,500);
})
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.