text stringlengths 7 3.69M |
|---|
import React, { useEffect, useState } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { useRouter } from "next/router"
import { db, auth } from '../../utils/fire-config/firebase'
import HeadMetadata from '../../components/HeadMetadata'
import Footer from '../../components/Footer'
import { deletePost, parseMd, openLoading } from '../../myFunctions'
import { confirmAlert } from 'react-confirm-alert';
function PostsPage({ post }) {
// openLoading('close')
useEffect(() => {
openLoading('close');
}, []);
const router = useRouter()
const [user, setUser] = useState([]);
const [canEdit, setCanEdit] = useState(false);
// setUser
useEffect(() => {
auth.onAuthStateChanged(authUser => {
if (authUser) {
setUser(authUser);
} else {
// router.push('/login')
}
})
}, []);
// setCanEdit
useEffect(() => {
if (user?.displayName === 'code-cent') {
setCanEdit(true)
}
}, [user]);
const onDelete = (slug) => {
confirmAlert({
title: 'Confirm to delete',
message: 'Are you sure to do this.',
buttons: [
{
label: 'Yes',
onClick: async () => {
openLoading('open');
let res = deletePost(slug)
console.log(res)
openLoading('close');
window.location.reload()
}
},
{
label: 'No',
// onClick: () => alert('Click No')
}
]
});
}
const prettyDate = new Date(post?.createdAt).toLocaleString('en-US', {
month: 'short',
day: '2-digit',
year: 'numeric',
})
if (router.isFallback) {
return (
<div className="loading" style={{ display: 'grid' }}>
<Image src="/loading.gif" alt="loading..." width="50px" height="50px" />
</div>
)
} else {
return (<>
<HeadMetadata
title={post ? `${post?.title} - Cent Blog` : "Get latest update around the world at your finger tip | Cent Blog"}
metaDescription={post ? post?.excerpt : "Get latest update around the world at your finger tip | Cent Blog"}
/>
<div className="parent">
<div className="left"></div>
<div className="middle homepage-container">
{post?.createdAt && <div className="layout-wrapper">
<div className="blog-post-container">
<div>
{canEdit && <div className="modBtn">
<Link href={`/admin/edit/${post?.slug}`}>
<a><button style={{ marginRight: 10 }}>Edit</button></a>
</Link>
<button className="modBtn2" onClick={() => { onDelete(post?.slug) }}>Delete</button>
</div>}<br />
<div className="blog_post_card__title" >{post?.title}</div>
<div style={{ margin: 10 }}></div>
<hr style={{ margin: '20px 0', border: '1px solid #25c7eb' }} />
<div className="blog-post-top-section">
<div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center' }}>
<div className="blog-post-author" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
{post?.author?.photoURL && <Image src={post?.author?.photoURL} alt={post?.author?.userName} width="100px" height="100px" className="authorPhoto" />}
<Link href={`/authors/${post?.author?.slug}`}><a style={{ color: '#005584', fontSize: '1.125rem', fontWeight: 900, fontFamily: 'Lato,Helvetica,Arial,sans-serif' }}>{post?.author?.userName && <b>{post?.author?.userName}</b>}</a></Link>
</div>
<div>
<div className="blog_post_card__date">
<div>Published at</div>
<time dateTime={post?.createdAt}>{prettyDate}</time>
</div>
{/* <div>S H A R E</div> */}
</div>
</div>
</div>
<hr style={{ marginTop: 20, border: '1px solid #25c7eb' }} />
<div style={{ margin: 10 }}></div>
{post?.body && <article dangerouslySetInnerHTML={{ __html: parseMd(post?.body) }} className="blog-post-body-content">
</article>}
</div>
</div>
</div>
}
<Footer />
</div>
<div className="right"></div>
</div>
</>)
}
}
export default PostsPage
export const getServerSideProps = async (context) => {
const { slug } = context.params;
// console.log({ slug })
if (slug) {
const res = await db.collection("posts").doc(slug).get();
const post = res?.data();
if (res.exists) {
return {
props: { post }
}
} else {
return {
props: {}
}
}
}
} |
import React from 'react'
import { Link } from 'react-router'
import Nav from '../components/Nav'
class Home extends React.Component {
constructor(props) {
super(props)
}
render() {
return <div>
<div id="homePage" className="row">
<div className="col-sm-12 text-center">
<h1>Welcome to Chirp!</h1>
<h3>Come chirp with us!</h3>
</div>
<div className="col-sm-6 text-center">
<Link to={path + "/signin"}>
<button id="signin" type="button" className="btn btn-primary btn-block" >SignIn</button>
</Link>
</div>
<div className="col-sm-6">
<Link to={path + "/signup"}>
<button id="signup" type="button" className="btn btn-success btn-block" >SignUp</button>
</Link>
</div>
</div>
</div>
}
}
export default Home
|
import styled from 'styled-components'
export default styled.hr`
width: 90%;
height: 2px;
background-color: black ;
`
|
/* Promises
Understand the differences of the promise and the callback pattern to work with mongodb
Refer to 04-callbacks.js to understand the callback syntax */
const simplePromise = new Promise((resolve, reject) => {
setTimeout(() => {
// If it resolves:
// resolve('Resolved');
// If things went wrong, like a failed connection:
reject('Reject: Things went wrong, maybe a connection problem?')
}, 800)
})
simplePromise.then((result) => {
console.log('Success!', result)
}).catch((error) => {
console.log('Error!', error)
})
// PROMISE CHAINING
console.log(`Promise Chaining:`)
const add = (a, b) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(a + b)
}, 2000);
})
}
// First try... it works, but will be bad to read and can get very complex
// add(1, 2).then((sum) => {
// console.log(sum)
// add(sum, 10).then((sum2) => {
// console.log(sum2)
// }).catch((err) => {
// console.log(err)
// })
// }).catch((err) => {
// console.log(err)
// })
// The better way:
add(1, 2).then((sum) => {
console.log(sum)
return add(sum, 2) // Here we return the resolved promise
}).then((sum2) => {
console.log(sum2)
return add(sum2, 5)
}).then((sum3) => {
console.log(sum3)
}).catch((err) => {
console.log(err)
}) |
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
const Promise = require('pinkie-promise');
const EventEmitter = require('events');
const inspect = require('util').inspect;
const store = require('./store');
const tools = require('./tools');
const announcer = require('./announcer');
const c2s = tools.cnx2str;
module.exports = function () {
let options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
return Promise.all([announcer({ log: options.log, bind: options.announce }), require('./datagram')({ log: options.log, socket: { type: 'udp4' }, bind: options.bind })]).then(_ref => {
var _ref2 = _slicedToArray(_ref, 2);
let announcer = _ref2[0];
let bolo = _ref2[1];
return new Promise((resolve, reject) => {
options.bind = options.bind || {};
let closed = false;
const log = options.log || tools.noLog;
const peerEvents = new EventEmitter();
const events = new EventEmitter();
const peers = store(peerEvents);
const myData = store(events);
const theirData = store(events);
const peerUrl = peer => `udp://${ peer.address }:${ peer.port }`;
const facade = {
close: () => {
closed = true;
return Promise.all(peers.mapData(peer => bolo.send(JSON.stringify({
bolo: 'quit',
quit: (options.bind.address ? [options.bind.address] : tools.externalAddresses().map(a => a.address)).map(address => peerUrl({ address: address, port: bolo.address().port })),
remove: myData.map(key => key)
}), peer.port, peer.address).catch(error => log.warn(`failed to quit from ${ inspect(peer) } (${ error })`)))).then(() => Promise.all([announcer.close().catch(err => log.warn(`failed to close announcer (${ err })`)), bolo.close().catch(err => log.warn(`failed to close (${ err })`))])).then(() => events.emit('close')).then(() => facade);
},
set: (key, datum) => {
if (closed) {
Promise.reject(new Error('closed'));
}
myData.set(key, datum);
return Promise.all(peers.mapData(peer => bolo.send(JSON.stringify({
bolo: 'set',
set: [{ key: key, datum: datum }]
}), peer.port, peer.address).catch(err => log.warn(`failed to set ${ key } on ${ inspect(peer) } (${ err })`)))).then(() => facade);
},
remove: key => {
if (closed) {
Promise.reject(new Error('closed'));
}
myData.remove(key);
return Promise.all(peers.mapData(peer => bolo.send(JSON.stringify({
bolo: 'remove',
remove: [key]
}), peer.port, peer.address).catch(err => log.warn(`failed to remove ${ key } from ${ inspect(peer) } (${ err })`)))).then(() => facade);
},
get: function get(key) {
let options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
return new Promise((resolve, reject) => {
let timeout = null;
let askInterval = null;
const stored = myData.get(key) || theirData.get(key);
const closeHandler = () => {
facade.removeListener('set', resolver);
clearTimeout(timeout);
clearInterval(askInterval);
reject(new Error('closed'));
};
const resolver = (k, d) => {
if (k === key) {
facade.removeListener('set', resolver);
facade.removeListener('close', closeHandler);
clearTimeout(timeout);
clearInterval(askInterval);
resolve(d);
}
};
if (typeof stored !== 'undefined') {
return resolve(stored);
}
if (closed) {
reject(new Error('closed'));
}
if (options.timeout) {
timeout = setTimeout(() => {
facade.removeListener('set', resolver);
facade.removeListener('close', closeHandler);
clearInterval(askInterval);
reject(new Error(`${ key } was not found`));
}, options.timeout);
}
if (options.askInterval) {
askInterval = setInterval(() => {
peers.mapData(peer => bolo.send(JSON.stringify({
bolo: 'ask',
ask: [key]
}), peer.port, peer.address).catch(error => log.warn(`failed to ask for ${ key } (${ error })`)));
}, options.askInterval);
}
facade.on('close', closeHandler);
facade.on('set', resolver);
});
}
};
const checkPeer = peer => {
const url = peerUrl(peer);
if (!peers.get(url)) {
peers.set(url, peer);
}
};
const messageHandler = {
quit: (message, rinfo) => {
message.quit.forEach(peers.remove);
message.remove.forEach(theirData.remove);
},
set: (message, rinfo) => {
checkPeer(rinfo);
message.set.map(_ref3 => {
let key = _ref3.key;
let datum = _ref3.datum;
return theirData.set(key, datum);
});
},
remove: (message, rinfo) => {
checkPeer(rinfo);
message.remove.map(key => theirData.remove(key));
},
ask: (message, rinfo) => {
const foundData = message.ask.map(key => ({ key: key, datum: myData.get(key) })).filter(_ref4 => {
let key = _ref4.key;
let datum = _ref4.datum;
return typeof datum !== 'undefined';
});
checkPeer(rinfo);
if (foundData.length) {
bolo.send(JSON.stringify({
bolo: 'set',
set: foundData
}, rinfo.port, rinfo.address)).catch(error => log.warn(`failed to reply on demand for ${ message.ask } (${ error })`));
}
}
};
log.info(`listening on ${ bolo.address().address }:${ bolo.address().port }`);
tools.mixEventEmitter(events, facade);
peerEvents.on('set', (peerUrl, peer) => {
log.info(`new peer ${ peerUrl } ${ inspect(peer) }`);
bolo.send(JSON.stringify({
bolo: 'set',
set: myData.map(key => ({ key: key, datum: myData.get(key) }))
}), peer.port, peer.address).then(() => log.debug(`[bolo] own data sent to ${ c2s(peer) }`)).catch(err => log.warn(`failed to send own data to ${ c2s(peer) } (${ err })`));
});
announcer.on('peer', peer => {
peers.set(peerUrl(peer), peer);
});
announcer.on('error', events.emit.bind(events, 'error'));
announcer.on('close', () => {
log.info('announcer closed');
});
bolo.on('error', events.emit.bind(events, 'error'));
bolo.on('message', (msg, rinfo) => {
log.debug(`[bolo] received ${ msg.toString() } from ${ c2s(rinfo) }`);
try {
const message = JSON.parse(msg);
messageHandler[message.bolo](message, rinfo);
} catch (error) {
log.warn(`malformed message (${ msg.toString() }) from ${ rinfo.address }:${ rinfo.port } (${ error })`);
}
});
bolo.on('close', () => {
log.info('closed');
});
announcer.announce({
address: options.bind.address,
port: bolo.address().port
}).then(() => resolve(facade), reject);
});
});
}; |
import React, { Component } from 'react';
//competences passed as props from Cv component
let competences = [];
/*function for update cv content in the parent component(cv), passed as props from cv creation component*/
let handleChange;
/*Adding Competence component*/
class Competence extends Component {
constructor(props) {
super(props);
this.state = {
index: this.props.index,
};
}
render(){
return(
<div>
<form>
<div className="form-group">
<input type="text" className="form-control border rounded"
defaultValue={this.props.competence.title}
id="title" name="title" placeholder="title" onChange={this.handleChange}/>
</div>
</form>
<hr/>
</div>
)}
handleChange = (e) => {
const { id, value } = e.target;
competences[this.state.index][id] = value;
handleChange('competences',competences);
}
}
//Competences component: has many Competence
class Competences extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
}
componentDidMount(){
competences = this.props.competences;
handleChange = this.props.handleChange;
this.renderCompetences();
}
render(){
return(
<div className="container spacer col-12 login-form">
<div className="sub-title">
Competences
<button className="btn btn-light"
onClick={this.newCompetence}><span>+</span></button></div>
<React.Fragment>
{this.state.items}
</React.Fragment>
</div>
)}
renderNewCompetence = () => {
let it = [];
const index = competences.length - 1;
let competence = competences[index];
it.push(<Competence index={index} competence={competence} key={index}/>)
this.setState({
items: [...this.state.items, ...it]
})
}
newCompetence = () => {
competences.push({title:''});
this.renderNewCompetence();
}
renderCompetences = () => {
let it = [];
for(const [index, competence] of competences.entries()){
it.push(<Competence index={index} competence={competence} key={index}/>)
}
this.setState({
items: [...this.state.items, ...it]
})
}
}
export default Competences; |
import React from 'react'
import Example from '../components/Example'
import { Breadcrumb } from '../snippets/snippets'
const BreadcrumbPage = () => {
const breadList = ["Home", "Projects", "Project One"]
return (
<Example>
<Breadcrumb items={ breadList } />
</Example>
)
}
export default BreadcrumbPage
|
import { createElement, render, Component } from './toy-react.js';
class MyComponent extends Component {
constructor() {
super();
this.state = {
name: 'xuwanwan nb+',
data: 1
};
}
render() {
return (
<div>
<div>{this.state.name}<span>{this.state.data.toString()}</span></div>
<button onClick={() => { this.setState({ data: this.state.data + 1 }) }}>点我</button>
{this.children}
</div>
)
}
};
let a = (
<MyComponent className={'active'} id={'root'}>
<div className={'item'} >1</div>
<div className={'item'} >2</div>
<div className={'item'} >3</div>
</MyComponent>
);
render(a, document.querySelector('#root')); |
require(['data','deleteTable','createTable','totalSort', 'filter','jQuery'], function (data, deleteTable, createTable, sort, filter, jQuery ){
//modify json format in data (module "data")
var books = JSON.parse(data);
var newTable = document.getElementById('newTable');
//define the amount of items displayed on one page
var param = Math.ceil(books.length/3);
createTable(books, 0, param);
//pagination 1,2,3
var pageOne = document.getElementById('first');
pageOne.addEventListener('click',function (e) {
if (e.target) {
deleteTable(newTable);
createTable(books, 0, param);
}
});
var pageTwo = document.getElementById('second');
pageTwo.addEventListener('click',function (e) {
if (e.target) {
deleteTable(newTable);
createTable(books, param, param*2);
}
});
var pageThree = document.getElementById('third');
pageThree.addEventListener('click',function (e) {
if (e.target) {
deleteTable(newTable);
createTable(books, 2*param, param*3);
}
});
//pagination forward
var pageForward = document.getElementById('forwardMod');
pageForward.addEventListener('click',function (e) {
if (e.target) {
field = document.getElementsByTagName('tr')[1];
var author = field.getElementsByTagName('td')[0].innerText;
var title = field.getElementsByTagName('td')[1].innerText;
for (var i=0; i<books.length; i++){
if(books[i]['author'] == author && books[i]['title'] ==title ){
deleteTable(newTable);
if ((i+param)<books.length){
createTable(books, i+param, i+2*param);
}
else createTable(books, i, books.length);
}
}
}
});
//pagination backward
var pageBackward = document.getElementById('backwardMod');
pageBackward.addEventListener('click',function (e) {
if (e.target) {
field = document.getElementsByTagName('tr')[1];
var author = field.getElementsByTagName('td')[0].innerText;
var title = field.getElementsByTagName('td')[1].innerText;
for (var i=0; i<books.length; i++){
if(books[i]['author'] == author && books[i]['title'] ==title ){
deleteTable(newTable);
if (i > 0){
createTable(books, i-param, i);
}
else createTable(books, 0, 5);
}
}
}
});
// filter by title (module "filter")
var filterParameterButton = document.getElementById('submit');
var filterParameter = document.getElementById('filterParameter');
filterParameterButton.addEventListener('click',function (e) {
if (e.target) {
e.preventDefault();
var specialTitle=filterParameter.value;
deleteTable(newTable);
var newBooks = filter (specialTitle, books)
createTable(newBooks, 0, newBooks.length);
}
});
// display all the array
var showAllData = document.getElementById('showAllData');
showAllData.addEventListener('click',function (e) {
if (e.target) {
deleteTable(newTable);
createTable(books, 0, books.length);
}
});
//event that occurs when the client makes click
var headerRow = document.getElementById('headerRow');
headerRow.addEventListener('click',function (e) {
if (e.target) {
deleteTable(newTable);
createTable(books,0,param);
}
});
});
|
const fs = require('fs');
const md5 = require('js-md5');
let request = require('async-request'),
response;
function toWei(amount) {
return web3._extend.utils.toWei(amount, 'ether')
}
function fromWei(amount) {
return web3._extend.utils.fromWei(amount, 'ether')
}
const real_world_number = 2;
module.exports = async() => {
let all_transactions = [];
let url = 'http://api.etherscan.io/api?module=account&action=tokentx&address=0x1d29d34686f3d26816816170c65b436dc011d3ff&startblock=0&endblock=999999999&sort=asc&apikey=YourApiKeyToken';
response = await request(url);
let all_buys = JSON.parse(response.body);
for (let k = 0; k < all_buys.result.length; k++){
if (all_buys.result[k].from=='0x0000000000000000000000000000000000000000'){
continue;
}
if (parseInt(fromWei(all_buys.result[k].value))>50){
all_buys.result[k].ticket = md5(""+(parseInt(all_buys.result[k].hash.substr(all_buys.result[k].hash.length-8,8),16)+real_world_number));
console.log(all_buys.result[k].hash,all_buys.result[k].hash.substr(all_buys.result[k].hash.length-8,8),parseInt(all_buys.result[k].hash.substr(all_buys.result[k].hash.length-8,8),16),md5(""+(parseInt(all_buys.result[k].hash.substr(all_buys.result[k].hash.length-8,8),16)+real_world_number)));
all_buys.result[k].realvalue = parseInt(fromWei(all_buys.result[k].value));
all_transactions.push(all_buys.result[k]);
}
}
url = 'http://api.etherscan.io/api?module=account&action=tokentx&address=0x64396f0e37d523e8ff32e1eb02dd7dded84cd34f&startblock=0&endblock=999999999&sort=asc&apikey=YourApiKeyToken';
response = await request(url);
all_buys = JSON.parse(response.body);
for (let k = 0; k < all_buys.result.length; k++){
if (all_buys.result[k].from=='0x0000000000000000000000000000000000000000'){
continue;
}
if (all_buys.result[k].hash=='0x838ac86eaf77437fb559abf93a6412b84bb0d01d9b3eb5577c498927c0e27f08'){
continue;
}
if (parseInt(fromWei(all_buys.result[k].value))>50){
all_buys.result[k].ticket = md5(""+(parseInt(all_buys.result[k].hash.substr(all_buys.result[k].hash.length-8,8),16)+real_world_number));
console.log(all_buys.result[k].hash,all_buys.result[k].hash.substr(all_buys.result[k].hash.length-8,8),parseInt(all_buys.result[k].hash.substr(all_buys.result[k].hash.length-8,8),16),md5(""+(parseInt(all_buys.result[k].hash.substr(all_buys.result[k].hash.length-8,8),16)+real_world_number)));
all_buys.result[k].realvalue = parseInt(fromWei(all_buys.result[k].value));
all_transactions.push(all_buys.result[k]);
}
}
let all_transactions_count = all_transactions.length;
let winners_1 = Math.ceil(all_transactions_count*0.02);
let winners_2 = Math.ceil(all_transactions_count*0.25);
let winners_3 = all_transactions_count - winners_1 - winners_2;
console.log('all_transactions_count',all_transactions_count);
console.log('winners_1',winners_1);
console.log('winners_2',winners_2);
console.log('winners_3',winners_3);
all_transactions.sort(function (a, b) {
return parseInt(a.ticket,16) - parseInt(b.ticket,16);
});
for (var i = 0; i<=all_transactions.length - 1; i++) {
let result_t = {hash:all_transactions[i].hash,address:all_transactions[i].to,ticket:all_transactions[i].ticket,realvalue:all_transactions[i].realvalue};
if (i<winners_1){
result_t.awardLevel = 1;
} else if (i<winners_1+winners_2){
result_t.awardLevel = 2;
} else {
result_t.awardLevel = 3;
}
console.log(result_t);
}
}
|
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import Section from '../../../Layout/Section/Section';
const stepsContent = [
{
id: 1,
imgUrl:
'https://static.thumbtackstatic.com/_assets/images/release/modules/how-thumbtack-works/images/estimates.image.4df8109523f34a9c87ca5e5fbd347342.svg',
title: 'Answer a few questions',
text: 'Tell us what you need so we can bring you the right pros.',
},
{
id: 2,
imgUrl:
'https://static.thumbtackstatic.com/_assets/images/release/modules/how-thumbtack-works/images/compare.image.d6667a9e41f6d7d2ba9c5bc7e3d4d747.svg',
title: 'Get quotes',
text: 'Receive quotes from pros who meet your needs.',
},
{
id: 3,
imgUrl:
'https://static.thumbtackstatic.com/_assets/images/release/modules/how-thumbtack-works/images/hire.image.4165884630930da67f128f1c9126fd6d.svg',
title: 'Hire the right pro',
text: 'Compare quotes, message pros, and hire when ready.',
},
];
const SectionTitle = styled.div`
text-align: center;
margin-bottom: 2rem;
`;
const HowTTWorksSteps = styled.div`
display: flex;
flex-direction: column;
@media (min-width: 1026px) {
flex-direction: row;
}
`;
const StyledStep = styled.div`
width: 100%;
text-align: center;
padding-bottom: 3rem;
@media (min-width: 1026px) {
width: 33.3%;
padding: 1rem;
}
> img {
width: 80%;
height: 150px;
display: inline-block;
margin-bottom: 1rem;
}
> p {
font-size: 0.9rem;
}
`;
const HowTTWorksStep = ({ imgUrl, title, text }) => (
<StyledStep>
<img src={imgUrl} alt="How it works ilustration" />
<h4>{title}</h4>
<p>{text}</p>
</StyledStep>
);
HowTTWorksStep.propTypes = {
imgUrl: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
};
const howTTWorksSection = ({ hasBorder }) => (
<Section hasBorder={hasBorder}>
<SectionTitle>
<h3>How Thumbtack works</h3>
</SectionTitle>
<HowTTWorksSteps>
{stepsContent.map(step => <HowTTWorksStep key={step.id} {...step} />)}
</HowTTWorksSteps>
</Section>
);
howTTWorksSection.propTypes = {
hasBorder: PropTypes.bool,
};
howTTWorksSection.defaultProps = {
hasBorder: false,
};
export default howTTWorksSection;
|
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { Navigation } from 'react-native-navigation';
import thunk from 'redux-thunk';
import reducers from './reducers/index';
import * as appActions from './reducers/app/actions';
const reducer = combineReducers(reducers);
const store = createStore(
reducer,
applyMiddleware(thunk)
)
import { registerScreens } from './screens';
registerScreens(store, Provider);
export default class App {
constructor() {
this.startApp();
}
startApp() {
Navigation.startSingleScreenApp({
screen: {
screen: 'MainScreen',
title: 'do you feel lucky punk?!'
}
});
}
}
|
/**
* Created by mapbar_front on 2017/6/6.
*/
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import todoApp from './reducer/reducer';
import Main from "./components/Main";
const store = createStore(todoApp);
render(<Provider store={store}><Main /></Provider>,document.getElementById('root'));
|
Discourse.KbGlyprob = Discourse.KbObj.extend({
// the event object as received from the store
event: '',
// a new event name that we are submitting to the store, which will handle creation of the event object
eventName: null,
// high/low
evaluation: null,
init: function() {
this.set('dataType', Discourse.KbDataType.get('glycemic-problems'));
this._super();
},
// builds a data object to submit to server
// overrides parent method
serialize: function() { var self = this;
var data = self._super();
console.log("super", data);
// discard name and inlink properties and add eval and event name
delete data.name;
delete data.inlinkIds;
data.evaluation = self.get('evaluation');
data.eventName = self.get('eventName');
return data;
}
});
Discourse.KbGlyprob.reopenClass({
dataTypeName: 'glycemic-problems',
// defines the other subtypes to which this one is related
relations: function() {
return [
Discourse.KbObjRelation.create({other: Discourse.KbTrigger, direction: 'forward'})
];
}
}) |
describe('is-human-url', function () {
var isHumanUrl = require('..');
describe('valid', function () {
it('http://google.com', function () {
isHumanUrl('http://google.com').should.be.true;
});
it('https://google.com', function () {
isHumanUrl('https://google.com').should.be.true;
});
it('ftp://google.com', function () {
isHumanUrl('ftp://google.com').should.be.true;
});
it('http://www.google.com', function () {
isHumanUrl('http://www.google.com').should.be.true;
});
it('http://google.com/something', function () {
isHumanUrl('http://google.com/something').should.be.true;
});
it('http://google.com?q=query', function () {
isHumanUrl('http://google.com?q=query').should.be.true;
});
it('http://google.com#hash', function () {
isHumanUrl('http://google.com#hash').should.be.true;
});
it('http://google.com/something?q=query#hash', function () {
isHumanUrl('http://google.com/something?q=query#hash').should.be.true;
});
it('http://google.co.uk', function () {
isHumanUrl('http://google.co.uk').should.be.true;
});
it('http://www.google.co.uk', function () {
isHumanUrl('http://www.google.co.uk').should.be.true;
});
it('http://google.cat', function () {
isHumanUrl('http://google.cat').should.be.true;
});
it('https://d1f4470da51b49289906b3d6cbd65074@app.getsentry.com/13176', function () {
isHumanUrl('https://d1f4470da51b49289906b3d6cbd65074@app.getsentry.com/13176').should.be.true;
});
it('http://0.0.0.0', function () {
isHumanUrl('http://0.0.0.0').should.be.true;
});
it('http://localhost', function () {
isHumanUrl('http://localhost').should.be.true;
});
it('localhost', function () {
isHumanUrl('localhost').should.be.true;
});
it('google.com', function () {
isHumanUrl('google.com').should.be.true;
});
it('g.co', function () {
isHumanUrl('g.co').should.be.true;
});
it('g.name', function () {
isHumanUrl('g.name').should.be.true;
});
it('a.CONSTRUCTION', function () {
isHumanUrl('a.CONSTRUCTION').should.be.true;
});
it('alsdkjfadlfjaklsdjflak---kjkj.jsdlkfjalskdj.flaksjdlfkjasld.kjflaksjdl.fkjasdf.xxx', function () {
isHumanUrl('alsdkjfa.dlfjaklsdjflak---123.jsdlkfjalskdj.flaksjdlfkjasld.kjflaksjdl.fkjasdf.xxx').should.be.true;
});
});
describe('invalid', function () {
it('http://', function () {
isHumanUrl('http://').should.be.false;
});
it('http://google', function () {
isHumanUrl('http://google').should.be.false;
});
it('http://google.', function () {
isHumanUrl('http://google.').should.be.false;
});
it('google', function () {
isHumanUrl('google').should.be.false;
});
});
}); |
import { combineReducers } from 'redux';
// reducers
import user from 'javascripts/store/reducers/user';
const rootReducers = combineReducers({ user });
export default rootReducers;
|
const mongoose = require('mongoose');
mongoose.set('useCreateIndex', true)
const proposalSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
user: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
title: { type: String, required: true },
abstract: { type: String, required: true },
theme: { type: String, enum: ['technical', 'study'] },
duration: { type: Number },
type: {
type: String,
trim: true,
required: true,
enum: ['keynote',
'short-talk',
'competition',
'panel',
'workshop'
]
},
file: { type: String, required: true },
status: {
type: String,
required: true,
enum: ['accepted',
'rejected',
'waiting'
],
default: 'waiting'
}
});
proposalSchema.virtual('evaluation',{
ref: 'evaluation',
localField: '_id',
foreignField: 'proposal'
})
proposalSchema.set('toObject', { virtuals: true });
proposalSchema.set('toJSON', { virtuals: true });
module.exports = mongoose.model('proposal', proposalSchema); |
const ajs = require('@tarapiygin/ajs-homeworks-platforms-1');
console.log(ajs.info()); |
tippy('#books-parables', {
theme: 'light-border',
arrow: false,
allowHTML: true,
placement: 'right',
touch: false,
maxWidth: 550,
interactive: true,
interactiveBorder: 1,
content: '<div class="article-component"><h1>Parables</h1><ul><li>Bach, Illusions (1977)</li><li>Bach, Jonathan Livingston Seagull (1970) ★</li><li>Coelho, The Alchemist (1988)</li><li>Hesse, Siddhartha (1922)</li><li>Voltaire, Candide (1759)</li></ul></div>'
}); |
import React, { useState } from 'react';
const Habit = props => {
const [alreadyDidHabit, setAlreadyDidHabit] = useState(<></>);
function handleDelete() {
props.deleteHabit(props.id);
}
function handleClick() {
if (!props.chooseHabit && !props.routineHabit) {
props.changeView('scheduledHabit');
props.currentHabit(props.id);
} else if (!props.routineHabit) {
checkIfHabitInProcess();
}
}
function checkIfHabitInProcess() {
fetch(`/api/habit/${props.userId}`)
.then(result => result.json())
.then(userHabits => {
const resultIdArr = userHabits.filter(item => item.habitId === props.id);
if (resultIdArr.length === 0) {
props.changeView('chooseFrequency');
props.chooseHabitFunction('habitId', props.id);
} else {
setAlreadyDidHabit(<p className='text-danger'>you are already working on this habit</p>);
}
});
}
function canDelete() {
if (!props.chooseHabit) {
return (<i className="fas fa-trash-alt cursor-pointer text-secondary col-2 fa-2x " onClick={handleDelete}></i>);
}
}
return (
<div className="card m-2" >
<div className="row card-body text-left">
<h2 className="text-secondary col-10" onClick={handleClick}>{props.name}</h2>
{canDelete()}
{alreadyDidHabit}
</div>
</div>
);
};
export default Habit;
|
module.exports = function (req, res, next) {
if (!req.cookies.cdc_session) {
res.cookie('last_activity', new Date().getTime());
res.cookie('logged_in', false);
res.cookie('admin', false);
res.cookie('cdc_session', "Enabled");
} else {
res.cookie('last_activity', new Date().getTime())
}
next();
}; |
import React, { useEffect, useState } from 'react';
import socket from '../socket/socket';
import { getCookie } from '../utils/cookies';
import { useDispatch } from 'react-redux';
import { updateUser } from '../redux/user/actionCreators';
const withSocket = (Component) => (props) => {
const [isConnected, setIsConnected] = useState(socket.isConnected());
const dispatch = useDispatch();
useEffect(() => {
if (!socket.isConnected()) {
const username = getCookie('username');
socket.connect(username).then((user) => {
dispatch(updateUser(user));
setIsConnected(true);
console.log('HHEEY');
});
socket.onGetUser((user) => dispatch(updateUser(user)));
}
}, [dispatch]);
return (
<>
{isConnected && (
<Component
socket={socket}
{...props}
/>
)}
</>
);
}
export default withSocket; |
import styled from 'styled-components';
const Buttons = styled.div`
margin-top: 2em;
text-align: center;
`;
export const Styles = {
Buttons,
};
|
Ext.require([
'Ext.form.*'
]);
Ext.define("gigade.Vendor", {
extend: 'Ext.data.Model',
fields: [
{ name: "vendor_id", type: "string" },
{ name: "vendor_name_simple", type: "string" }]
});
var VendorStore = Ext.create('Ext.data.Store', {
model: 'gigade.Vendor',
autoLoad: true,
proxy: {
type: 'ajax',
url: "/WareHouse/GetVendorName",
actionMethods: 'post',
reader: {
type: 'json',
root: 'data'
}
}
});
Ext.onReady(function () {
var formPanel = Ext.create('Ext.form.Panel', {
frame: false,
width: 980,
bodyPadding: 30,
border: false,
items: [
{
html: '<div class="capion">提示:匯出主料位商品摘除報表</div>',
frame: false,
border: false
},
{
xtype: 'combobox',
allowBlank: true,
name: 'search',
id: 'search',
editable: false,
fieldLabel: SEARCH,
labelWidth: 40,
queryMode: 'local',
store: VendorStore,
submitValue: true,
displayField: 'vendor_name_simple',
valueField: 'vendor_id',
forceSelection: false,
value: '0'
}
,
{
xtype: 'button',
text: "確定匯出",
margin: ' 20,30,10,0',
id: 'btnQuery',
buttonAlign: 'center',
handler: function () {
//alert(Ext.getCmp('product_id').getValue());
window.open('/WareHouse/GetIlocReportList?search=' + Ext.getCmp('search').getValue());
}
}
],
renderTo: Ext.getBody()
});
});
|
import React from "react";
import styled from "styled-components/macro";
import "./App.css";
import { PlayerContext } from "./Contexts/PlayerContext";
import TranscriptSentence from "./TranscriptSentence.js";
import SearchResultTranscriptSentence from "./SearchResultTranscriptSentence.js";
import IntroSentence from "./IntroSentence.js";
import { useDispatch, useSelector } from "react-redux";
import { recordTranslationMP3PlayerState } from "./actions";
import {
getSimplifiedSentences,
getTranslationPlaying,
getTranslationTimeCodeAndUUID,
getMP3PlayerState,
getSearchResults,
getTranslationMP3PlayerState,
getUUIDPlaying,
getShowTranslation,
getShouldTranslationsAutoPlay,
} from "./reducers";
import { updateShouldTranslationsAutoPlay } from "./actions";
import {
COLORS_SHOPIFY_BLUE_PALLETE,
TRANSLATION_MP3_PLAYER_STATES,
} from "./constants.js";
import { isMobile } from "react-device-detect";
import { IoMdLock } from "react-icons/io";
import SpinnerJustKF from "./Singles/SpinnerJustKF";
// import { combineReducers } from "redux";
function Scrolltext(heightOfText) {
const playerContext = React.useContext(PlayerContext);
const dispatch = useDispatch();
const [toggle, setToggle] = React.useState(false);
let simplifiedSentences = useSelector(getSimplifiedSentences);
let uuidPlaying = useSelector(getUUIDPlaying);
const [currentUUID, setcurrentUUID] = React.useState({
uuid: "intro-uuid",
start: 0.1,
end: 77,
});
const [isLoaded, setIsLoaded] = React.useState(false);
const [playerWasClicked, setplayerWasClicked] = React.useState(false);
const [translatedAudioSrc, setTranslatedAudioSource] = React.useState(
"https://us-east-1.linodeobjects.com/podcast-files/1__Merci_79afef9c-2b39-452e-888f-27c63c439374.mp3"
);
let translationPlaying = useSelector(getTranslationPlaying);
let translationTimeCodeUUID = useSelector(getTranslationTimeCodeAndUUID);
let podcast_player_state = useSelector(getMP3PlayerState);
let translation_podcast_player_state = useSelector(
getTranslationMP3PlayerState
);
let search_results = useSelector(getSearchResults);
let showTranslation = useSelector(getShowTranslation);
let shouldTranslationsAutoPlay = useSelector(getShouldTranslationsAutoPlay);
const audioref = React.useRef(null);
React.useEffect(() => {
// let filename =
// "https://us-east-1.linodeobjects.com/podcast-files/third/" +
// translationTimeCodeUUID.translated_filename;
let filename =
"https://us-east-1.linodeobjects.com/podcast-files/pureChimp/" +
translationTimeCodeUUID.translated_filename;
setTranslatedAudioSource(filename);
}, [translationTimeCodeUUID, translationPlaying]);
// loadup
React.useEffect(() => {
async function getTranscriptSentences() {
// eslint-disable-next-line
let computed_transcript = await playerContext.computeTranscript();
setIsLoaded(true);
}
getTranscriptSentences();
dispatch(
recordTranslationMP3PlayerState(TRANSLATION_MP3_PLAYER_STATES.PAUSED)
);
if (audioref.current !== null) {
audioref.current.addEventListener(
"seeking",
function () {
console.log("seeked done");
},
true
);
}
// eslint-disable-next-line
}, []);
React.useEffect(() => {
if (audioref.current !== null) {
if (
translation_podcast_player_state ===
TRANSLATION_MP3_PLAYER_STATES.PLAYING
) {
audioref.current.play();
} else if (
translation_podcast_player_state ===
TRANSLATION_MP3_PLAYER_STATES.PAUSED
) {
audioref.current.pause();
}
}
}, [translation_podcast_player_state]);
//uuidPlaying
React.useEffect(() => {
// console.log("uuidPlaying changed");
// console.log(shouldTranslationsAutoPlay.shouldTranslationsAutoPlay);
// console.log(audioref.current);
if (audioref.current !== null) {
audioref.current.addEventListener(
"play",
function () {
console.log("translaiton playing");
dispatch(
recordTranslationMP3PlayerState(
TRANSLATION_MP3_PLAYER_STATES.PLAYING
)
);
},
true
);
audioref.current.addEventListener(
"pause",
function () {
console.log("translaiton paused");
dispatch(
recordTranslationMP3PlayerState(
TRANSLATION_MP3_PLAYER_STATES.PAUSED
)
);
},
true
);
}
if (uuidPlaying !== undefined) {
setcurrentUUID(uuidPlaying);
let element = document.getElementById(uuidPlaying.uuid);
if (element !== null && element !== undefined) {
element.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
if (
shouldTranslationsAutoPlay.shouldTranslationsAutoPlay &&
audioref.current !== null
) {
audioref.current.onloadeddata = function () {
console.log("loaded");
audioref.current.play();
};
}
}
}
// eslint-disable-next-line
}, [uuidPlaying, showTranslation]);
React.useEffect(() => {
dispatch(updateShouldTranslationsAutoPlay(false));
if (uuidPlaying !== undefined) {
setcurrentUUID(uuidPlaying);
let element = document.getElementById(uuidPlaying.uuid);
if (element !== null && element !== undefined) {
element.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
}
}
// eslint-disable-next-line
}, [showTranslation]);
React.useEffect(() => {
if (
podcast_player_state === "playing" ||
podcast_player_state === "paused"
) {
if (playerWasClicked === false) {
setplayerWasClicked(true);
console.log("setting player state");
}
}
setToggle(!toggle);
// eslint-disable-next-line
}, [podcast_player_state]);
if (isMobile && playerWasClicked === false) {
return (
<UnlockWarning>
<div>
<IoMdLock size={60} color={"#EEC200"}></IoMdLock>
</div>
<WarningText>
Mobile devices require you to click play first!
</WarningText>
</UnlockWarning>
);
}
if (isLoaded === false) {
return (
<Loading>
<LoadingFlex>
<LoadingSpinner>
<SpinnerJustKF></SpinnerJustKF>
</LoadingSpinner>
<LoadingText>
Loading up{" "}
<a href={"https://www.justheard.ca:8000/returnCombined"}>
transcript.
</a>
</LoadingText>
</LoadingFlex>
</Loading>
);
}
return (
<ScrollWrapper>
<TranscriptList>
{
//eslint-disable-next-line
simplifiedSentences.map((element, i) => {
if (i === 0) {
return (
<IntroSentence
sentence_object={element}
key={element.uuid}
englishHighlighted={
element.uuid === currentUUID.uuid &&
translationPlaying === false
}
translatedUUID={element.uuid + "trans"}
translatedHightlighted={
element.uuid === translationTimeCodeUUID.uuid &&
translationPlaying
}
next_start_time={element.next_start_time}
></IntroSentence>
);
}
if (
search_results === undefined ||
search_results.searchResults.filtered_sentences === undefined ||
search_results.searchResults.filtered_sentences.length === 0
) {
return (
<div key={element.uuid + "topdiv"}>
<TranscriptSentence
sentence_object={element}
key={element.uuid}
englishHighlighted={element.uuid === currentUUID.uuid}
translatedUUID={element.uuid + "trans"}
translatedHightlighted={
element.uuid === translationTimeCodeUUID.uuid
}
next_start_time={element.next_start_time}
i_from_list={i}
></TranscriptSentence>
{element.uuid === translationTimeCodeUUID.uuid &&
translationPlaying &&
showTranslation &&
shouldTranslationsAutoPlay.shouldTranslationsAutoPlay ? (
<AudioFlex>
<AudioDivBelowTrans
controls
autoPlay
ref={audioref}
src={translatedAudioSrc}
></AudioDivBelowTrans>
</AudioFlex>
) : (
<div></div>
)}
{element.uuid === translationTimeCodeUUID.uuid &&
translationPlaying &&
showTranslation &&
!shouldTranslationsAutoPlay.shouldTranslationsAutoPlay ? (
<AudioDivBelow
controls
ref={audioref}
src={translatedAudioSrc}
></AudioDivBelow>
) : (
<div></div>
)}{" "}
</div>
);
} else if (
search_results.searchResults.filtered_sentences.length > 0 &&
search_results.searchResults.filtered_sentences.includes(
element.uuid
)
) {
return (
<div>
<TimeDividerTop>
<TimeText>{element.time_string}</TimeText> <Line></Line>
</TimeDividerTop>
<SearchResultTranscriptSentence
sentence_object={element}
key={element.uuid}
englishHighlighted={
element.uuid === currentUUID.uuid &&
translationPlaying === false
}
translatedUUID={element.uuid + "trans"}
translatedHightlighted={
element.uuid === translationTimeCodeUUID.uuid &&
translationPlaying
}
next_start_time={element.next_start_time}
search_phrase={
search_results.searchResults.sentenceSearchText
}
original_search_phrase={
search_results.searchResults.original_search_phrase
}
></SearchResultTranscriptSentence>
{/* I have to do this because when the translations show up again after selecting the quebec flag, I don't want it to autoplay. However, if the user has clicked on the translation, I do want it to autoplay. */}
{element.uuid === translationTimeCodeUUID.uuid &&
translationPlaying &&
showTranslation &&
shouldTranslationsAutoPlay.shouldTranslationsAutoPlay ? (
<AudioDivBelow
controls
autoPlay
ref={audioref}
src={translatedAudioSrc}
></AudioDivBelow>
) : (
<div></div>
)}
{element.uuid === translationTimeCodeUUID.uuid &&
translationPlaying &&
showTranslation &&
!shouldTranslationsAutoPlay.shouldTranslationsAutoPlay ? (
<AudioDivBelow
controls
ref={audioref}
src={translatedAudioSrc}
></AudioDivBelow>
) : (
<div></div>
)}
</div>
);
}
})
}
</TranscriptList>
</ScrollWrapper>
);
}
const AudioDivBelow = styled.audio`
width: 48%;
height: 20px;
padding-left: 440px;
margin-top: -7px;
z-index: 5;
position: absolute;
@media (max-width: 800px) {
padding-left: 0px;
width: 80%;
}
::-webkit-media-controls-panel {
height: 20px;
border-radius: 5px;
background-color: white;
padding-left: 2px;
}
::-webkit-media-controls-play-button {
background-color: white;
}
::-webkit-media-controls-volume-slider-container {
display: hidden;
visibility: hidden;
}
`;
const AudioFlex = styled.div`
display: flex;
flex-direction: column;
`;
const AudioDivBelowTrans = styled.audio`
width: 50%;
height: 20px;
margin-top: -7px;
z-index: 5;
align-self: flex-end;
padding-right: 10px;
@media (max-width: 800px) {
padding-right: 0px;
padding-left: 0px;
width: 100%;
}
::-webkit-media-controls-panel {
height: 20px;
border-radius: 5px;
background-color: white;
}
::-webkit-media-controls-play-button {
background-color: white;
}
::-webkit-media-controls-volume-slider-container {
display: hidden;
visibility: hidden;
}
`;
const ScrollWrapper = styled.div`
display: flex;
flex-direction: column;
align-items: stretch;
/* max-width: 1800px; */
`;
const TranscriptList = styled.div`
display: flex;
flex-direction: column;
justify-content: flex-start;
overflow-y: scroll;
max-width: 960px;
transform: translateX(-50px); /* background-color: red; */
bottom: 20px;
top: 400px;
position: absolute;
@media (max-width: 800px) {
top: 330px;
transform: translateX(-10px); /* background-color: red; */
}
`;
const Line = styled.div`
border-bottom: 1px dashed ${COLORS_SHOPIFY_BLUE_PALLETE.Blue};
height: 1px;
flex-grow: 2;
padding-top: 9px;
`;
const TimeDividerTop = styled.div`
padding-left: 11px;
display: flex;
flex-direction: row;
@media (max-width: 600px) {
padding-left: 10px;
}
`;
const TimeText = styled.div`
padding-bottom: 10px;
color: ${COLORS_SHOPIFY_BLUE_PALLETE.Dark};
padding-right: 5px;
`;
const LoadingText = styled.div``;
const LoadingFlex = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
`;
const Loading = styled.div`
max-width: 1000px;
background-color: white;
padding-top: 20px;
`;
const LoadingSpinner = styled.div`
padding-left: 20px;
`;
const WarningText = styled.div`
padding: 10px;
/* color: #573b00; */
`;
const UnlockWarning = styled.div`
width: 250px;
background-color: #f4f6f8;
border-radius: 10px;
margin: auto;
display: flex;
flex-direction: column;
text-align: center;
`;
export default Scrolltext;
|
/* eslint-disable no-console */
import sass from 'gulp-sass';
import {
dest, src, watch, series,
} from 'gulp';
import autoprefixer from 'gulp-autoprefixer';
import BrowserSync from 'browser-sync';
import eslint from 'gulp-eslint';
const jasmineBrowser = require('gulp-jasmine-browser');
const browserSync = BrowserSync.create();
export const test = () => (
src('tests/spec/extraSpec.js')
.pipe(jasmineBrowser.specRunner({ console: true }))
.pipe(jasmineBrowser.server({ port: 8888 }))
);
export const lint = () => (
src(['js/**/*.js'])
// eslint() attaches the lint output to the "eslint" property
// of the file object so it can be used by other modules.
.pipe(eslint())
// eslint.format() outputs the lint results to the console.
// Alternatively use eslint.formatEach() (see Docs).
.pipe(eslint.format())
// To have the process exit with an error code (1) on
// lint error, return the stream and pipe to failAfterError last.
.pipe(eslint.failAfterError())
);
export const styles = () => src('sass/**/*.scss')
.pipe(sass())
.on('error', sass.logError)
.pipe(autoprefixer())
.pipe(dest('./css'))
.pipe(browserSync.stream());
export const log = (done) => {
console.log('In log file');
done();
};
export const watchScss = (done) => {
watch(['sass/**/*.scss'], styles);
watch(['js/**/*.js'], lint);
browserSync.init({
server: './',
});
done();
};
export default series(styles, lint, watchScss);
|
const passport = require("passport");
exports.isLoggedIn = (req, res, next) => {
passport.authenticate("jwt", { session: false }, (err, user) => {
if (user) {
req.user = user;
next();
} else {
const message = encodeURIComponent("로그인이 필요합니다");
res.status(403).redirect(`/?error=${message}`);
}
})(req, res, next);
};
exports.isNotLoggedIn = (req, res, next) => {
passport.authenticate("jwt", { session: false }, (err, user) => {
if (!user) {
next();
} else {
const message = encodeURIComponent("로그인한 상태입니다");
res.status(403).redirect(`/?error=${message}`);
}
})(req, res, next);
};
exports.noMatter = (req, res, next) => {
passport.authenticate("jwt", { session: false }, (err, user) => {
if (user) {
req.user = user;
}
next();
})(req, res, next);
};
|
exports.up = function(knex) {
return knex.schema.createTable('videosgroups', t => {
t.string('id').primary()
t.string('key').notNull()
t.string('title').notNull()
t.float('height_ratio').notNull()
t.string('p720').notNull()
t.string('p480').notNull()
t.string('p360').notNull()
t.string('p144').notNull()
t.timestamp('created_at').notNullable().defaultTo(knex.fn.now());
t.timestamp('updated_at').notNullable().defaultTo(knex.fn.now());
})
};
exports.down = function(knex) {
return knex.schema.dropTable(`videosgroups`)
};
|
export const HOME = '/home';
export const LANDING = '/';
export const NOTES = '/notes';
export const CREATE_NOTE = '/create_note';
export const VIEW_NOTE = '/view_note';
|
import React, { Component } from 'react';
import { Link, Route , Redirect} from 'react-router-dom';
import '../../src/App.css';
import axios from 'axios'
import HeaderAdmin from './adminNavbar'
import {connect} from 'react-redux'
class adminDetails extends Component{
securityAdmin(){
if(this.props.admin === 0){
this.setState({redirect_admin: true})
return(
alert('this is the admin page, please login if you are the admin')
)
}
}
render(){
return (
<div>
{this.securityAdmin()}
<HeaderAdmin/>
<br/>
<br/>
<center>
<Link to="/adminProduct"><h3>Product</h3></Link>
<br/>
<Link to="/adminCategory"><h3>Category</h3></Link>
<br/>
<Link to="/adminInvoice"><h3>Invoice</h3></Link>
</center>
</div>
)
}
}
const mapStateToProps = (state) =>{
const admin = state.admin;
return{
admin
}
}
export default connect (mapStateToProps) (adminDetails) |
import PropTypes from 'prop-types';
import { useState, useEffect } from 'react';
import { withTranslation } from '../../i18n';
import useSweeper, { routeSweeper } from '../../hooks/useSweeper';
const MonsterSweeperButton = ({ t, monster, size }) => {
const [active, setActive] = useState(false);
const { data: sweepers } = useSweeper();
const openSweeperPage = (event) => {
routeSweeper(monster);
};
useEffect(() => {
setActive(sweepers && sweepers.includes(monster.id));
}, [sweepers]);
return (
<button
type="button"
title={t('sweeper-monster')}
className={`monster-sweeper-button ${active ? 'active' : ''} ${size}`}
onClick={openSweeperPage}
/>
);
};
MonsterSweeperButton.propTypes = {
monster: PropTypes.shape({
id: PropTypes.string,
name: PropTypes.string,
slug: PropTypes.string,
}).isRequired,
size: PropTypes.string,
};
MonsterSweeperButton.defaultProps = {
size: '',
};
export default withTranslation('monster')(MonsterSweeperButton);
|
var owners_names_dic = {
"1":"Fer Romo",
"2":"Victor Plata",
"3":"Cesar Hdz",
"4":"Alex Falconi",
"5":"Juan Pablo",
"6":"Fer Garza",
"7":"Mau Reyna",
"8":"Ana Pau",
"9":"Karely",
"10":"Claudia F",
"11":"Fran R",
"12":"Aylin V",
"13":"Daniel G",
"14":"Eduardo D",
"15":"Paulina M",
"16":"Aranza S",
"17":"Ayde M",
"18":"Cinthia U",
"19":"Miguel P",
"20":"Eduardo G"
};
var dogs_names_dic ={
"1":"Coco",
"2":"Lucas",
"3":"Max",
"4":"Chilakil",
"5":"Chinis",
"6":"Otis",
"7":"Rex",
"8":"Rudy",
"9":"Rufus",
"10":"Rocco",
"11":"Baxter",
"12":"Firulais",
"13":"Duke",
"14":"Loki",
"15":"Toby",
"16":"Sparky",
"17":"Ziggy",
"18":"Ollie",
"19":"Lilly",
"20":"Snoopy"
}
var owners_choice = {};
var own_size = 20;
function myFunction(){
for(let i =1; i<=own_size;i++){
document.getElementById("sd"+i).style.backgroundImage="url('./dog_images/perro"+i+".png')";
document.getElementById("o"+i).style.backgroundImage="url('./owner_images/dueno"+i+".png')";
owners_choice["dueno"+i+".png"] = 0;
var x=document.getElementById('myTable').insertRow(-1);
var y = x.insertCell(0);
var z = x.insertCell(1);
var w = x.insertCell(2);
y.innerHTML=owners_names_dic[i];
var owner_first_choice = ownersDic["dueno"+i+".png"][0];
owner_first_choice = owner_first_choice.replace(/[^\d\s]|_/g, "").replace(/\s+/g, " ");
z.innerHTML=dogs_names_dic[owner_first_choice];
w.innerHTML="0";
var xd =document.getElementById('myTableDogs').insertRow(-1);
var yd = xd.insertCell(0);
var zd = xd.insertCell(1);
var wd = xd.insertCell(2);
yd.innerHTML=dogs_names_dic[i];
var dog_first_choice = dogsDic["perro"+i+".png"][0];
dog_first_choice = dog_first_choice.replace(/[^\d\s]|_/g, "").replace(/\s+/g, " ");
zd.innerHTML=owners_names_dic[dog_first_choice];
wd.innerHTML="0";
x=document.getElementById('myTableM').insertRow(-1);
y = x.insertCell(0);
z = x.insertCell(1);
w = x.insertCell(2);
y.innerHTML=owners_names_dic[i];
owner_first_choice = ownersDic["dueno"+i+".png"][0];
owner_first_choice = owner_first_choice.replace(/[^\d\s]|_/g, "").replace(/\s+/g, " ");
z.innerHTML=dogs_names_dic[owner_first_choice];
w.innerHTML="0";
x=document.getElementById('myTableDogsM').insertRow(-1);
y = x.insertCell(0);
z = x.insertCell(1);
w = x.insertCell(2);
y.innerHTML=owners_names_dic[i];
owner_first_choice = ownersDic["dueno"+i+".png"][0];
owner_first_choice = owner_first_choice.replace(/[^\d\s]|_/g, "").replace(/\s+/g, " ");
z.innerHTML=dogs_names_dic[owner_first_choice];
w.innerHTML="0";
}
}
function inValues(dict, val){
for(var key in dict){
if (val === dict[key])
return true;
}
return false;
}
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
function isDogFoster(dog, array){
var i = 0;
for(i; i < array.length;i++){
if (array[i] === dog)
return true;
}
return false;
}
function getIndexOf(array, val){
for(let i = 0; i < array.length; i++){
if (array[i].localeCompare(val) === 0)
return i;
}
return -1;
}
function shuffle(array) {
var ar = array.slice(0);
for(let i = ar.length - 1; i > 0; i--){
const j = Math.floor(Math.random() * i)
const temp = ar[i]
ar[i] = ar[j]
ar[j] = temp
}
return ar;
}
var owners = []
for(let i = 1;
i<=own_size;i++){
owners.push("dueno"+i.toString()+".png");
}
var dogs = []
for(let i = 1;i<=own_size;i++){
dogs.push("perro"+i.toString()+".png");
}
var ownersDic = {}
for(let i =0; i<owners.length; i++){
var dogsList = shuffle(dogs)
ownersDic[owners[i]]= dogsList;
}
var dogsDic = {}
for(let i =0; i<dogs.length; i++){
var ownersList = shuffle(owners);
dogsDic[dogs[i]]= ownersList
}
function getOwners(){
return owners;
}
function getDogs(){
return dogs;
}
var possible_matches = {};
var foster_dogs = dogs.slice(0);
function getAnimations(){
var animation = [];
while(foster_dogs.length != 0){
let ownerIndx = 0;
for(var owner in ownersDic){
for(var i = 0; i < ownersDic[owner].length; i++){
var dog = ownersDic[owner][i];
if(isDogFoster(dog, foster_dogs) && !inValues(possible_matches, owner)) {
removeA(foster_dogs, dog);
possible_matches[dog] = owner;
animation.push(owner+" will potentialy adopt " + dog);
break;
}else if (getIndexOf(dogsDic[dog],owner) < getIndexOf(dogsDic[dog],possible_matches[dog]) && !inValues(possible_matches, owner)){
animation.push(owner + "will potentially adopt "+ dog);
possible_matches[dog] = owner;
break;
}
}
ownerIndx ++;
}
}
var results = [possible_matches, animation]
return results;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function findMatches(){
const results = getAnimations();
var matches = results[0];
var animation = results[1];
let i =1 ;
var dogs_choice = {};
for(var dog in matches){
var owner = matches[dog];
dogs_choice[dog] = parseInt(getIndexOf(dogsDic[dog],matches[dog])+1);
owners_choice[owner] = parseInt(getIndexOf(ownersDic[owner], dog))+1;
var dogs_table = document.getElementById('myTableDogs');
var owners_table = document.getElementById('myTable');
var dogs_tableM = document.getElementById('myTableDogsM');
var owners_tableM = document.getElementById('myTableM');
//var pic = 'url(' + imgUrl + ')';
await sleep(100);
var dogId =matches[dog].replace(/[^\d\s]|_/g, "").replace(/\s+/g, " ");
document.getElementById("d"+dogId).style.backgroundImage = "url('./dog_images/"+dog+"')";
document.getElementById("dn"+dogId).textContent = dogs_names_dic[dog.replace(/[^\d\s]|_/g, "").replace(/\s+/g, " ")];
document.getElementById("l"+dogId).textContent = "Will adopt";
document.getElementById("sd"+dogId+"t").style.color = "green";
document.getElementById("sd"+dogId+"t").textContent = "ADOPTED";
i++;
}
i = 1;
for(var owner in owners_choice){
owners_table.rows[i].cells[2].innerHTML = owners_choice[owner];
owners_tableM.rows[i].cells[2].innerHTML = owners_choice[owner];
i++;
}
i = 1;
console.log(dogs_choice);
for(var dog in dogs_choice){
dogs_table.rows[dog.replace(/[^\d\s]|_/g, "").replace(/\s+/g, " ") ].cells[2].innerHTML = dogs_choice[dog];
dogs_tableM.rows[dog.replace(/[^\d\s]|_/g, "").replace(/\s+/g, " ") ].cells[2].innerHTML = dogs_choice[dog];
i++;
}
} |
const config = {
frequency: 10000,
botherFrequency: 3000,
drinkDate: null,
nextReminder: null,
version: '0.0.1'
};
const text = {
installWelcomeTitle: '欢迎使用喝水控!',
installWelcomeContent: '喝水喝水喝水,不喝我就烦死你!ヾ(o◕∀◕)ノ',
updateWelcomeTitle: '喝水控更新啦!',
updateWelcomeContent: '本次更新的内容有:额?我这是初版啊,怎么会提示你已经更新了呢?如果你看到了这条消息,在chrome商店给我留言哟',
todayTitle: '开启今天的喝水之旅了哟!',
todayContent: `从现在开始,每过${config.frequency/60000}分钟我就会提醒你喝水!(。・\`ω´・)`,
beginTitle: '我又开始运作了!',
beginContent: `从现在开始,每过${config.frequency/60000}分钟我就会提醒你喝水!(。・\`ω´・)`,
drinkTitle: '多喝热水!',
drinkContent: '又到了喝水的时候啦,快快去接水喝!(≖ ‿ ≖)✧ ',
drinkConfirm: '你有喝水嘛?',
botherTitle: '怎么还不喝水!',
botherContent: '信不信我烦死你,快去喝水!(/= _ =)/~┴┴'
};
const showNotification = (message, onButtonClick = () => {},id = 'introduce') => {
chrome.notifications.getPermissionLevel((level) => {
if(level === 'granted') {
const notificationOptions = {
type: 'basic',
title: message.title,
message: message.message,
iconUrl: message.icon || chrome.extension.getURL("asset/pic3.jpg"),
buttons: id === 'reminder' ?
[{title: '我有喝水哦!'}, {title: '手头有点事我过会再喝~'}] : [],
requireInteraction: id === 'reminder'
};
chrome.notifications.create(id, notificationOptions);
chrome.notifications.onButtonClicked.addListener((clickedId, buttonIndex) => {
onButtonClick(buttonIndex);
})
} else {
chrome.permissions.request('notifications', (granted) => {
if(granted) {
showNotification(message, onClick, id);
}
});
}
})
};
const clearNotification = () => {
chrome.notifications.clear('reminder');
};
// type drink喝水提醒 bother拒绝后骚扰提醒
const setTimeInterval = (type) => {
const intervalConfig = {
drink: {
interval: config.frequency,
title: text.drinkTitle,
content: text.drinkContent,
},
bother: {
interval: 300,
title: text.botherTitle,
content: text.botherContent
}
};
const usingConfig = intervalConfig[type];
const timer = setInterval(() => {
showNotification({
title: usingConfig.title,
content: usingConfig.content
});
}, usingConfig.interval)
}; |
var net=require('net');
var sockets=[];
var serv=net.Server(function(socket){
sockets.push(socket);
socket.on('data',function(input){
for(var i=0;i<sockets.length;i++){
if(sockets[i]==socket)continue;//not to listen to own socket
sockets[i].write(input);
}
});
socket.on('end',function(){
var i=sockets.indexOf(socket);
sockets.splice(i,1);
});
});
serv.listen(8000);
|
$(document).ready(function(){
var doc = $(document);
var body = $("body,html");
$(window).scroll(function(){
console.log( doc.scrollTop() );
$(".menu").removeClass("active");
if ( doc.scrollTop() > 0 ) {
$(".menu_btn__text").removeClass("active");
}
else {
$(".menu_btn__text").addClass("active");
}
});
$(".menu_btn").click(function(){
$(".menu").toggleClass("active");
});
$(".menu_close").click(function(){
$(".menu").toggleClass("active");
});
$(".form_btn").click(function() {
if (!$(this).hasClass("submit")) {
$(this).removeClass("active");
$(".footer_form_info_phone").removeClass("active");
$(this).next(".form_btn").addClass("active");
$(".footer_form_info input[type='text']").addClass("active");
}
});
$(".footer_copy__go_up").click(function() {
body.animate({scrollTop: 0}, 2000);
});
}); |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
import Cookies from 'js-cookie';
import './Framemenu.css';
class SubMenu extends Component {
constructor(props) {
super(props);
this.state = { menuSwitchOn: false };
}
render() {
return <div>
<dd onClick={ e => {
e.nativeEvent.stopImmediatePropagation() // 阻止事件冒泡, 阻止div里的点击这个动作层层上传,不让这次点击被document监听到
this.setState({ menuSwitchOn: !this.state.menuSwitchOn })
}}><i className="fl drop-down"></i>{this.props.treeNode.name}</dd>
<ul className="myMenu-nav-2" style={this.state.menuSwitchOn ? {display: "block"} : { display: "none"}}>
{
this.props.treeNode.subMenuList? this.props.treeNode.subMenuList.map(item => {
return <li key={item.id}><a href={item.url}>{item.name}</a></li>
}) : <dd key={item.id}>
<i className="drop-right fl flhide"></i>
<a href="#">{treeNode.name}</a>
</dd>
}
</ul>
</div>
}
}
SubMenu.propTypes = {
treeNode: PropTypes.object,
}
class Menu extends Component {
constructor(props) {
super(props);
this.state = { menuTree: props.menuTree };
}
shouldComponentUpdate(nextProps, nextState) {
return JSON.stringify(nextProps) !== JSON.stringify(this.props)
}
render() {
return <div>
{this.props.menuTree.map(treeNode => {
return treeNode.subMenuList ? <SubMenu key={treeNode.id} treeNode={treeNode} /> : <dd key={treeNode.id}>
<i className="drop-right fl flhide"></i>
<a href="#">{treeNode.name}</a>
</dd>}
)}
</div>
}
}
Menu.propTypes = {
menuTree: PropTypes.array,
}
export default class Framemenu extends Component {
constructor(props) {
super(props);
this.state = {
menuSwitchOn: false,
menuTree: []
}
}
hideAllMenu = () => {
this.setState({ menuSwitchOn: false })
}
showAllMenu = (event) => {
this.stopPropagation(event);
this.setState({ menuSwitchOn: !this.state.menuSwitchOn })
}
stopPropagation(e) {
e.nativeEvent.stopImmediatePropagation();
}
componentDidMount() {
document.addEventListener('click', this.hideAllMenu);
// const Authorization = Cookies.get('Authorization');
axios.get("/sysware/api/menu/queryMenu").then(res => {
this.setState({ menuTree: res.data.data });
// console.log(res.data.data)
})
}
render() {
return <div id="uiframe-myplace-nav" className="newFrameMenu">
<div className="myMenu">
<div className="myMenu-functions fl">
<a href="javascript:void(0)" className="myMenu-btn fl" onClick={this.showAllMenu}></a>
<dl className={this.state.menuSwitchOn ? "myMenu-nav-1" : "myMenu-nav-1 myMenu-nav-1-collapse" }>
<Menu menuTree={this.state.menuTree} />
</dl>
<span id="navMenuNameOrg" className="myMenu-btn-info fl">{this.props.menuName || '仪表板'}</span>
</div>
</div>
</div>
}
}
Framemenu.propTypes = {
menuName: PropTypes.string
} |
var indexSectionsWithContent =
{
0: "abcdefghilnoprstuvw",
1: "beoprt",
2: "o",
3: "eopru",
4: "abcdefghilnoprstw",
5: "ailos",
6: "cinorsv",
7: "a",
8: "beot"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "namespaces",
3: "files",
4: "functions",
5: "variables",
6: "typedefs",
7: "enums",
8: "pages"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Namespaces",
3: "Files",
4: "Functions",
5: "Variables",
6: "Typedefs",
7: "Enumerations",
8: "Pages"
};
|
"use strict";
(function() {
let currentCategory;
var alreadySelected = false;
window.onload = function() {
$("view-all").onclick = fetchCategories;
$("next").onclick = questionOrAnswer;
};
function fetchCategories() {
// use fetch HTTP request to get the categories
// call displayCategories
if (alreadySelected == false){
document.getElementById("category-view").style.display = 'block';
document.getElementById("categories-heading").style.display = 'block';
document.getElementById("question-view").style.display = 'block';
let hrx = new XMLHttpRequest();
hrx.open("GET", "trivia.php?mode=categories");
hrx.onload = displayCategories;
hrx.send();
alreadySelected = true;
}
}
function questionOrAnswer() {
// your code here
document.getElementById("card").style.display = 'block';
if (document.getElementById("Question")){
var Question = document.getElementById('Question');
Question.remove();
}
showTrivia();
}
// leave the showTrivia function as it is.
function showTrivia() {
let url = "trivia.php?mode=category";
if (currentCategory) {
url += "&name=" + currentCategory;
}
fetch(url)
.then(checkStatus)
.then(JSON.parse)
.then(displayQuestion);
}
function displayQuestion(response) {
//your code here
var outside = document.getElementById("card");
var temp = document.createElement("id");
temp.id = "Question";
var p = document.createElement("p");
p.appendChild(document.createTextNode(response));
temp.appendChild(p);
outside.appendChild(temp);
}
function displayCategories() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
for (var i = 0; i < myArr.length; i++) {
var ul = document.getElementById("categories");
var li = document.createElement("li");
var temp = document.createElement("id");
temp.id = myArr[i];
li.appendChild(document.createTextNode(myArr[i]));
temp.appendChild(li);
ul.appendChild(temp);
}
}
}
/// provided helper functions don't change.
function $(id) {
return document.getElementById(id);
}
function qsa(el) {
return document.querySelectorAll(el);
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300 ||
response.status == 0) {
return response.text();
} else {
return Promise.reject(
new Error(response.status + ": " + response.statusText));
}
}
})()
|
import React from "react"
import { useSelector } from "react-redux"
const Notification = () => {
const message = useSelector((state) => state.notification)
if (!message) {
return null
}
console.log("notification message", message)
return <div className={message.type}>{message.text}</div>
}
export default Notification
|
WMS.module("Models", function(Models, WMS, Backbone, Marionette, $, _) {
/***************************************************************************
* Dichiarazioni generiche
***************************************************************************/
var Invoice = Models.Invoice = Backbone.CollectionModel.extend({
defaults: {
code : "",
date : Date.today(),
subject : "",
commissionId : null,
destinationId : null,
paymentTypeId : null,
vatRateId : null,
applyTo : "",
discountPercent : 0,
discountValue : 0,
fullPrice : 0,
discounted : 0,
totalVat : 0,
total : 0,
pending : false
},
maps: [
{ local: "applyTo", remote: "persona_di_riferimento" },
{ local: "code", remote: "codice" },
{ local: "commissionCode", remote: "commessa_codice" },
{ local: "commissionId", remote: "commessa" },
{ local: "date", remote: "data", type: "date" },
{ local: "destinationId", remote: "destinazione" },
{ local: "discounted", remote: "imponibile_netto" },
{ local: "discountPercent", remote: "sconto_percentuale" },
{ local: "discountValue", remote: "sconto_euro" },
{ local: "fullPrice", remote: "imponibile" },
{ local: "paymentTypeCode", remote: "pagamento_label" },
{ local: "paymentTypeId", remote: "pagamento" },
{ local: "pending", remote: "da_confermare" },
{ local: "subject", remote: "oggetto" },
{ local: "total", remote: "totale" },
{ local: "totalVat", remote: "totale_iva" },
{ local: "vatRateId", remote: "aliquota_IVA" },
{ local: "wps", remote: "wps" }
],
validation: {
paymentTypeId : { required: true }
},
initialize: function(options) {
if ((options || {}).urlRoot) {
this.urlRoot = options.urlRoot;
}
Backbone.Model.prototype.initialize.call(this, options);
},
getCommissions : WMS.getCommissions,
getVatRates : WMS.getVatRates,
getPaymentTypes : WMS.getPaymentTypes,
toString: function() {
return this.get("code") + " - " + this.get("subject");
}
});
Models.Invoices = Backbone.Collection.extend({
/**
* Restituisce una lista degli ordini con almeno una riga selezionata.
* @return(array) La lista.
*/
getSelected: function() {
var invoices = [];
_.each(this.models, function(invoice) {
// recupero le righe dell'ordine. fetch:false impedisce il fetch dal server.
var rows = invoice.getRows({ fetch:false });
if (rows && _.where(rows.models, {selected:true}).length > 0) {
invoices.push(invoice);
}
});
return invoices;
},
/**
* Restituisce la lista delle righe selezionate tra tutti gli ordini.
* @return(array) La lista.
*/
getSelectedRows: function() {
var rows = [];
_.each(this.models, function(invoice) {
var _rows = invoice.getRows({fetch:false});
if (_rows) {
rows = rows.concat(_.where(_rows.models, {selected:true}));
}
});
return rows;
}
});
Models.InvoiceRow = Backbone.Model.extend({
defaults: {
articleId : undefined,
description : "",
unitTypeId : undefined,
price : 0,
quantity : 0,
discountPercent : 0,
total : 0,
noteCode : ""
},
maps: [
{ local: "invoiceId", remote: "fattura" },
{ local: "commissionId", remote: "commessa" },
{ local: "commissionCode", remote: "commessa_codice" },
{ local: "estimateId", remote: "preventivo" },
{ local: "estimateCode", remote: "preventivo_codice" },
{ local: "articleId", remote: "articolo" },
{ local: "description", remote: "articolo_descrizione" },
{ local: "articleCode", remote: "articolo_codice" },
{ local: "unitTypeId", remote: "articolo_unita_di_misura" },
{ local: "unitType", remote: "articolo_unita_di_misura_label" },
{ local: "quantity", remote: "quantita" },
{ local: "price", remote: "articolo_prezzo" },
{ local: "total", remote: "totale" },
{ local: "noteRowId", remote: "riga_bolla" },
{ local: "noteCreated", remote: "bollettizzata" },
{ local: "discountPercent", remote: "sconto_percentuale" },
{ local: "noteCode", remote: "riga_bolla_codice" }
],
computed: {
total: {
depends: ["quantity", "price", "discountPercent"],
get: function(fields) {
return fields.quantity * (1 - fields.discountPercent/100) * fields.price;
}
}
},
validation: {
invoiceId : { required: true },
articleId : { required: true },
description : { required: true },
unitTypeId : { required: true },
quantity : { min: 0 },
discountPercent: { min:0, max: 100 }
},
getArticles: WMS.getArticles,
getUnitTypes: WMS.getUnitTypes,
toString: function() {
return this.get("description") + " x " + this.get("quantity");
}
});
Models.InvoiceRows = Backbone.Collection.extend({
model: Models.InvoiceRow
});
/***************************************************************************
* CLIENTI
***************************************************************************/
Models.ClientInvoice = Models.Invoice.extend({
urlRoot: "/api/v1/fatturaCliente/",
defaults: _.extend({}, {
code : "",
date : Date.today(),
clientId : null,
clientCode : ""
}, Models.Invoice.prototype.defaults),
maps: _.union([
{ local: "clientId", remote: "cliente" },
{ local: "clientCode", remote: "cliente_codice" },
{ local: "client", remote: "cliente_label" }
], Models.Invoice.prototype.maps),
validation: _.extend({}, Models.Invoice.prototype.validation, {
clientId : { required: true }
}),
getClients : WMS.getClients,
getDestinations : WMS.getClientDestinations,
canAddRows: function() {
if (this.isNew()) return false;
return Models.ClientInvoiceRow.canCreate();
}
}, {
modelName: "client:invoice"
});
Models.ClientInvoices = Models.Invoices.extend({
url: "/api/v1/fatturaCliente/"
, model: Models.ClientInvoice
, initialize: function(options) {
if((options || {}).url) {
this.url = options.url;
}
Backbone.Collection.prototype.initialize.call(this, options);
}
});
Models.ClientInvoiceRow = Models.InvoiceRow.extend({
urlRoot: "/api/v1/rigaFatturaCliente/",
resetParent: function() {
WMS.request('get:client:invoice', {id: this.get('invoiceId') })
.then(function(invoice) {
invoice.fetch();
});
}
}, {
modelName: "client:invoice:row"
});
Models.ClientInvoiceRows = Models.InvoiceRows.extend({
url: "/api/v1/rigaFatturaCliente/"
, model: Models.ClientInvoiceRow
, getTotal: function() {
return this.reduce(function(memo, value) { return memo + parseFloat(value.get("total")); }, 0);
}
});
_.extend(Models.ClientInvoice.prototype, {
rowsClass: Models.ClientInvoiceRows,
parentName: "fattura"
});
/***************************************************************************
* FORNITORI
***************************************************************************/
Models.SupplierInvoice = Models.Invoice.extend({
urlRoot: "/api/v1/fatturaFornitore/",
defaults: _.extend({}, {
code : "",
date : Date.today(),
supplierId : null,
supplierCode : "",
supplierInvoice : "",
supplierDate : Date.today()
}, Models.Invoice.prototype.defaults),
maps: _.union([
{ local: "supplierId", remote: "fornitore" },
{ local: "supplierCode", remote: "fornitore_codice" },
{ local: "supplier", remote: "fornitore_label" },
{ local: "supplierInvoice", remote: "codice_fattura_fornitore" },
{ local: "supplierDate", remote: "data_fattura_fornitore", type: "date" }
], Models.Invoice.prototype.maps),
validation: _.extend({}, Models.Invoice.prototype.validation, {
supplierId: { required: true }
}),
getSuppliers : WMS.getSuppliers,
getDestinations : WMS.getOwnerDestinations,
canAddRows: function() {
if (this.isNew()) return false;
return Models.SupplierInvoiceRow.canCreate();
}
}, {
modelName: "supplier:invoice"
});
Models.SupplierInvoices = Models.Invoices.extend({
url: "/api/v1/fatturaFornitore/",
model: Models.SupplierInvoice,
initialize: function(options) {
if((options || {}).url) {
this.url = options.url;
}
Backbone.Collection.prototype.initialize.call(this, options);
}
});
Models.SupplierInvoiceRow = Models.InvoiceRow.extend({
urlRoot: "/api/v1/rigaFatturaFornitore/",
resetParent: function() {
WMS.request('get:supplier:invoice', {id: this.get('invoiceId') })
.then(function(invoice) {
invoice.fetch();
});
}
}, {
modelName: "supplier:invoice:row"
});
Models.SupplierInvoiceRows = Models.InvoiceRows.extend({
url: "/api/v1/rigaFatturaFornitore/",
model: Models.SupplierInvoiceRow,
getTotal: function() {
return this.reduce(function(memo, value) { return memo + parseFloat(value.get("total")); }, 0);
}
});
_.extend(Models.SupplierInvoice.prototype, {
rowsClass: Models.SupplierInvoiceRows
, parentName: "fattura"
});
/***************************************************************************
* Gestione richieste
***************************************************************************/
var __getClientInvoiceList = function(params, options) {
var defer = $.Deferred();
params = (params || {});
if (!!params.from && !!params.to) {
var coll = new Models.ClientInvoices(options);
coll.fetch({
data: {
codice : params.code
, cliente : params.clientId
, da : params.from && params.from.toString("yyyy-MM-dd")
, a : params.to && params.to.toString("yyyy-MM-dd")
}
}).always(function() {
defer.resolve(coll);
});
} else {
defer.reject();
}
return defer.promise();
}
WMS.reqres.setHandler("get:client:invoice:list", function(params) {
return __getClientInvoiceList(params);
});
WMS.reqres.setHandler("get:client:invoice:list:nototal", function(params) {
return __getClientInvoiceList(params, { url: "/api/v1/fatturaClienteSenzaTotale/"} );
});
WMS.reqres.setHandler("get:client:invoice", function(id) {
return Models.__fetchModel('clientInvoice', Models.ClientInvoice, id);
});
WMS.reqres.setHandler("get:client:invoice:nototal", function(id) {
return Models.__fetchModel('clientInvoice', Models.ClientInvoice, id, {
urlRoot: "/api/v1/fatturaClienteSenzaTotale/"
});
});
WMS.reqres.setHandler("get:client:invoice:rows", function(id) {
var defer = $.Deferred();
if (typeof id === 'object' ? !id.id : !id) {
defer.resolve(new Models.ClientInvoiceRows());
} else {
WMS.request("get:client:invoice", id)
.then(function(invoice) {
invoice.getRows().then(function(rows) {
defer.resolve(rows);
});
})
.fail(function(error) {
console.error(error);
defer.reject()
});
}
return defer.promise();
});
WMS.reqres.setHandler("get:client:invoice:drop", function(params) {
var defer = $.Deferred();
params = (params || {});
var path = null
, options = null;
if (params.noteRows) {
path = params.id ? params.id + "/crea_righe_da_bolla/" : "crea_fattura_da_righe_bolla/";
options = {
riga_bolla_cliente: params.noteRows
};
}
if(params.orderRows) {
path = params.id ? params.id + "/crea_righe_da_ordine/" : "crea_fattura_da_righe_ordine/";
options = {
riga_ordine_cliente: params.orderRows
};
}
if (!path) {
defer.reject();
} else {
$.post("/api/v1/fatturaCliente/" + path, options)
.then(function(resp) {
var invoice = new Models.ClientInvoice(Models.ClientInvoice.prototype.parse(resp));
defer.resolve(invoice);
WMS.vent.trigger("client:invoice:updated", invoice);
})
.fail(function(error) {
defer.reject(error);
});
}
return defer.promise();
});
WMS.reqres.setHandler("get:client:invoice:print:url", function(id) {
return id === undefined ? "#" : "/anagrafiche/stampa/fatturaCliente/" + id + "/";
});
Models.ClientInvoiceCommission = Backbone.Model.extend({
defaults: {
clientId : null
, commissionId : null
}
, validation: {
commissionId: { required: true }
}
, initialize: function() {
if (!this.get("clientId")) {
throw new Error("ClientId is required.");
}
}
, getClients: function() {
return WMS.request("get:client:list");
}
, getCommissions: function() {
var defer = $.Deferred()
, clientId = this.get("clientId");
$.when(WMS.request("get:commission:list")).then(function(list) {
defer.resolve(list.where({clientId:clientId}));
});
return defer;
}
});
var __getSupplierInvoiceList = function(params, options) {
var defer = $.Deferred();
params = (params || {});
if (!!params.from && !!params.to) {
var coll = new Models.SupplierInvoices(options);
coll.fetch({
data: {
codice : params.code
, fornitore : params.supplierId
, da : params.from && params.from.toString("yyyy-MM-dd")
, a : params.to && params.to.toString("yyyy-MM-dd")
}
}).always(function() {
defer.resolve(coll);
});
} else {
defer.reject();
}
return defer.promise();
}
WMS.reqres.setHandler("get:supplier:invoice:list", function(params) {
return __getSupplierInvoiceList(params);
});
WMS.reqres.setHandler("get:supplier:invoice:list:nototal", function(params) {
return __getSupplierInvoiceList(params, { url: "/api/v1/fatturaFornitoreSenzaTotale/"} );
});
var __getSupplierInvoice = function(id, options) {
//options = (options || {});
var defer = $.Deferred();
if (typeof id === 'object' ? !id.id : !id) {
defer.resolve();
} else {
if (_.isObject(id)) {
id = id.id;
}
//options[id] = id;
var model = new Models.SupplierInvoice({id: id}, options);
model.fetch()
.success(function() { defer.resolve(model); })
.fail(function() { defer.resolve(); });
}
return defer.promise();
}
WMS.reqres.setHandler("get:supplier:invoice", function(id) {
return __getSupplierInvoice(id);
});
WMS.reqres.setHandler("get:supplier:invoice:nototal", function(id) {
return __getClientInvoice(id, { urlRoot: "/api/v1/fatturaFornitoreSenzaTotale/" });
});
WMS.reqres.setHandler("get:supplier:invoice:rows", function(id) {
var defer = $.Deferred();
if (typeof id === 'object' ? !id.id : !id) {
defer.resolve(new Models.SupplierInvoiceRows());
} else {
WMS.request("get:supplier:invoice", id)
.then(function(invoice) {
invoice.getRows().then(function(rows) {
defer.resolve(rows);
});
})
.fail(function(error) {
console.error(error);
defer.reject()
});
}
return defer.promise();
});
WMS.reqres.setHandler("get:supplier:invoice:drop", function(params) {
var defer = $.Deferred();
params = (params || {});
var path = null
, options = null;
if (params.noteRows) {
path = params.id ? params.id + "/crea_righe_da_bolla/" : "crea_fattura_da_righe_bolla/";
options = {
riga_bolla_fornitore: params.noteRows
};
}
if(params.orderRows) {
path = params.id ? params.id + "/crea_righe_da_ordine/" : "crea_fattura_da_righe_ordine/";
options = {
riga_ordine_fornitore: params.orderRows
};
}
if (!path) {
defer.reject();
} else {
$.post("/api/v1/fatturaFornitore/" + path, options)
.then(function(resp) {
var invoice = new Models.SupplierInvoice(Models.SupplierInvoice.prototype.parse(resp));
defer.resolve(invoice);
WMS.vent.trigger("supplier:invoice:updated", invoice);
})
.fail(function(error) {
defer.reject(error);
});
}
return defer.promise();
});
WMS.reqres.setHandler("get:supplier:invoice:print:url", function(id) {
return id === undefined ? "#" : "/anagrafiche/stampa/fatturaFornitore/" + id + "/";
});
Models.SupplierInvoiceCommission = Backbone.Model.extend({
defaults: {
supplierId : null
, commissionId : null
}
, validation: {
commissionId: { required: true }
}
, initialize: function() {
if (!this.get("supplierId")) {
throw new Error("SupplierId is required.");
}
}
, getSuppliers: function() {
return WMS.request("get:supplier:list");
}
, getCommissions: function() {
return WMS.request("get:commission:list");
}
});
WMS.commands.setHandler('unlink:invoice', function(invoice) {
if (!invoice) return;
if (!invoice._rows) return;
var noteRowIds = invoice._rows
.filter(function(row) { return !!row.get("noteCode"); })
.map(function(row) { return row.get("noteRowId"); });
if (noteRowIds.length === 0) return;
$.post("/api/v1/fatturaCliente/" + invoice.get("id") + "/dissocia_bolle/")
.then(function(resp) {
var attrs = Models.ClientInvoice.prototype.parse(resp);
var invoice = new Models.ClientInvoice(attrs);
var rows = (resp.righe || []).map(function(r) {
return Models.ClientInvoiceRow.prototype.parse(r);
});
invoice._rows = new Models.ClientInvoiceRows(rows);
WMS.vent.trigger("client:invoice:updated", invoice);
var notes = Models.getAllModels("clientNote")
.filter(function(note) {
if (!note._rows) return false;
var rows = note._rows.filter(function(row) {
return _.contains(noteRowIds, row.get("id"));
});
return rows.legth;
});
notes.forEach(function(note) {
note.fetch();
note._rows.fetch();
});
})
.fail(function(error) {
});
})
}); |
import Navbar from '@components/Navbar';
import { ILayout, ILayoutContent, ILayoutAside, ILayoutFooter, ILayoutHeader, IContainer, IRow, IColumn } from "@inkline/inkline/src/index";
export default {
name: 'Layout',
components: {
Navbar,
ILayout,
ILayoutContent,
ILayoutAside,
ILayoutFooter,
ILayoutHeader,
IContainer,
IRow,
IColumn
}
};
|
window.onload = function () {
document.querySelector("form").addEventListener("submit", function (event) {
event.preventDefault();
var errorMsg = "";
if (document.getElementById("lastname").value.length < 5) {
errorMsg ="Le nom doit contenir au moins 5 caractères <br/>";
}
if (document.getElementById("firstname").value.length < 5) {
errorMsg += "Le prénom doit contenir au moins 5 caractères <br/>";
}
if (document.getElementById("date").value.length < 8) {
errorMsg +="La date est obligatoire <br/>";
}
if (document.getElementById("adresse").value.length < 8) {
errorMsg +="L'adresse est obligatoire <br/>";
}
if (document.getElementById("email").value.length < 5) {
errorMsg +="L'email est obligatoire <br/>";
}
if(errorMsg != ""){
errorMessageShow(errorMsg);
}
else{
messageShow();
}
});
}
function errorMessageShow(_msg){
document.getElementById("errorMessage").innerHTML = _msg;;
document.getElementById("errorMessage").classList.remove("hidden");
}
function messageShow(){
document.getElementById("errorMessage").classList.add("hidden");
document.getElementById("message").innerHTML = "Bienvenue " + document.getElementById("lastname").value;
document.getElementById("message").classList.remove("hidden");
}; |
#!/usr/bin/nodejs
fs = require('fs');
file = fs.readFileSync(process.argv[2]);
console.log(JSON.stringify(JSON.parse(file)));
|
// Team: SkyBox Studios
// Team Members:
// Nathan Bailey
// Steven Bass
// Tyler Cochran
// Adil Delawalla
// Tyler Meehan
var speed = 90;
var leftJoint : Transform;
var rightJoint : Transform;
function ActivateWings(){
leftJoint.localEulerAngles = Vector3(0,0,0);
rightJoint.localEulerAngles = Vector3(0,0,0);
}
function DeactivateWings(){
leftJoint.localEulerAngles = Vector3(0,0,-90);
rightJoint.localEulerAngles = Vector3(0,0,90);
} |
alert ("Welcome To MyQuiz")
|
/* Run */
myApp.run([
'$rootScope',
'$window',
'$location',
'$timeout',
function ($rootScope, $window, $location, $timeout) {
$rootScope.isWorking = true;
$rootScope.refId = '';
var ngApp = document.getElementById('ng-app'),
header = document.getElementsByTagName('header')[0],
jsGo = false;
/*
ngApp.classList.add('slide-left');
$rootScope.$on('$locationChangeStart', function(e, next, previous) {
if( !jsGo ) {
if (next.length > previous.length) {
//forward
ngApp.classList.remove('slide-left', 'slide-right');
ngApp.classList.add('slide-left');
} else if (next.length < previous.length) {
//back
ngApp.classList.remove('slide-left', 'slide-right');
ngApp.classList.add('slide-right');
}
}
jsGo = false;
});
$rootScope.$on('$viewContentLoaded', function(){
header.classList.remove('up');
$timeout(function(){
var page = angular.element(document.getElementsByClassName('page')),
lastScroll = 0;
page.on('scroll', function() {
var scrollTop = page.scrollTop();
if (scrollTop >= lastScroll && scrollTop >= 60) {
header.classList.add('up');
} else if (scrollTop < (lastScroll - 10) || scrollTop < 60) {
header.classList.remove('up');
}
lastScroll = scrollTop;
});
},1000);
});
$rootScope.goTo = function(loc,dir) {
jsGo = true;
ngApp.classList.remove('slide-left', 'slide-right');
if (dir === "next") {
ngApp.classList.add('slide-left');
if (loc) {
$location.path(loc);
}
} else if (dir === "back") {
ngApp.classList.add('slide-right');
if (loc) {
$location.path(loc);
} else {
$window.history.back();
}
}
};
*/
}
]); |
const express = require('express');
const app = express();
const fs = require('fs');
const { generateControllers } = require('./src/dependency');
const serverless = require('serverless-http');
const c = generateControllers();
app.use(express.json());
console.log('here')
app.get('/', (req, res) => {
res.status(200).send('API is up');
});
app.post('/ImageFont', c.TextController.generateCustomFontImageText.bind(c.TextController));
if (process.env.isLocal) {
app.listen(8020, () => {
console.log('listening to port 8020');
});
}
module.exports.handler = serverless(app);
|
'use strict';
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
import React from 'react'
import { render } from 'react-dom'
import thunk from 'redux-thunk'
import { applyMiddleware, createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, IndexRoute, Link, hashHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'
import * as reducers from './reducers'
import App from './container/App'
import Home from './container/Home'
import Search from './container/Search'
import Article from './container/Article'
const reducer = combineReducers({
...reducers,
routing: routerReducer
})
const DevTools = createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q">
<LogMonitor theme="tomorrow" preserveScrollTop={false} />
</DockMonitor>
)
const store = createStore(
reducer,
applyMiddleware(thunk)
)
const history = syncHistoryWithStore(hashHistory, store)
render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="search/" component={Search}/>
<Route path="article/:id" component={Article}/>
</Route>
</Router>
</Provider>,
document.getElementById('root')
)
|
import React from 'react';
import firebase from 'firebase';
import { app, db } from '../config/firebase';
import { View, ScrollView, Text, TouchableOpacity } from 'react-native';
import styles from './styles';
import TagSelector from 'react-native-tag-selector';
class CustomSettings extends React.Component {
constructor() {
super();
this.state = {
email: '',
intolerances: [],
diet: [],
};
this.handleLogout = this.handleLogout.bind(this);
this.clickHandler = this.clickHandler.bind(this);
this.clickHandlerDiet = this.clickHandlerDiet.bind(this);
}
async componentDidMount() {
let user = firebase.auth().currentUser;
let userIntolerances = [];
let userDiet = [];
if (user) {
await db
.collection('users')
.doc(user.uid)
.get()
.then(function(doc) {
if (doc.exists) {
console.log('doc data obtained');
userIntolerances = doc.data().intolerances;
userDiet = doc.data().diet;
} else {
console.log('doc does not exist');
}
});
}
this.setState({
email: user.email,
intolerances: userIntolerances,
diet: userDiet,
}).catch(err => console.log('a firebase error has occurred', err));
}
clickHandler(selection) {
this.setState({
intolerances: selection,
});
}
clickHandlerDiet(selection) {
this.setState({
diet: selection,
});
}
async handleSubmit() {
let user = firebase.auth().currentUser;
if (user) {
await db
.collection('users')
.doc(user.uid)
.set(
{ intolerances: this.state.intolerances, diet: this.state.diet },
{ merge: true }
)
.catch(err => console.log('a firebase error has occurred', err));
}
}
async handleLogout() {
await firebase
.auth()
.signOut()
.then(() => console.log('signed out'))
.then(() => this.props.navigation.navigate('Main'))
.catch(error => {
console.log('an error has occurred logging out', error);
});
}
render() {
const intolerancesList = [
'dairy',
'gluten',
'peanut',
'shellfish',
'sesame',
'soy',
'tree nut',
'sulfite',
];
const dietList = ['vegetarian', 'vegan', 'pescetarian'];
const intolerancesObj = intolerancesList.map(intolerance => {
return { id: intolerance, name: intolerance };
});
const dietObj = dietList.map(diet => {
return { id: diet, name: diet };
});
return (
<View style={styles.container}>
<ScrollView>
<View style={styles.defaultContainer}>
<View style={styles.settingsContainer}>
<Text style={styles.settingsTitle}>Email: </Text>
<Text style={styles.settingsData}>{this.state.email}</Text>
<Text style={styles.settingsTitle}>Intolerances:</Text>
<TagSelector
tags={intolerancesObj}
customSelect={this.state.intolerances}
onChange={selected => this.clickHandler(selected)}
containerStyle={styles.settingsTagContainer}
tagStyle={styles.settingsTag}
selectedTagStyle={styles.settingsTagSelected}
/>
<Text style={styles.settingsTitle}>Diet:</Text>
<TagSelector
tags={dietObj}
customSelect={this.state.diet}
onChange={selected => this.clickHandlerDiet(selected)}
containerStyle={styles.settingsTagContainer}
tagStyle={styles.settingsTag}
selectedTagStyle={styles.settingsTagSelected}
/>
</View>
<TouchableOpacity
onPress={() => this.handleSubmit()}
type="outline"
style={styles.defaultBtn}
>
<Text style={styles.defaultBtnText}>Submit Changes</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.handleLogout()}
type="outline"
style={styles.logoutBtn}
>
<Text style={styles.logoutBtnText}>Logout</Text>
</TouchableOpacity>
</View>
</ScrollView>
</View>
);
}
}
CustomSettings.navigationOptions = {
title: 'My Settings',
headerStyle: {
backgroundColor: '#5bc0eb',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
fontFamily: 'Avenir',
},
};
export default CustomSettings;
|
$(document).ready(function(e){
$(".select_option").live("change",function(e){
var object = $(this);
var _option = $(this).val();
$.post("/reportes/valueoption/",{option:_option},function(info){
object.parent().after("<p>"+info.input +"</p>");
},"json");
});
$(".new_filter_report").click(function(e){
e.preventDefault();
var filters = $("#filter_1");
var object = $(this);
object.before("<p><select name='filters[]' class='select_option'>"+filters.html()+"</select></p>");
});
$("#campos_reporte").submit(function(e){
var status = $("#status_reporte").val();
var _confirm;
if(status == "new"){
response = confirm("¿Desea guardar esta configuración?");
if(response){
$("#popup").css("display","table");
$("#popup .content").css("width","400px");
$("#popup .content .html").html("");
$("#popup .content .html").html($("#save-box-reporte").html());
e.preventDefault();
}else{
$("#status_reporte").val("not_saved");
$("#generar_reporte").submit();
}
}
});
$(".form-reporte-guardar").live("submit",function(e){
e.preventDefault();
var action = $(this).attr("action");
var form = $("#campos_reporte").serialize() + "&descripcion="+$("#descripcion-reporte").val();
$("#submit-reporte").addClass("hidden");
$("#loader-reporte").addClass("loader2");
$.post(action,form,function(info){
if(info.result){
$("#loader-reporte").removeClass("loader2");
$("#loader-reporte").html("<p>Reporte Guardado Satisfactoriamente.</p>");
setTimeout(function(){
$("#status_reporte").val("saved");
$("#campos_reporte").submit();
},1500);
}else{
$("#submit-reporte").removeClass("hidden");
$("#loader-reporte").removeClass("loader2");
$("#loader-reporte").html("<p>El reporte no se Guardo correctamente intente otra vez</p>");
}
},"json");
});
$("#insert_data").change(function(e){
var value = $(this).val();
$.post("/reportes/htmloperaciones",{option:value},function(html){
$(".container .center").append(html);
$("#insert_data").val("");
});
});
});
|
const fs = require('fs');
const { assert } = require('chai');
const { Parser } = require('htmlparser2');
// use the JSON file because this file is less susceptible to merge conflicts
const { languages } = require('../components.json');
describe('Examples', function () {
const exampleFiles = new Set(fs.readdirSync(__dirname + '/../examples'));
const ignore = new Set([
// these are libraries and not languages
'markup-templating',
't4-templating',
// this does alter some languages but it's mainly a library
'javadoclike'
]);
const validFiles = new Set();
/** @type {string[]} */
const missing = [];
for (const lang in languages) {
if (lang === 'meta') {
continue;
}
const file = `prism-${lang}.html`;
if (!exampleFiles.has(file)) {
if (!ignore.has(lang)) {
missing.push(lang);
}
} else {
validFiles.add(file);
}
}
const superfluous = [...exampleFiles].filter(f => !validFiles.has(f));
it('- should be available for every language', function () {
assert.isEmpty(missing, 'Following languages do not have an example file in ./examples/\n'
+ missing.join('\n'));
});
it('- should only be available for registered languages', function () {
assert.isEmpty(superfluous, 'Following files are not associated with any language\n'
+ superfluous.map(f => `./examples/${f}`).join('\n'));
});
describe('Validate HTML templates', function () {
for (const file of validFiles) {
it('- ./examples/' + file, async function () {
const content = fs.readFileSync(__dirname + '/../examples/' + file, 'utf-8');
await validateHTML(content);
});
}
});
});
/**
* Validates the given HTML string of an example file.
*
* @param {string} html
*/
async function validateHTML(html) {
const root = await parseHTML(html);
/**
* @param {TagNode} node
*/
function checkCodeElements(node) {
if (node.tagName === 'code') {
assert.equal(node.children.length, 1,
'A <code> element is only allowed to contain text, no tags. '
+ 'Did you perhaps not escape all "<" characters?');
const child = node.children[0];
if (child.type !== 'text') {
// throw to help TypeScript's flow analysis
throw assert.equal(child.type, 'text', 'The child of a <code> element must be text only.');
}
const text = child.rawText;
assert.notMatch(text, /</, 'All "<" characters have to be escape with "<".');
assert.notMatch(text, /&(?!amp;|lt;|gt;)(?:[#\w]+);/, 'Only certain entities are allowed.');
} else {
node.children.forEach(n => {
if (n.type === 'tag') {
checkCodeElements(n);
}
});
}
}
for (const node of root.children) {
if (node.type === 'text') {
assert.isEmpty(node.rawText.trim(), 'All non-whitespace text has to be in <p> tags.');
} else {
// only known tags
assert.match(node.tagName, /^(?:h2|h3|ol|p|pre|ul)$/, 'Only some tags are allowed as top level tags.');
// <pre> elements must have only one child, a <code> element
if (node.tagName === 'pre') {
assert.equal(node.children.length, 1,
'<pre> element must have one and only one child node, a <code> element.'
+ ' This also means that spaces and line breaks around the <code> element are not allowed.');
const child = node.children[0];
if (child.type !== 'tag') {
// throw to help TypeScript's flow analysis
throw assert.equal(child.type, 'tag', 'The child of a <pre> element must be a <code> element.');
}
assert.equal(child.tagName, 'code', 'The child of a <pre> element must be a <code> element.');
}
checkCodeElements(node);
}
}
}
/**
* Parses the given HTML fragment and returns a simple tree of the fragment.
*
* @param {string} html
* @returns {Promise<TagNode>}
*
* @typedef TagNode
* @property {"tag"} type
* @property {string | null} tagName
* @property {Object<string, string>} attributes
* @property {(TagNode | TextNode)[]} children
*
* @typedef TextNode
* @property {"text"} type
* @property {string} rawText
*/
function parseHTML(html) {
return new Promise((resolve, reject) => {
/** @type {TagNode} */
const tree = {
type: 'tag',
tagName: null,
attributes: {},
children: []
};
/** @type {TagNode[]} */
let stack = [tree];
const p = new Parser({
onerror(err) {
reject(err);
},
onend() {
resolve(tree);
},
ontext(data) {
stack[stack.length - 1].children.push({
type: 'text',
rawText: data
});
},
onopentag(name, attrs) {
/** @type {TagNode} */
const newElement = {
type: 'tag',
tagName: name,
attributes: attrs,
children: []
};
stack[stack.length - 1].children.push(newElement);
stack.push(newElement);
},
onclosetag() {
stack.pop();
}
}, { lowerCaseTags: false });
p.end(html);
});
}
|
const express = require("express");
const graphqlHTTP = require("express-graphql");
const schema = require("./schema/schema");
const mongoose = require("mongoose");
const cors = require("cors");
const passport = require("passport");
const cookieSession = require("cookie-session");
require("./config/passport-setup");
const authRouter = require("./api/authRouter");
const checkLoginRouter = require("./api/checkLoginRouter");
const filesRouter = require("./api/filesRouter");
const keys = require("./config/keys");
const app = express();
app.use(cors());
// app.use("*/uploads", express.static("uploads"));
app.use(
"/uploads",
// passport.authenticate("jwt", { session: false }),
filesRouter
);
app.use(
cookieSession({
maxAge: 24 * 60 * 60 * 1000,
keys: [keys.session.cookieKey]
})
);
//initialize passport
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(keys.mongodb.dbURI, { useNewUrlParser: true });
mongoose.connection.once("open", () => {
console.log("Connected to database");
});
mongoose.set("useCreateIndex", true);
mongoose.set("useFindAndModify", false);
app.use(
"/graphql",
passport.authenticate("jwt", { session: false }),
graphqlHTTP({
schema,
graphiql: true
})
);
// app.use(
// "/graphql",
// graphqlHTTP(req => ({
// formatError: error => ({
// message: error.message,
// state: error.originalError && error.originalError.state,
// locations: error.locations,
// path: error.path
// })
// }))
// );
app.use("/auth", authRouter);
app.use(
"/checkLogin",
passport.authenticate("jwt", { session: false }),
checkLoginRouter
);
app.listen(4000, () => console.log("Now listening for requests on port 4000"));
|
// import React, {useState, useEffect} from 'react'
// import {View, Text, StatusBar, TouchableOpacity, Dimensions} from 'react-native'
// import Constants from 'expo-constants';
// import DateTimePicker from "react-native-modal-datetime-picker";
// import { FontAwesome } from '@expo/vector-icons';
// import { Scheduler } from '../../apis/firebase'
// import {db} from '../../configs/firebase'
// import ToggleSwitch from 'toggle-switch-react-native'
// const screenWidth = Math.round(Dimensions.get('window').width);
// export default (props) => {
// const [modal, setModal] = useState(false)
// const [time, setTime] = useState(null)
// const [schedules, setSchedules] = useState([])
// const addScheduler = (hour, minute) => {
// db.collection('schedulers').add({
// userId: '123',
// hour,
// minute,
// isAuto: false
// })
// .then(function(docRef) {
// console.log("Document written with ID: ", docRef.id);
// })
// .catch(function(error) {
// console.error("Error adding document: ", error);
// });
// }
// const changeIsAuto = (id, val ) => {
// db.collection('schedulers').doc(id).update({isAuto: val})
// .then(function() {
// console.log("Document successfully updated!");
// })
// .catch(function(error) {
// // The document probably doesn't exist.
// console.error("Error updating document: ", error);
// });
// }
// let unsubscribe = null
// const fetchScheduler = () => {
// unsubscribe = db.collection('schedulers').where("userId", "==", "123")
// .onSnapshot(function(querySnapshot) {
// const newScheduler = []
// querySnapshot.forEach(function(doc) {
// newScheduler.push({
// id: doc.id,
// ...doc.data()
// })
// })
// setSchedules(newScheduler)
// });
// }
// useEffect(() => {
// return () => {
// unsubscribe()
// };
// }, []);
// useEffect(() => {
// fetchScheduler()
// },[])
// return (
// <>
// <StatusBar barStyle={'dark-content'} />
// <DateTimePicker
// isVisible={modal}
// mode="time"
// locale={'id_ID'}
// onConfirm={data => {
// setTime(data)
// addScheduler(data.getHours(), data.getMinutes())
// setModal(false)
// }}
// onCancel={()=> setModal(false)}
// />
// <View style={{flex: 1, backgroundColor: '#f9f9f9'}}>
// <View style={{marginTop: Constants.statusBarHeight, flex: 1, alignItems: 'center', width: '100%'}}>
// {
// schedules.map(schedule => {
// let shadow = null
// let labelAuto = "Auto on"
// schedule.isAuto ? shadow = "#c18501" : shadow = '#000'
// console.log(schedule.hour, schedule.minute)
// return (
// <TouchableOpacity key={schedule.id}>
// <View style={[styles.menu, {shadowColor: shadow}]}>
// <Text style={styles.text}>{schedule.hour} : {schedule.minute}</Text>
// <ToggleSwitch
// label={labelAuto}
// isOn={schedule.isAuto}
// labelStyle={{color: 'silver'}}
// onColor="#e8d296"
// offColor="#dbdbdb"
// size="medium"
// onToggle={isOn => changeIsAuto(schedule.id, isOn)}
// />
// </View>
// </TouchableOpacity>
// )
// })
// }
// <View style={{padding: 30}}>
// <Text style={{color: 'silver', textAlign: 'center'}}>All the selected devices will be turned on automatically</Text>
// </View>
// <TouchableOpacity style={{
// position: "absolute",
// bottom: 20,
// right: 20,}}
// onPress={()=>setModal(true)}>
// <View style={{
// justifyContent: 'center',
// alignItems: 'center',
// width:60, height: 60,
// borderRadius: '100',
// backgroundColor: 'white',
// shadowColor: "#000",
// shadowOffset: {
// width: 0,
// height: 2,
// },
// shadowOpacity: 0.25,
// shadowRadius: 3.84,
// elevation: 5,}}>
// <FontAwesome name="plus" size={30} color="#383838" />
// </View>
// </TouchableOpacity>
// </View>
// </View>
// </>
// )
// }
// const styles = {
// menu: {
// width: screenWidth*0.9,
// height: 80,
// borderRadius: 15,
// backgroundColor: 'white',
// marginBottom: 20,
// justifyContent: 'center',
// flexDirection: 'row',
// alignItems: 'center',
// justifyContent: 'space-between',
// padding: 20,
// shadowOffset: {
// width: 0,
// height: 2,
// },
// shadowOpacity: 0.25,
// shadowRadius: 3.84,
// elevation: 5,
// },
// text: {
// fontSize: 22,
// fontWeight: '600',
// letterSpacing: 2,
// color: '#383838'
// }
// } |
angular.module("komGikkApp")
.factory("timeEventService", function (activityService) {
function setEventProperties(scopeData, timeEvent) {
if (timeEvent.activity.defaultType) {
switch (timeEvent.activity.defaultType) {
case 'START':
scopeData.events.isStarted = true;
break;
case 'END':
scopeData.events.isEnded = true;
break;
case 'START_EXTRA':
scopeData.events.isExtraOngoing = true;
scopeData.events.currentAction = null;
break;
case 'END_EXTRA':
scopeData.events.isExtraOngoing = false;
break;
default:
break;
}
} else {
scopeData.events.currentAction = timeEvent.activity;
}
scopeData.events.list.push(timeEvent);
}
return {
initTimeEvents: function(scopeData) {
scopeData.events = {};
scopeData.events.isStarted = false;
scopeData.events.isEnded = false;
scopeData.events.isExtraOngoing = false;
scopeData.events.list = [];
scopeData.events.currentAction = null;
},
addAllTimeEvents: function(scopeData, timeEvents) {
if (angular.isUndefined(timeEvents) || !angular.isArray(timeEvents)) {
console.log("timeEvent is undefined or not an array");
return;
}
//TODO: sort timeEvents på tid
//reset previous data
scopeData.events.isStarted = false;
scopeData.events.isEnded = false;
scopeData.events.isExtraOngoing = false;
scopeData.events.list = [];
for (var i = 0; i < timeEvents.length; ++i) {
setEventProperties(scopeData, timeEvents[i]);
}
},
addNewTimeEvent: function(scopeData, timeEvent) {
if (angular.isUndefined(scopeData.events.list)) {
scopeData.events.list = [];
}
setEventProperties(scopeData, timeEvent);
}
}
}); |
// pages/info/showInfo/showInfo.js
var app = getApp()
var common = require('../../../service/common.js')
import {
getHouseholdById
} from '../../../service/info.js'
Page({
data: {
household: {}
},
toUpdateInfo() {
const household = JSON.stringify(this.data.household)
wx.navigateTo({
url: '/pages/info/updateInfo/updateInfo?household=' + household,
})
},
onShow: function(options) {
const hh_id = app.globalData.hh_id
getHouseholdById(hh_id).then(res => {
const result = res.data
console.log(result)
if (result.status == 200) {
const household = result.data
household.arrivalDate = household.arrivalDate.split('T')[0]
this.setData({
household: household
})
} else {
common.errorStatus(result)
}
})
}
}) |
// global variables
var username = "";
var userID = "010";
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
displayUserProfile();
} else {
// The person is not logged into your app or we are unable to tell.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '1853245974998322',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use graph api version 2.8
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function displayUserProfile(){
FB.api('/me', function(response){
username = response.name;
userID = response.id;
$("#user").html("<div id='username'>" + response.name + "</div");
FB.api("/"+ response.id +"/picture", function (response) {
if (response && !response.error) {
$("#user").append("<img id='userpic' width = '25px' heigth = '25px' src = '" + response.data.url + "'/>");
console.log(response.data.url);
}
});
});
}
$(document).ready(function(){
$("#user").on("click", function(){
console.log("INHERE");
window.location = "profile.php/?id="+ userID;
});
});
|
// Written in 2014-2016 by Dmitry Chestnykh and Devi Mandiri.
// Public domain.
(function(root, f) {
'use strict';
if (typeof module !== 'undefined' && module.exports) module.exports = f();
else if (root.nacl) root.nacl.util = f();
else {
root.nacl = {};
root.nacl.util = f();
}
}(this, function() {
'use strict';
var util = {};
util.decodeUTF8 = function(s) {
if (typeof s !== 'string') throw new TypeError('expected string');
var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
return b;
};
util.encodeUTF8 = function(arr) {
var i, s = [];
for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i]));
return decodeURIComponent(escape(s.join('')));
};
util.encodeBase64 = function(arr) {
if (typeof btoa === 'undefined') {
return (new Buffer(arr)).toString('base64');
} else {
var i, s = [], len = arr.length;
for (i = 0; i < len; i++) s.push(String.fromCharCode(arr[i]));
return btoa(s.join(''));
}
};
util.decodeBase64 = function(s) {
if (typeof atob === 'undefined') {
return new Uint8Array(Array.prototype.slice.call(new Buffer(s, 'base64'), 0));
} else {
var i, d = atob(s), b = new Uint8Array(d.length);
for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
return b;
}
};
return util;
}));
|
var child_process = require ('child_process');
var fs = require ('fs');
var config = require ('../config.js');
var rule = require('./rule.model');
var async = require('async');
var getNowFormatDate = function () {
var day = new Date();
var Year = 0;
var Month = 0;
var Day = 0;
var CurrentDate = "";
Year = day.getFullYear();
Month = day.getMonth() + 1;
Day = day.getDate();
CurrentDate += Year;
if (Month >= 10 ) {
CurrentDate += Month;
} else {
CurrentDate += "0" + Month;
}
if (Day >= 10 ) {
CurrentDate += Day;
} else {
CurrentDate += "0" + Day ;
}
return CurrentDate;
};
var getNowFormatTime = function () {
var day = new Date();
var Hour = 0;
var Minute = 0;
var Second = 0;
var Millisecond = 0;
var CurrentTime = "";
Hour = day.getHours();
Minute = day.getMinutes();
Second= day.getSeconds();
Millisecond= day.getMilliseconds();
if (Hour >= 10 ) {
CurrentTime += Hour;
} else {
CurrentTime += "0" + Hour;
}
if (Minute >= 10 ) {
CurrentTime += Minute;
} else {
CurrentTime += "0" + Minute;
}
if (Second >= 10 ) {
CurrentTime += Second;
} else {
CurrentTime += "0" + Second;
}
if (Millisecond >= 100 ) {
CurrentTime += Millisecond;
} else if (Millisecond >= 10 ) {
CurrentTime += "00" + Millisecond;
} else if (Millisecond >= 0 ) {
CurrentTime += "000" + Millisecond;
}
return CurrentTime;
};
var readCSV = function (path, name){
fs.readFile(path + name, function (error, data){
var csvdata = new Array();
var csvrow = data.toString().split('\n');
var i;
for(i = 0; i < csvrow.length - 1; i += 1) {
var csvspan = csvrow[i].split(',');
csvspan.length = csvspan.length - 1;
if(csvspan.length > 1)csvdata.push(csvspan);
}
processData(csvdata);
})
};
var numToPer = function (numerator, denominator) {
if(denominator == 0) {
return 'Nerr';
} else {
var step1 = numerator * 100 / denominator;
var step2 = step1.toFixed(2);
var per = String(step2) + "%";
return per;
}
};
var processData = function (csvdata) {
var i;
var firstDate,secondDate;
var tabledata = new Array();
if (csvdata[0][0] == 'Report') {
var temp;
temp = csvdata[0][1].split(' ');
firstDate = temp[6] + ' ' + temp[7];
secondDate = temp[9] + ' ' + temp[10];
tabledata.push([firstDate,secondDate]);
}
for(i = 1; i <= csvdata.length - 1; i += 1) {
if (csvdata[i][0] == 'VIEW' || csvdata[i][1] == firstDate) {
continue;
}else if (csvdata[i][0].indexOf('(%)') !== -1) {
var na = false,j,percentResult,numerator = 0,denominator = 0;
for(j = 1; j <= csvdata[i].length - 1; j += 1) {
if((csvdata[i+1][j] == 'N/A') || (csvdata[i+2][j] == 'N/A')){
na = true;
break;
} else {
numerator += parseInt(csvdata[i+1][j]);
denominator += parseInt(csvdata[i+2][j]);
}
}
if (na){
tabledata.push([csvdata[i][0],'N/A']);
continue;
} else if ((numerator == 0) || (denominator == 0)) {
percentResult = "0%";
tabledata.push([csvdata[i][0],percentResult]);
i += 2;
continue;
};
percentResult = numToPer (numerator, denominator);
tabledata.push([csvdata[i][0],percentResult]);
i += 2;
} else if (csvdata[i][0].indexOf('_avg)') !== -1) {
var na = false,j,tofix = 0, averageResult = 0;
for(j = 1; j <= csvdata[i].length - 1; j += 1) {
if(csvdata[i][j] == 'N/A') {
na = true;
break;
} else if (csvdata[i][j].indexOf('.') !== -1){
if(tofix < csvdata[i][j].split('.')[1].length){
tofix = csvdata[i][j].split('.')[1].length;
}
}
averageResult += parseFloat(csvdata[i][j]);
}
if (na){
tabledata.push([csvdata[i][0],'N/A']);
continue;
} else {
averageResult = averageResult / (csvdata[i].length - 1);
averageResult = averageResult.toFixed(tofix);
tabledata.push([csvdata[i][0],averageResult]);
}
} else {
var na = false,j,result = 0;
for(j = 1; j <= csvdata[i].length - 1; j += 1) {
if(csvdata[i][j] == 'N/A') {
na = true;
break;
} else {
result += parseFloat(csvdata[i][j]);
}
}
if (na){
tabledata.push([csvdata[i][0],'N/A']);
continue;
} else {
tabledata.push([csvdata[i][0],result]);
}
}
}
/* console.log("tabledata:");
console.log(tabledata);*/
return tabledata;
};
exports.import_rule = function (data) {
/* console.log(data);*/
async.waterfall([
function (callback){
var i;
var rules = new Array();
for (i = 1; i <= data.length -1; i += 1){
var tmp = data[i].split(',');
rules.push(data[i].split(','));
};
rule.importRules(rules, function (from){callback(null, from);});
},
function (rules,callback){
console.log(rules);
rule.importTemplate(data[0], rules, function (from){
console.log("from");
console.log(from);
callback(null, from);
});
}
],function (err,result){
console.log('import result:');
console.log(result);
/*next(result);*/
});
};
exports.run_cmd = function (reporttemplate, type, eid, firstdate, seconddate, ruletemplate, next){
var timestamp = getNowFormatDate() + getNowFormatTime();
var cmd = "sh " + config.cmd.scriptFile + " " + config.cmd.serverIP +" report -u '" + config.cmd.username + ":" + config.cmd.password + "' -o " + config.csvFile.path + timestamp + ".csv reporttemplatename=" + reporttemplate + " otype=" + type + " eids=" + eid + " periodicity=h firstdate=" + firstdate + " seconddate=" + seconddate + " tz=" + config.cmd.timeZone + " format=csv";
async.waterfall([
function(callback){
child_process.exec(cmd, function (error, stderr, stdout) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
next(null);
}
callback(null);
})
},
function(callback){
fs.readFile(config.csvFile.path + timestamp + ".csv ", function (error, data){
if(error){
console.log('read file error!');
next(null);
} else {
var csvdata = new Array();
var csvrow = data.toString().split('\n');
var i;
for(i = 0; i < csvrow.length - 1; i += 1) {
var csvspan = csvrow[i].split(',');
csvspan.length = csvspan.length - 1;
if(csvspan.length > 1)csvdata.push(csvspan);
};
/*console.log(csvdata);*/
callback(null,csvdata);
}
})
},
function(csvdata,callback){
var tabledata = new Array();
tabledata = processData(csvdata);
callback(null,tabledata);
},
function(tabledata, callback){
rule.queryTemplateByName(ruletemplate, tabledata, function (from) {callback(null, from);});
}
], function (err, result) {
next(result);
});
};
exports.createOutFile = function (outdata, next) {
var timestamp = getNowFormatDate() + getNowFormatTime();
var i;
for (i = 1; i< outdata.length ; i+=1){
outdata[i][0] = '\n'+ outdata[i][0];
}
fs.writeFile(config.outDataFile.path + timestamp+'.csv', outdata, function (err) {
if (err) {
console.log(err);
} else {
console.log('file saved!');
next(config.outDataFile.path + timestamp+'.csv');
}
});
} |
import Taro, { Component } from '@tarojs/taro'
import { View, Button, Image } from '@tarojs/components'
import './index.less'
import logo from '../../assets/images/logo.jpg'
export default class Authorization extends Component {
config = {
navigationBarTitleText: '授权'
}
constructor() {
super(...arguments)
this.state = {
text: "获取微信授权登录"
}
}
confirmModal(e) {
if (e.detail.userInfo) {
if (Taro.getStorageSync('userInfo') && JSON.parse(Taro.getStorageSync('userInfo')).name) {
Taro.switchTab({
url: `/pages/index/index`
})
} else {
Taro.redirectTo({
url: `/pages/login/index`
})
}
}
}
render() {
return (
<View className='page'>
<Image src={logo} />
<Button
className='page-button'
open-type='getUserInfo'
onGetUserInfo={this.confirmModal.bind(this)}
>{this.state.text}
</Button>
</View>
)
}
} |
function functionWithException() {
try {
throw new Error("test exception");
}
catch (e) {
//implementation of any partial processing
//and send error to the calling code
throw e;
}
}
try {
functionWithException();
}
catch (e) {
console.log(e);
}
|
import React, { useState, useEffect } from 'react'
const CalcHooks = () => {
const [number, setNumber] = useState(0)
const [showNumber, setShowNumber] = useState(false)
return (
<>
<button onClick={() => setNumber(number + 1)}>
Click to increment by 1
</button>
<button onClick={() => setNumber(number - 1)}>
Click to decrease by 1
</button>
<button onClick={() => setShowNumber(!showNumber)}>
{ showNumber ? 'Hide number' : 'Show number' }
</button>
{ showNumber ? <h2>{ number }</h2> : '' }
</>
)
}
export default CalcHooks |
export const gridOptions = {
columnDefs: [
{
headerName: "Athlete",
field: "athlete",
width: 150
},
{
headerName: "Age",
field: "age",
sortingOrder: ["asc", "desc"]
},
{
headerName: "Country",
field: "country",
width: 150
},
{
headerName: "Year",
field: "year",
sortingOrder: ["asc", "desc"]
},
{
headerName: "Date",
field: "date",
width: 100,
unSortIcon: true,
sortingOrder: ["asc", "desc"]
},
{
headerName: "Sport",
field: "sport",
width: 150
}
],
defaultColDef: {
width: 90,
sortable: true // global sort enable
},
sortingOrder: ["asc", "desc", null], // global default method sorting
multiSortKey: "ctrl"
};
export const defaultSortModel = [
{
colId: "athlete",
sort: "desc"
},
{
colId: "age",
sort: "asc"
},
{
colId: "country",
sort: "asc"
}
];
export const SortOptionsGridOptions = props => {
const columnDefs = [];
const rowData = [];
const obj = {};
props.forEach(item => {
columnDefs.push({ headerName: item.colId, field: item.colId, width: 230 });
obj[`${item.colId}`] = item.sort;
});
rowData.push(obj);
return { columnDefs, rowData };
};
|
// JavaScript - Node v8.1.3
typeOfSum = (a, b) => typeof(a + b);
|
import React from 'react';
import fire from '../Config/fire'
import { connect } from 'react-redux';
import '../CSS/Work.css';
class AdminHome extends React.Component {
constructor() {
super();
this.state = {
COUNTER: 0,
COMPANY_BLOCK_USER: [],
COMPANY_ACTIVE_USER: [],
STUDENT_BLOCK_USER: [],
STUDENT_ACTIVE_USER: [],
// ALL_STUDENT:[],
}
this.ChangeData = this.ChangeData.bind(this);
this.LogOutMe = this.LogOutMe.bind(this);
}
componentWillMount() {
for (var x in this.props.ALL_COMPANY) {
if (this.props.ALL_COMPANY[x].Status === "ACTIVE") {
this.state.COMPANY_ACTIVE_USER.push({ Data: this.props.ALL_COMPANY[x], ID: x })
}
else if (this.props.ALL_COMPANY[x].Status === "BLOCKED") {
this.state.COMPANY_BLOCK_USER.push({ Data: this.props.ALL_COMPANY[x], ID: x })
}
}
for (var x in this.props.ALL_STUDENT) {
if (this.props.ALL_STUDENT[x].Status === "ACTIVE") {
this.state.STUDENT_ACTIVE_USER.push({ Data: this.props.ALL_STUDENT[x], ID: x })
}
else if (this.props.ALL_STUDENT[x].Status === "BLOCKED") {
this.state.STUDENT_BLOCK_USER.push({ Data: this.props.ALL_STUDENT[x], ID: x })
}
}
}
ChangeData() {
fire.database().ref('Detail' + "/" + "-M-C2hDo5ed35FBl2slj" + "/" + "Status").set(
"BLOCKED"
)
}
COMPANY_BLOCK_ACTIVE(Myid, Type, index) {
if (Type === "BLOCK") {
fire.database().ref('ALL_COMPANY/' + Myid + '/Status').set(
"BLOCKED");
var DeleteData = this.state.COMPANY_ACTIVE_USER.splice(index, 1)
console.log(DeleteData)
this.state.COMPANY_BLOCK_USER.push(DeleteData[0])
this.setState({ COUNTER: this.state.COUNTER })
}
else if (Type === "UNBLOCK") {
fire.database().ref('ALL_COMPANY/' + Myid + '/Status').set(
"ACTIVE")
var DeleteData = this.state.COMPANY_BLOCK_USER.splice(index, 1)
this.state.COMPANY_ACTIVE_USER.push(DeleteData[0])
this.setState({ COUNTER: this.state.COUNTER })
}
}
STUDENT_BLOCK_ACTIVE(Myid, Type, index) {
if (Type === "BLOCK") {
fire.database().ref('ALL_STUDENTS/' + Myid + '/Status').set(
"BLOCKED");
var DeleteData = this.state.STUDENT_ACTIVE_USER.splice(index, 1)
// console.log(DeleteData)
this.state.STUDENT_BLOCK_USER.push(DeleteData[0])
this.setState({ COUNTER: this.state.COUNTER })
}
else if (Type === "UNBLOCK") {
fire.database().ref('ALL_STUDENTS/' + Myid + '/Status').set(
"ACTIVE")
var DeleteData = this.state.STUDENT_BLOCK_USER.splice(index, 1)
this.state.STUDENT_ACTIVE_USER.push(DeleteData[0])
this.setState({ COUNTER: this.state.COUNTER })
}
}
LogOutMe() {
fire.auth().signOut().then(() => {
this.props.history.push('/Login')
// alert("LogOut SuccessFull")
}).catch(function (error) {
console.log(error)
// alert("Many Error in LogOut")
});
}
render() {
this.state.COUNTER = 0;
return (
<div>
<div class="topnav">
<a class="active">Home</a>
<a onClick={() => this.LogOutMe()} >LogOut</a>
<span>ADMIN ACCOUNT</span>
</div>
<div>
{/* COMPANY ACTIVE ACCOUNTS */}
<h6 className="listhead" >COMPANY ACTIVE ACCOUNTS</h6>
<div className="listsize" >
<table className="customers" >
<tr>
<th>Serial Number</th>
<th>Email</th>
<th>Block</th>
</tr>
{this.state.COMPANY_ACTIVE_USER.map((val, index) => {
console.log(val)
this.state.COUNTER++
return (
<tr>
<td>
{this.state.COUNTER}
</td>
<td>
{val.Data.Email}
</td>
<td>
<button onClick={() => this.COMPANY_BLOCK_ACTIVE(val.ID, "BLOCK", index)}>
BLOCK
</button>
</td>
</tr>
)
})}
{this.state.COUNTER = 0,
this.state.COMPANY_BLOCK_USER.map((val, index) => {
this.state.COUNTER++
return (
<tr>
<td>
{this.state.COUNTER}
</td>
<td>
{val.Data.Email}
</td>
<td>
<button onClick={() => this.COMPANY_BLOCK_ACTIVE(val.ID, "UNBLOCK", index)}>
UN BLOCK
</button>
</td>
</tr>
)
})}
</table>
</div>
<hr />
{/* COMPANY BLOCK ACCOUNTS */}
{/* <h6 className="listhead">COMPANY BLOCK ACCOUNTS</h6>
<div className="listsize" >
<table className="customers" >
<tr>
<th>Serial Number</th>
<th>Email</th>
<th>UnBlock</th>
</tr>
{this.state.COUNTER = 0,
this.state.COMPANY_BLOCK_USER.map((val, index) => {
this.state.COUNTER++
return (
<tr>
<td>
{this.state.COUNTER}
</td>
<td>
{val.Data.Email}
</td>
<td>
<button onClick={() => this.COMPANY_BLOCK_ACTIVE(val.ID, "UNBLOCK", index)}>
UN BLOCK
</button>
</td>
</tr>
)
})}
</table>
</div> */}
{/* STUDENT ACTIVE ACCOUNTS */}
<h6 className="listhead" >STUDENT ACTIVE ACCOUNTS</h6>
<div className="listsize" >
<table className="customers" >
<tr>
<th>Serial Number</th>
<th>Email</th>
<th>Block</th>
</tr>
{this.state.STUDENT_ACTIVE_USER.map((val, index) => {
console.log(val)
this.state.COUNTER++
return (
<tr>
<td>
{this.state.COUNTER}
</td>
<td>
{val.Data.Email}
</td>
<td>
<button onClick={() => this.STUDENT_BLOCK_ACTIVE(val.ID, "BLOCK", index)}>
BLOCK
</button>
</td>
</tr>
)
})}
{this.state.COUNTER = 0,
this.state.STUDENT_BLOCK_USER.map((val, index) => {
this.state.COUNTER++
return (
<tr>
<td>
{this.state.COUNTER}
</td>
<td>
{val.Data.Email}
</td>
<td>
<button onClick={() => this.STUDENT_BLOCK_ACTIVE(val.ID, "UNBLOCK", index)}>
UN BLOCK
</button>
</td>
</tr>
)
})}
</table>
</div>
<hr />
{/* STUDENT BLOCK ACCOUNTS */}
{/* <h6 className="listhead">STUDENT BLOCK ACCOUNTS</h6>
<div className="listsize" >
<table className="customers" >
<tr>
<th>Serial Number</th>
<th>Email</th>
<th>UnBlock</th>
</tr>
{this.state.COUNTER = 0,
this.state.STUDENT_BLOCK_USER.map((val, index) => {
this.state.COUNTER++
return (
<tr>
<td>
{this.state.COUNTER}
</td>
<td>
{val.Data.Email}
</td>
<td>
<button onClick={() => this.STUDENT_BLOCK_ACTIVE(val.ID, "UNBLOCK", index)}>
UN BLOCK
</button>
</td>
</tr>
)
})}
</table>
</div> */}
</div>
</div>
)
}
}
function mapStateToProps(state) {
return ({
MY_USER: state.MyReducer.MYUSER,
ALL_COMPANY: state.MyReducer.COMPANYDATA,
ALL_STUDENT: state.MyReducer.STUDENTDATA,
COMPANYPOST: state.MyReducer.COMPANYPOST,
STUDENTPOST: state.MyReducer.STUDENTPOST
})
}
function mapDispatchToProps(dispatch) {
// return({
// ChangeStateToReducer:(PickUserName)=>{
// dispatch(ChangeState(PickUserName))
// }
// })
}
export default connect(mapStateToProps, mapDispatchToProps)(AdminHome);
|
import React, {Component} from 'react';
import XLSX from "xlsx";
class UploadFiles extends Component{
constructor(props){
super(props)
this.state = {
data : ''
}
}
onChange = (f) => {
// debugger
// let files = event.target.files;
var name = f.name;
console.log(name);
let reader = new FileReader();
// reader.readAsDataURL(files[0]);
// reader.onload = (event) => {
// console.log(event.target.result)
reader.onload = (event) => {
console.log(event.target.result)
var data = new Uint8Array(event.target.result);
var webFile = XLSX.read(data,{type:'binary'});
/* Get first worksheet */
const wsname = webFile.SheetNames[0];
const ws = webFile.Sheets[wsname];
/* Convert array of arrays */
const data1 = XLSX.utils.sheet_to_csv(ws, {header:1});
/* Update state */
console.log("Data>>>"+data1);
};
reader.readAsBinaryString(f);
// console.log("data",data)
// console.log("webFile",webFile)
// var htmlStr = XLSX.write(webFile, {
// Sheets: "Sheet1",
// type: "binary",
// bookType: "html"
// });
// console.log(htmlStr)
}
render(){
return(
<div onSubmit={this.onFormSubmit}>
<input type='file' name='file' onChange={this.onChange}/>
</div>
);
}
}
export default UploadFiles; |
const person = {
age: 28
}
person.age = 29;
console.log( person ); |
//Object property shorthand
const name = 'Arush';
const userAge = 26;
const user = {
name: name,
age: userAge,
location: 'Austin'
};
/**
* Same as code below
*/
const es6User = {
name,
age: userAge,
location: 'Austin'
};
console.log(user);
console.log(es6User);
// Object Destructuring
const product = {
label: 'Red Dead Redemption',
price: 60,
stock: 100,
salePrice: undefined
};
// console.log(product.label);
const { label: productLabel, stock, rating = 4 } = product;
console.log(productLabel);
console.log(stock);
console.log(rating);
const transaction = (type, { label, stock }) => {
console.log(type, label, stock);
};
transaction('order', product);
|
const fs = require('fs');
const argv = process.argv; // shows array of each command line argument/keyword
function cat(path) {
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
console.log(`Error reading ${path}: `);
console.log(` ${err}`);
process.exit(1);
}
console.log(data);
})
}
cat(argv[2]);
|
const path = require('path');
const glob = require('glob');
const fs = require('fs');
const webpack = require('webpack');
const C = require("./workspace.config.js");
let conf = {
mode: 'development',
devtool: 'source-map',
entry: (() => {
let entries = {};
let pts = glob.sync("./" + C.ENTRY + "/*.{js,ts}");
for(let p of pts){
let pinf = path.parse(p);
entries[pinf.name] = p;
}
return entries;
})(),
output: {
globalObject: "this",
path: path.resolve(__dirname, C.DEST),
filename: "[name].js",
publicPath: "."
},
optimization: {
splitChunks: {
chunks: 'async',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
},
},
resolve: {
modules: [path.join(__dirname, C.ENTRY), "node_modules"],
extensions: [
'.ts', '.tsx', '.js', '.vue'
],
alias: {
// vue-template-compiler
vue$: 'vue/dist/vue.esm.js',
//asset: path.resolve(__dirname + "/" + C.ENTRY + "/asset")
},
},
devServer: {
contentBase: path.join(__dirname, C.ENTRY),
compress: true,
inline: true,
hot: false,
https: false,
host: "localhost",
port: 3030
},
watchOptions: {
// Example watchOptions
aggregateTimeout: 300,
poll: 1000
}
};
conf = Object.assign(conf, require('./webpack.config.module.js')(webpack, conf), require('./webpack.config.local.js')(webpack, conf))
// Asset List
let srcm = new RegExp("^" + C.ENTRY.replace(/(^\/|\/$)/, "") + "/");
let srcs = glob.sync(C.ENTRY + "/**/*.{html,htm,xml,yml,jpg,jpeg,png,gif,tiff,svg,woff,woff2,ttf,eot,mp3,mp4,m4a,wav,zip}")
.map((r) => { return r.replace(srcm, ""); });
fs.writeFileSync(C.ENTRY + "/.asset.list.js", "// generated in webpack.config\nexport default " + JSON.stringify(srcs));
console.log("[WORKSPACE]", "Listing up assets... ", srcs);
module.exports = conf; |
import React from 'react';
import Grid from '@material-ui/core/Grid';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
respContainer: {
position: 'relative',
overflow: 'hidden',
paddingTop: '56.25%',
height: '100%'
},
respIframe: {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
border: 0
}
}));
const BudgetTracker = () => {
const classes = useStyles();
return (
<>
<Grid
container
direction="column"
spacing={4}
justify="center"
>
<Grid item style={{
height: '90vh',
backgroundPosition: 'center bottom',
backgroundSize: 'cover',
backgroundImage: 'url(https://samahan.stdcdn.com/21-22/landing.png), linear-gradient(to right, #1637BC, #2D8AEA)',
paddingLeft: 'clamp(50px, 10vw, 100px)',
paddingRight: 'clamp(50px, 10vw, 100px)'
}}>
<Card style={{ height: '100%', borderRadius: 20 }}>
<CardContent className={classes.respContainer}>
<iframe className={classes.respIframe} src="https://docs.google.com/spreadsheets/d/e/2PACX-1vSkswDONSXkYpZSeLdFdjz39soMvtmLWBaeXVkXuQaA9LpVFeK2Z2FEXUgZ4J3XRPxVw-0FTBYjQT1Y/pubhtml?widget=true&headers=false" />
</CardContent>
</Card>
</Grid>
<Grid item style={{
backgroundPosition: 'center bottom',
backgroundSize: 'cover',
backgroundImage: 'linear-gradient(to right, #1637BC, #2D8AEA)',
paddingTop: '10rem',
paddingBottom: '10rem',
paddingLeft: 'clamp(50px, 10vw, 100px)',
paddingRight: 'clamp(50px, 10vw, 100px)'
}}>
<Grid container direction="column" justify="center" alignItems="center" spacing={4}>
<Grid item>
<Typography variant="h3" color="secondary">SAMAHAN Live Budget Tracker</Typography>
</Grid>
<Grid item>
<Typography color="secondary">For many years, it has always been a challenge to keep the students up to date about their money banked in SAMAHAN. The SAMAHAN Live Budget Tracker is a real time budget update, displayed live on the SAMAHAN website. It will project expenses and current standing of the budget. Along with all the events, this tracker competently used to work more effectively and promote transparency for the Ateneans. </Typography>
</Grid>
</Grid>
</Grid>
</Grid>
</>
)
}
export default BudgetTracker; |
console.log('周珣睡着了'); |
'use strict'
//ZADATAK 1
function numReverse(num) {
var reverseNum = parseInt(num.toString().split('').reverse().join(''));
return reverseNum;
}
function fact(x) {
if (x < 0) {
return NaN;
}
if (x == 0 || x == 1) {
return 1;
}
return fact(x - 1) * x;
}
// ZADATAK 2
function cloneArray(array) {
if (!(array instanceof Array)) {
throw "Not array";
}
var newArray = [];
for (var index in array) {
newArray.push(array[index]);
}
return newArray;
}
function sortArray(x, y) {
var newArray = cloneArray(x)
var swapped;
do {
swapped = false;
for (var i = 0; i < newArray.length - 1; i++) {
if (y(newArray[i], newArray[i + 1]) > 0) {
var temp = newArray[i];
newArray[i] = newArray[i + 1];
newArray[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return newArray;
}
function removeSmallest(array) {
var newArray = cloneArray(array);
var index = 0;
var value = array[0];
for (var i = 1; i < newArray.length; i++) {
if (newArray[i] < value) {
value = newArray[i];
index = i;
}
}
newArray.splice(index, 1);
return newArray;
}
// ZADATAK 3
function printObject(obj) {
for (var index in obj) {
console.log(obj[index]);
}
}
var Person = function(ime, prezime, datum) {
this.ime = ime;
this.prezime = prezime;
this.datum = datum;
}
Person.prototype.getName = function() {
return this.ime;
}
Person.prototype.getAge = function() {
var d = new Date;
return Math.floor((d - this.datum) / (365 * 24 * 3600 * 1000));
}
var ivan = new Person("Ivan", "Horvat", new Date(91, 9, 15));
// ZADATAK 4
var addBtn = document.getElementById("addButton");
addBtn.addEventListener("click", function() {
var numbers = getValues();
var flag = checkValues(numbers);
if(flag == true && isNumber(numbers)){
numbers = toNumber(numbers);
}
printResult(numbers[0]+numbers[1]);
});
var subBtn = document.getElementById("subtractButton");
subBtn.addEventListener("click", function() {
var numbers = getValues();
var flag = checkValues(numbers);
if(flag == true && isNumber(numbers)){
numbers = toNumber(numbers);
printResult(numbers[0]-numbers[1]);
}
else {
printResult("");
alert("Only numbers can be substracted");
}
});
function getValues() {
return [document.getElementById("first").value, document.getElementById("second").value];
}
function checkValues(x) {
if (x[0].length == 0 || x[1].length == 0) {
alert("Fill both inputs");
}
else {
return true;
}
}
function printResult(x) {
if (!(x === undefined)) {
document.getElementById("result").innerHTML = x;
}
}
function isNumber(x) {
if (!isNaN(x[0]) && !isNaN(x[1])) {
return true;
} else {
return false;
}
}
function toNumber(x) {
var num1 = parseInt(x[0]);
var num2 = parseInt(x[1]);
return [num1, num2];
}
|
const jwt = require('jsonwebtoken');
const { resolveContent } = require('nodemailer/lib/shared');
function confirm_signup (data, cb) {
const token_confirm_signup = jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60*30),
data: data
}, process.env.SECRET);
cb(token_confirm_signup);
}
function verify_signup(token) {
return new Promise((resolve, reject)=>{
try {
jwt.verify(token, process.env.SECRET);
resolve(jwt.verify(token, process.env.SECRET).data);
} catch (error) {
reject(error);
}
});
}
module.exports = {
confirm_signup: confirm_signup,
verify_signup: verify_signup
}; |
// JavaScript Document
function convert()
{
var oprt = document.getElementById("operators").value;
var slct = document.getElementById("selectors").value;
if(slct==="b")
{ var b= parseFloat(document.getElementById("inpt").value);
if(oprt === "b")
{
document.getElementById("result").value = b;
}
else if(oprt === "k")
{
document.getElementById("result").value = b/1000;
}
else if(oprt === "m")
{
document.getElementById("result").value = b/1000000;
}
else if(oprt === "c")
{
document.getElementById("result").value = b/37000000000;
}
else if(oprt === "ml")
{
document.getElementById("result").value = b/37000000;
}
else if(oprt === "mi")
{
document.getElementById("result").value = b/37000;
}
else if(oprt === "r")
{
document.getElementById("result").value = b/1000000;
}
}
if(slct==="k")
{ var k= parseFloat(document.getElementById("inpt").value);
if(oprt === "b")
{
document.getElementById("result").value = k*1000;
}
else if(oprt === "k")
{
document.getElementById("result").value = (k*1000)/1000;
}
else if(oprt === "m")
{
document.getElementById("result").value = (k*1000)/1000000;
}
else if(oprt === "c")
{
document.getElementById("result").value = (k*1000)/37000000000;
}
else if(oprt === "ml")
{
document.getElementById("result").value = (k*1000)/37000000;
}
else if(oprt === "mi")
{
document.getElementById("result").value = (k*1000)/37000;
}
else if(oprt === "r")
{
document.getElementById("result").value = (k*1000)/1000000;
}
}
if(slct==="m")
{ var m= parseFloat(document.getElementById("inpt").value);
if(oprt === "b")
{
document.getElementById("result").value = m*1000000;
}
else if(oprt === "k")
{
document.getElementById("result").value = (m*1000000)/1000;
}
else if(oprt === "m")
{
document.getElementById("result").value = (m*1000000)/1000000;
}
else if(oprt === "c")
{
document.getElementById("result").value = (m*1000000)/37000000000;
}
else if(oprt === "ml")
{
document.getElementById("result").value = (m*1000000)/37000000;
}
else if(oprt === "mi")
{
document.getElementById("result").value = (m*1000000)/37000;
}
else if(oprt === "r")
{
document.getElementById("result").value = (m*1000000)/1000000;
}
}
if(slct==="c")
{ var c= parseFloat(document.getElementById("inpt").value);
if(oprt === "b")
{
document.getElementById("result").value = c*37000000000;
}
else if(oprt === "k")
{
document.getElementById("result").value = (c*37000000000)/1000;
}
else if(oprt === "m")
{
document.getElementById("result").value = (c*37000000000)/1000000;
}
else if(oprt === "c")
{
document.getElementById("result").value = (c*37000000000)/37000000000;
}
else if(oprt === "ml")
{
document.getElementById("result").value = (c*37000000000)/37000000;
}
else if(oprt === "mi")
{
document.getElementById("result").value = (c*37000000000)/37000;
}
else if(oprt === "r")
{
document.getElementById("result").value = (c*37000000000)/1000000;
}
}
if(slct==="ml")
{ var ml= parseFloat(document.getElementById("inpt").value);
if(oprt === "b")
{
document.getElementById("result").value = ml*37000000;
}
else if(oprt === "k")
{
document.getElementById("result").value = (ml*37000000)/1000;
}
else if(oprt === "m")
{
document.getElementById("result").value = (ml*37000000)/1000000;
}
else if(oprt === "c")
{
document.getElementById("result").value = (ml*37000000)/37000000000;
}
else if(oprt === "ml")
{
document.getElementById("result").value = (ml*37000000)/37000000;
}
else if(oprt === "mi")
{
document.getElementById("result").value = (ml*37000000)/37000;
}
else if(oprt === "r")
{
document.getElementById("result").value = (ml*37000000)/1000000;
}
}
if(slct==="mi")
{ var mi= parseFloat(document.getElementById("inpt").value);
if(oprt === "b")
{
document.getElementById("result").value = mi*37000;
}
else if(oprt === "k")
{
document.getElementById("result").value = (mi*37000)/1000;
}
else if(oprt === "m")
{
document.getElementById("result").value = (mi*37000)/1000000;
}
else if(oprt === "c")
{
document.getElementById("result").value = (mi*37000)/37000000000;
}
else if(oprt === "ml")
{
document.getElementById("result").value = (mi*37000)/37000000;
}
else if(oprt === "mi")
{
document.getElementById("result").value = (mi*37000)/37000;
}
else if(oprt === "r")
{
document.getElementById("result").value = (mi*37000)/1000000;
}
}
if(slct==="r")
{ var r= parseFloat(document.getElementById("inpt").value);
if(oprt === "b")
{
document.getElementById("result").value = r*1000000;
}
else if(oprt === "k")
{
document.getElementById("result").value = (r*1000000)/1000;
}
else if(oprt === "m")
{
document.getElementById("result").value = (r*1000000)/1000000;
}
else if(oprt === "c")
{
document.getElementById("result").value = (r*1000000)/37000000000;
}
else if(oprt === "ml")
{
document.getElementById("result").value = (r*1000000)/37000000;
}
else if(oprt === "mi")
{
document.getElementById("result").value = (r*1000000)/37000;
}
else if(oprt === "r")
{
document.getElementById("result").value = (r*1000000)/1000000;
}
}
} |
$(document).ready(function(){
$('.fas.fa-chevron-left').on('click', () => $('.carousel.carousel-slider').carousel('prev'));
$('.fas.fa-chevron-right').on('click', () => $('.carousel.carousel-slider').carousel('next'));
$('.carousel.carousel-slider').carousel({
fullWidth: true,
indicators: true,
dist: 0,
});
$('.parallax').parallax();
$('.collapsible').collapsible();
$('.sidenav').sidenav();
});
$(window).scroll(() => {
showItems();
});
function animateValue(obj, start, end, duration) {
let startTimestamp = null;
const step = (timestamp) => {
if (!startTimestamp) startTimestamp = timestamp;
const progress = Math.min((timestamp - startTimestamp) / duration, 1);
obj.innerHTML = Math.floor(progress * (end - start) + start);
if (progress < 1) {
window.requestAnimationFrame(step);
}
};
window.requestAnimationFrame(step);
}
const vaka = document.getElementById("vakasayisi");
const basari = document.getElementById("basariorani");
const musteri = document.getElementById("musterisayisi");
const deneyim = document.getElementById("deneyimyili");
statFlag = true;
const showItems = () => {
let statsGraph = document.querySelector('.stats');
let statsPosition = statsGraph.getBoundingClientRect().top;
let about = document.querySelector('#about-animate');
let aboutPosition = about.getBoundingClientRect().top;
let practice = document.querySelector('#calisma-alanlarimiz');
let practicePosition = practice.getBoundingClientRect().top;
let blog = document.querySelector('#blog');
let blogPosition = blog.getBoundingClientRect().top;
let screenPosition = window.innerHeight / 1.5;
if(statsPosition < screenPosition) {
if(statFlag) {
statsGraph.classList.add('show-stats');
animateValue(vaka, 0, 2400, 2300);
animateValue(basari, 0, 98, 2300);
animateValue(musteri, 0, 752, 2300);
animateValue(deneyim, 0, 15, 2300);
statFlag = false;
}
}
aboutFlag = true;
if(aboutPosition < screenPosition) {
if(aboutFlag) {
$(about).addClass('show-text');
$(about).next().addClass('show-text');
aboutFlag = false;
}
}
practiceFlag = true;
if(practicePosition < screenPosition ) {
if(practiceFlag) {
$.each($(practice).find('.card-panel').slice(1), (i, el) => {
setTimeout(function() {
$(el).addClass('show-text');
}, i * 250)
});
$.each($('#calisma-alanlarimiz').find('li'), (i, el) => {
setTimeout(function() {
$(el).addClass('show-text');
}, i * 150)
});
practiceFlag = false;
}
}
blogFlag = true;
if(blogPosition < screenPosition / 2 ) {
if(blogFlag) {
$.each($(blog).find('.card'), (i, el) => {
setTimeout(function() {
$(el).addClass('show-text');
}, i * 120)
});
blogFlag = false;
}
}
} |
/* eslint-disable */
const pako = require('pako')
const DATATYPE = [
'null',
'miINT8',
'miUINT8',
'miINT16',
'miUINT16',
'miINT32',
'miUINT32',
'miSINGLE',
'Reserved',
'miDOUBLE',
'Reserved',
'Reserved',
'miINT64',
'miUINT64',
'miMATRIX',
'miCOMPRESSED',
'miUTF8',
'miUTF16',
'miUTF32']
const ARRAYTYPE = [
'null',
'mxCELL_CLASS',
'mxSTRUCT_CLASS',
'mxOBJECT_CLASS',
'mxCHAR_CLASS',
'mxSPARSE_CLASS',
'mxDOUBLE_CLASS',
'mxSINGLE_CLASS',
'mxINT8_CLASS',
'mxUINT8_CLASS',
'mxINT16_CLASS',
'mxUINT16_CLASS',
'mxINT32_CLASS',
'mxUINT32_CLASS',
'mxINT64_CLASS',
'miCOMPRESSED',
'mxUINT64_CLASS']
function MatFileLoader(buffer) {
this.endianIndicator = null;
this.header = null;
this.version = null;
this.load(buffer)
}
Object.assign( MatFileLoader.prototype , {
constructor: MatFileLoader,
load: function (buffer) {
// MAT文件由一个128字节的文件头和若干个数据单元组成
// 文件头header里有124字节的文本描述区域和4个字节的flag。flag中的前2个字节说明version,后两个字节是endian indicator的I和M。
let headerBuffer = new Uint8Array(buffer.slice(0,128))
let endianIndicator = String.fromCharCode(headerBuffer[126]) + String.fromCharCode(headerBuffer[127])
let header = "";
for (let i = 0; i < headerBuffer.length - 12; i++) {
header += String.fromCharCode(headerBuffer[i]);
}
this.header = header
this.version = parseFloat(headerBuffer[headerBuffer.length -3])
let data = new Uint8Array(buffer.slice(128))
let temp
if (endianIndicator === 'IM') for (let i = 0; i < data.length / 2; i++){
temp = data[i * 2 + 1];
data[i * 2 + 1] = data[i * 2];
data[i * 2] = temp;
}
data = buffer.slice(128)
this.endianIndicator = endianIndicator
this.data = this.parse(data)
},
parse: function (data) {
let data_size = 0
let data_info
let data_block
let data_array = []
for (let i = 0;i < data.byteLength;) {
data_info = new Uint16Array(data.slice(i,i+8))
if (data_info[1] === 0) {
data_size = new Uint32Array(data.slice(i+4,i+8))[0]
data_block = data.slice(i+8,i+8+data_size)
i += data_size+8
} else {
data_size = data_info[1]
data_block = data.slice(i+4,i+4+data_size)
i += data_size+4
}
if (DATATYPE[data_info[0]] === 'null') break
switch (DATATYPE[data_info[0]]){
case 'miMATRIX':
data_array.push(new MatArray(data_block))
break;
case 'miCOMPRESSED':
this.parse(pako.inflate(data_block).buffer).forEach(v=>data_array.push(v))
break;
case 'miUTF8':
break;
case 'miUTF16':
break;
case 'miUTF32':
break;
default:
break;
}
}
return data_array
},
toJSON: function () {
let data = this.data;
if (data.length === 1) data = data[0];
return JSON.stringify(data, function (key, value) {
if (value instanceof Array&&typeof value[0] === 'number') {
return '['+value.toString()+']';
}
if (value instanceof MatArray) {
let obj = {};
let data = value.data;
if (value.type === 'mxSTRUCT_CLASS') {
let subobj = {};
data.forEach(v=>subobj[v.name] = v.data);
data = subobj
}
obj[value.name] = data;
return obj;
}
return value;
}, '\t').replace(/\"/g,'')
}
} );
function MatObject() {}
Object.assign( MatObject.prototype , {
constructor: MatObject,
parseString: function(buffer) {
let str = '';
buffer = new Uint8Array(buffer);
for (let i = 0; i < buffer.length; i++) str += String.fromCharCode(buffer[i])
return str.replace(/\0/g,'')
}
} );
function MatArray(data) {
this.parse(data)
}
MatArray.prototype = Object.assign( Object.create( MatObject.prototype ) , {
constructor: MatArray,
parse: function (data) {
// header
let offset = 0;
let data_size = 0;
offset = 24;
let ArrayFlag = new Uint8Array(data.slice(8,16));
let DA = new Uint16Array(data.slice(16,24));
offset += Math.ceil(DA[2] / 8) * 8;
let temp = new Uint32Array(data.slice(24,24+DA[2]));
DA = [];
for (let i = 0; i < temp.length; i++) {
DA[i] = temp[i];
}
let arr_name_str;
temp = new Uint16Array(data.slice(offset,offset+8));
if (temp[1] === 0) {
data_size = temp[2];
arr_name_str = this.parseString(data.slice(offset+8,offset+8+data_size));
offset += 8+data_size
} else {
data_size = temp[1];
arr_name_str = this.parseString(data.slice(offset+4,offset+4+temp[1]));
offset += 4+data_size
}
offset = Math.ceil(offset/8)*8;
// body
this.size = '('+DA.toString()+')';
this.type = ARRAYTYPE[ArrayFlag[0]];
this.name = arr_name_str;
switch (ARRAYTYPE[ArrayFlag[0]]){
case 'mxSTRUCT_CLASS':
this.data = this.parseStructure(data.slice(offset));
break;
default:
this.data = this.parseArray(data.slice(offset), DA)
}
},
parseArray: function (data, DataArray) {
const arrayBufferToArray = function(arrayBuffer) {
if (arrayBuffer.length === 1) return arrayBuffer[0];
let array = [];
let isMatrix = false;
let isVoxel = false;
if (DataArray !== undefined) {
isVoxel = DataArray.length===3;
isMatrix = DataArray[0] !== 1
}
if (isVoxel){
for (let k = 0; k < DataArray[2]; k++) {
let page = [];
for (let i = 0; i < DataArray[0]; i++) {
let row = [];
for (let j = 0; j < DataArray[1]; j++) {
row[j] = arrayBuffer[i+j*DataArray[0]+k*DataArray[1]];
}
page[i] = row
}
array[k] = page
}
}else if (isMatrix) {
for (let i = 0; i < DataArray[0]; i++) {
let row = [];
for (let j = 0; j < DataArray[1]; j++) {
row[j] = arrayBuffer[i+j*DataArray[0]];
}
array[i] = row;
console.log('matrix')
}
}else {
for (let i = 0; i < arrayBuffer.length; i++) {
array[i] = arrayBuffer[i];
}
}
return array;
}
let data_size = 0;
let data_info;
let data_block;
let data_type;
let offet = 0;
data_info = new Uint16Array(data.slice(offet,offet+8));
data_type = DATATYPE[data_info[0]];
if (data_type === 'null') return;
if (data_info[1] === 0) {
data_size = new Uint32Array(data.slice(offet+4,offet+8))[0];
data_block = data.slice(offet+8,offet+8+data_size)
} else {
data_size = data_info[1];
data_block = data.slice(offet+4,offet+4+data_size)
}
switch (data_type){
case 'miINT8':
return arrayBufferToArray(new Int8Array(data_block));
case 'miUINT8':
return arrayBufferToArray(new Uint8Array(data_block));
case 'miINT16':
return arrayBufferToArray(new Int16Array(data_block));
case 'miUINT16':
return arrayBufferToArray(new Uint32Array(data_block));
case 'miINT32':
return arrayBufferToArray(new Int32Array(data_block));
case 'miUINT32':
return arrayBufferToArray(new Uint32Array(data_block));
case 'miSINGLE':
break;// 不会
case 'miDOUBLE':
return arrayBufferToArray(new Float64Array(data_block));
case 'miINT64':
return arrayBufferToArray(new BigInt64Array(data_block));
case 'miUINT64':
return arrayBufferToArray(new BigUint64Array(data_block));
default:
break;
}
},
parseStructure: function (data) {
let temp = new Int32Array(data.slice(0,16));
let field_count = temp[3] / temp[1];
let data_size = 0;
let field_name;
let field_name_size = temp[1];
let data_array = [];
let offset = 16+Math.ceil(temp[3]/8)*8;
for (let i = 0; i < field_count; i++){
field_name = this.parseString(data.slice(16+i*field_name_size,16+i*field_name_size+field_name_size));
temp = new Uint16Array(data.slice(offset,offset+8));
let field = new MatArray(data.slice(offset+8,offset+8+temp[2]));
field.name = field_name;
data_array.push(field);
offset = offset+temp[2]+8;
}
return data_array;
},
} );
export { MatFileLoader };
|
$("#start").on("click",function(){
game.start();
})
var questions =[{
question: "What was the first full length CGI movie?",
answers:["A Bug's Life","Monsters Inc.","Toy story","The Lion King"],
correctAnswer: "Toy Story"
},{
question: "Which of these is NOT a name of one of the Spice Girls?",
answers:["Sporty Spice","Fred Spice","Scary Spice","Posh Spice"],
correctAnswer:"Fred Spice"
},{
question: "Whic NBA team won the most titles in 90s?",
answers:["New York Knicks","Portland Trailblazers","Los Angeles clippers","Chicago Bulls"],
correctAnswer: "Chicago Bulls"
},{
question: 'Which group released the hit song, "Smells Like Teen Spirit?"',
answers:["Nirvana","Backstreet Boys","The OffSpring","No Doubt"],
correctAnswer: "Nirvana"
},{
question: 'Which popular Disney movie featured the song, "Circle of life"?',
answers:["Alladin","Hercules","Mulan","The Lion King"],
correctAnswer: "The Lion King"
},{
question: "What was Doug's best friend's name?",
answers:["Skeeter","Mark","Zack","Cody"],
correctAnswer:"Skeeter"
},{
question: 'Finish this line from the Fresh Prince of Bel-Air theme song:"I whistled for a cab and when it came near,the license plate said..."',
answers:["Dice","Mirror","Fresh","Cab"],
correctAnswer: "Fresh"
},{
question: "What was the name of the principal at Bayside High in Saved By The Bel?",
answers:["Mr.Zhou","Mr.Driggers","Mr.Belding","Mr.Page"],
correctAnswer:"Mr.Belding"
}];
var game = {
correct:0,
incorrect:0,
counter:100,
countdown: function(){
game.counter--;
$("#counter").html(game.counter);
if(game.counter<=0){
console.log("Time is up!");
game.done();
}
},
start: function(){
timer = setInterval(game.countdown,1000);
$("#subwrapper").prepend('<h2>Time Remaining: <span id="counter">100</span> Seconds</h2>');
$("#start").remove();
for(var i=0;i<questions.length;i++){
$("#subwrapper").append("<h2>"+questions[i].question+"</h2>");
for (var j=0;j<questions[i].answers.length;j++){
$("#subwrapper").append("<input type='radio' name='question-"+i+"' value='"+questions[i].answers[j]+"'>"+questions[i].answers[j])
}
}
},
done: function(){
$.each($('input[name="question-0"]:checked'),function(){
if($(this).val()==questions[0].correctAnswer){
game.correct++;
}
else {
game.incorrect++;
}
});
$.each($('input[name="question-1"]:checked'),function(){
if($(this).val()==questions[1].correctAnswer){
game.correct++;
}
else {
game.incorrect++;
}
});
$.each($('input[name="question-2"]:checked'),function(){
if($(this).val()==questions[2].correctAnswer){
game.correct++;
}
else {
game.incorrect++;
}
});
$.each($('input[name="question-3"]:checked'),function(){
if($(this).val()==questions[3].correctAnswer){
game.correct++;
}
else {
game.incorrect++;
}
});
$.each($('input[name="question-4"]:checked'),function(){
if($(this).val()==questions[4].correctAnswer){
game.correct++;
}
else {
game.incorrect++;
}
});
$.each($('input[name="question-5"]:checked'),function(){
if($(this).val()==questions[5].correctAnswer){
game.correct++;
}
else {
game.incorrect++;
}
});
$.each($('input[name="question-6"]:checked'),function(){
if($(this).val()==questions[6].correctAnswer){
game.correct++;
}
else {
game.incorrect++;
}
});
$.each($('input[name="question-7"]:checked'),function(){
if ($(this).val()==questions[7].correctAnswer){
game.correct++;
}
else {
game.incorrect++;
}
});
this.result();
},
result: function(){
clearInterval(timer);
$("#subwrapper h2").remove();
$("#subwrapper").html("<h2>All done!</h2>");
$("#subwrapper").append("<h3>Correct Answers: "+this.correct+"</h3>");
$("#subwrapper").append("<h3>Incorrect Answers: "+this.incorrect+"</h3>");
$("#subwrapper").append("<h3>Unanswered: "+(questions.length-(this.incorrect+this.correct))+"</h3>");
}
} |
/**
* Created by hasee on 2018/1/6.
*/
Ext.define('Admin.view.players.PlayersController', {
extend: 'Admin.view.BaseViewController',
alias: 'controller.players',
requires: ['Admin.view.brand.BrandForm'],
/**
* grid的store加载
*/
loadStore:function () {
var me = this, grid = me.lookupReference('grid');
grid.getStore().load({params:{match_id:this.getView().match_id}});
},
/**
* 关闭窗口
*/
closeWindow: function () {
this.getView().close();
},
/** 清除 查询 条件
* @param {Ext.button.Button} component
* @param {Event} e
*/
reset: function () {
//this.lookupReference('form').reset();
}
}); |
import { FETCH_USERS, NEW_USER } from "../actions/types";
import { getAllUsres, postUser } from '../helpers/requstHelper';
export const fetchUsers = () => dispatch => {
return dispatch({
type: FETCH_USERS,
users: getAllUsres()
});
};
export const addNewUser = (user) => dispatch => {
return dispatch({
type: NEW_USER,
user: postUser({
name: user.name,
email: user.email,
password: user.password,
registred: new Date()
})
});
}; |
//exercise 1
var total=0
for (var num=1; num < 6; num ++) {
total=total+num;
}
console.log(total)
//exercise 2
var line = "";
do{
var play = prompt("Do You Want To Play?");
var word = prompt("Enter A Word");
line = line + " " + word;
}while (play === "yes");
console.log(line);
//exercise 3
var person = prompt("Would You Like to Print Your Name?");
var x = "!";
var count = "";
while (person === "yes") {
var name = prompt("What's Your Name?");
var y = count += x;
console.log(name + y);
var person = prompt("Would You Like to Print Your Name?");
}
//exercise 4
var choice = prompt("What Time Of Day Is It?");
switch (choice) {
case 'morning':
console.log("Since it is morning, you should eat breakfast. We suggest eggs and toast.");
break;
case 'noon':
console.log("Since it is noon, you should eat lunch. We suggest a salad.");
break;
case 'evening':
console.log("Since it is evening, you should eat dinner. We suggest chicken and rice.");
break;
default:
para.textContent = '';
}
|
function random_from_array(images){ //Função que gera números aletórios a partir do tamanho de images
return images[Math.floor(Math.random() * images.length)]; //Math.random() -> gera um número aleatório de 0 a 1 mas nunca seleciona o 1, a partir daí você multiplica o tamanho de images por esse número aleatório e faz o floor desse número vôce obtém um número aletório para uma imagem na pasta menos o último número, porém isso não importa, pois o index de array em Js começa do 0. images.length() -> sempre retorna o tamanho total de arquivos na pasta.
}
/*-------------------------------------------------------------------------------------------------*/
function upload_random_images(images){ //Função que faz o upload de imagens aleatórias de /image/ dentro da pasta e faz o post no twitter
console.log('Opening an image...');
var image_path = path.join(__dirname, '/images/' + random_from_array(images)),
b64content = fs.readFileSync(image_path, { encoding: 'base64' });
console.log('Uploading an image...');
T.post('media/upload', { media_data: b64content}, function(err, data, response){
if(err){
console.log('ERROR:');
console.log(err);
} else {
console.log('Image Uploaded!');
console.log('Now tweeting it...');
T.post('statuses/update', {
media_ids: new Array(data.media_id_string)
},
function(err, data, response){
if(err){
console.log('ERROR:');
console.log(err);
} else {
console.log('Posted an image!');
}
}
);
}
});
}
/*-------------------------------------------------------------------------------------------------*/
var Twit = require('twit')
var fs = require('fs'),
path = require('path'),
Twit = require('twit'),
config = require(path.join(__dirname, 'config.js'));
var T = new Twit(config);
fs.readdir(__dirname + '/images', function(err, files){
if(err){
console.log(err);
} else {
var images = [];
files.forEach(function(f){
images.push(f);
});
setInterval(function(){
upload_random_images(images);
}, 3600000);
}
});
|
const boton = document.getElementById('arrancar')
boton.addEventListener('click', ()=>{
const llanta1 = document.getElementById('llanta1')
const llanta2 = document.getElementById('llanta2')
llanta1.style.animationPlayState = 'running'
llanta2.style.animationPlayState = 'running'
}) |
import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { fakeAccountLogin, getFakeCaptcha } from '@/services/api';
import { setAuthority } from '@/utils/authority';
// import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
export default {
namespace: 'login',
state: {
status: undefined,
},
effects: {
*login({ payload }, { call, put }) {
const response = yield call(fakeAccountLogin, payload);
yield put({
type: 'changeLoginStatus',
payload: response,
});
// Login successfully
if (response.status === 'ok') {
var loginDate = moment().format('YYYY/MM/DD HH:mm:ss');
//设置当前登录用户和权限后,就可以跳转到指定页面
localStorage.setItem('adminName', response.userName);
localStorage.setItem('cellmonitor-loginDate', loginDate);
setAuthority(response.currentAuthority);
window.location.href = '/payorder/query';
}
},
*getCaptcha({ payload }, { call }) {
yield call(getFakeCaptcha, payload);
},
*logout(_, { put }) {
yield put({
type: 'changeLoginStatus',
payload: {
status: undefined,
type: 'account',
},
});
localStorage.setItem('adminName', '');
localStorage.setItem('cellmonitor-loginDate', '');
setAuthority('guest');
yield put(
routerRedux.push({
pathname: '/user/login',
search: stringify({
redirect: window.location.href,
}),
})
);
},
},
reducers: {
changeLoginStatus(state, { payload }) {
return {
...state,
status: payload.status,
type: payload.type,
};
},
},
};
|
let o = {};
let a = new WeakMap( [
[ o, '123' ]
] );
console.log( a.has( o ) );
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import '../../../assets/intro.js'
import '../../../assets/introjs.css'
import { Steps, Hints } from 'intro.js-react'
// eslint-disable-next-line valid-jsdoc
/**
* A component that leverages intro.js under the hood to provide the Hello component
* from musicfox.io. Include the steps you'd like to highlight and more.
*
* This component uses [intro.js](https://intro.js.com/) and thus far most endpoints for Steps
* are implemented.
*/
export default class Hello extends Component {
constructor(props) {
super(props);
this.state = {
stepsEnabled: true,
initialStep: 0,
onExit :()=>{
this.setState(() => ({stepsEnabled: false}));
},
}
}
render() {
const { stepsEnabled, initialStep, onExit, } = this.state;
const {
id,
setProps,
steps,
nextLabel,
prevLabel,
skipLabel,
doneLabel,
hidePrev,
hideNext,
defaultTooltipPos,
tooltipClass,
highlightClass,
exitOnEsc,
exitOnOverlayClick,
showStepNumbers,
keyboardNavigation,
showProgress,
overlayOpacity
} = this.props;
const options = {};
const value = this.props;
value && (options.value = value)
return (
<div id={id}>
<Steps
enabled={stepsEnabled}
steps={steps}
initialStep={0}
onExit={onExit}
options={{
nextLabel: this.props.nextLabel,
prevLabel: this.props.prevLabel,
skipLabel: this.props.skipLabel,
doneLabel: this.props.doneLabel,
hidePrev: this.props.hidePrev,
hideNext: this.props.hideNext,
defaultTooltipPos: this.props.defaultTooltipPos,
// tooltipClass: this.props.tooltipClass,
// highlightClass: this.props.highlightClass,
exitOnEsc: this.props.exitOnEsc,
exitOnOverlayClick: this.props.exitOnOverlayClick,
showStepNumbers: this.props.showStepNumbers,
keyboardNavigation: this.props.keyboardNavigation,
showProgress: this.props.showProgress,
overlayOpacity: this.props.overlayOpacity
}}
/>
</div>
);
}
}
Hello.defaultProps = {
/* Define default properties (intro.js options) here */
nextLabel: "Next",
prevLabel: "Previous",
skipLabel: "Skip tutorial",
doneLabel: "Done",
hidePrev: true,
hideNext: true,
defaultTooltipPos: 'bottom',
exitOnEsc: true,
exitOnOverlayClick: true,
showStepNumbers: true,
keyboardNavigation: true,
showProgress: true,
overlayOpacity: .5
};
Hello.propTypes = {
/**
* The ID used to identify this component in Dash callbacks
*/
id: PropTypes.string,
/**
* Dash-assigned callback that should be called whenever any of the
* properties change
*/
setProps: PropTypes.func,
/**
* List of dictionaries containing each step, with "intro" and "element"
* keys, at a minimum.
*/
steps: PropTypes.array.isRequired,
/**
* nextLabel
*
* String label for the "next" button
*
*/
nextLabel: PropTypes.string,
/**
* prevLabel
*
* String label for the "prev" button
*
*/
prevLabel: PropTypes.string,
/**
* skipLabel
*
* String label for the "skip" button
*
*/
skipLabel: PropTypes.string,
/**
* doneLabel
*
* String label for the "done" button
*/
doneLabel: PropTypes.string,
/**
*
* hidePrev
*
* Boolean true to hide "prev" button in the first step, default is false,
* disabled (grayed-out).
*/
hidePrev: PropTypes.bool,
/**
* hideNext
*
* Boolean true to hide "next" button in the last step, default is false,
* disabled (grayed-out).
*/
hideNext: PropTypes.bool,
/**
* defaultTooltipPos
*
* String default tooltip position (these can be changed per-step)
*/
defaultTooltipPos: PropTypes.string,
/**
* tooltipClass
*
* String class of all tooltip CSS
*/
tooltipClass: PropTypes.string,
/**
*
* highlightClass
*
* String class of all highlight over tooltip CSS (for the helperLayer) in
* intro.js
*/
highlightClass: PropTypes.string,
/**
*
* exitOnEsc
*
* Boolean true exits with an esc keypress, defaults to true
*/
exitOnEsc: PropTypes.bool,
/**
*
* exitOnOverlayClick
*
* Boolean true exits if clicking on the overlay, defaults to false
*/
exitOnOverlayClick: PropTypes.bool,
/**
*
* showStepNumbers
*
* Boolean true shows the steps in the red circle, default true
*
*/
showStepNumbers: PropTypes.bool,
/**
* keyboardNavigation
*
* Boolean true allows navigating with the keyboard
*/
keyboardNavigation: PropTypes.bool,
/**
* showProgress
*
*
* Boolean true shows the progress bar
*
*/
showProgress: PropTypes.bool,
/**
*
* overlayOpacity
*
* Number between 0 and 1 adjusts the opacity of the overlay layer
*/
overlayOpacity: PropTypes.number,
};
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Wysiwyg from '../../components/WYSIWYG'
import Layout from '../../components/Layout'
import Footer from '../../components/Footer'
import s from './Content.css'
import { loadAllPosts } from '../../actions/Content/actions'
const title = 'Conteudo Personalizado'
class Content extends Component{
componentWillMount() {
this.props.loadAllPosts()
}
componentDidMount() {
document.title = title
}
render(){
return(
<Layout>
<div className={`${s.conteudo}`}>
<div className={`${s.wrapperContainer}`}>
<Wysiwyg />
</div>
</div>
<Footer></Footer>
</Layout>
)
}
}
const mapStateToProps = (state) => {
return{
conteudo: state.content.conteudo
}
}
const mapDispatchToProps = (dispatch) =>
bindActionCreators({ loadAllPosts }, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(Content)
|
function biggieSize(arr){
for (x=0; x<arr.length; x++){
if (0<arr[x]){
arr[x]="big";
}
}
return arr;
}
arr=[-1,3,5,-5]
console.log(biggieSize(arr));
function printLowReturnHigh(arr){
min=arr[0];
max=arr[0];
for (x=0; x<arr.length; x++){
if (min>arr[x]){
min=arr[x]
}
if (max<arr[x]){
max=arr[x]
}
}
console.log(min);
return max;
}
arr=[-1,3,5,-5]
console.log(printLowReturnHigh(arr));
function printOneReturnAnother(arr){
odd=0;
for(x=1;x<arr.length;x++){
console.log(arr[x])
}
for(x=0;x<arr.length;x++){
if(arr[x]%2==1){
odd=arr[x];
return odd;
}
}
}
arr=[2,2,3,45,6,]
console.log(printOneReturnAnother(arr));
function doubleVision(arr){
arrnew=[];
for(x=0;x<arr.length;x++){
arrnew.push(arr[x]*=2);
}
return arrnew;
}
arr =[1,2,3];
console.log(doubleVision(arr));
function countPositives(arr){
var count =0;
for(x=0;x<=arr.length;x++){
if(arr[x]>0)
count++;
}
arr.pop();
arr.push(count);
return arr;
}
arr =[-1,1,1,1];
console.log(countPositives(arr));
function evensOdds(arr){
for(x=0;x<arr.length;x++){
if(arr[x]%2==1){
if(arr[x+1]%2==1){
if(arr[x+2]%2==1){
console.log("That's odd!");
}
}
}
if(arr[x]%2==0){
if(arr[x+1]%2==0){
if(arr[x+2]%2==0){
console.log("Even more so!");
}
}
}
}
}
arr=[1,3,2,2,4,6];
console.log(evensOdds(arr));
function incrementTheSeconds(arr){
var count =0;
for(x=0;x<arr.length;x++){
if(x%2!=0){
arr[x]=arr[x]+1;
}
console.log(arr[x]);
}
return arr;
}
arr =[1,2,3,4];
console.log(incrementTheSeconds(arr));
function previousLengths(arr){
for (x=arr.length-1;x>0;x--){
arr[x] = arr[x-1].length;
}
return arr;
}
arr=["hello", "dojo", "awesome"];
console.log(previousLengths(arr));
function addSeven(arr){
newarr=[];
for(x=0;x<arr.length;x++){
newarr.push(arr[x]+=7);
}
return newarr;
}
console.log(addSeven([1,2,3]));
function reverse(arr){
arr.reverse();
return arr;
}
arr=[1,2,3,4];
console.log(reverse(arr));
function outlook(arr){
newarr=[];
for(x=0;x<arr.length;x++){
if(arr[x]<0)
newarr.push(arr[x]);
else
newarr.push(-arr[x])
}
return newarr;
}
arr=[1,-3,5,7]
console.log(outlook(arr));
function hungry(arr){
count=0;
for(x=0;x<arr.length;x++){
if(arr[x]=="food"){
console.log("yummy")
count++;
}
}
if(count==0){
console.log("I'm hungry")
}
}
arr=["nouf", "nouf", "food","nouf"];
console.log(hungry(arr));
function swapTowardCenter(arr){
temp=arr[0];
arr[0]=arr[arr.length-1];
arr[arr.length-1]=temp;
b=arr.length-2;
for(x=1;x<b;x++){
temp=arr[x+1];
arr[x+1]=arr[b-1];
arr[b-1]=temp;
b--;
}
console.log(arr)
}
arr=[1,6,3,4,1,7,2];
swapTowardCenter(arr);
function scaleArray(arr,num){
for(x=0;x<arr.length;x++){
arr[x]*=num;
}
return arr;
}
console.log(scaleArray([1,2,3], 3));
|
debugger;
var elem = document.getElementById('tree');
var htmlStructure = {
name: 'p',
content: ' Some Text in Para',
params: 'class="green"',
subTags: [{
name: 'u',
content: ' some underlined text ',
params: '',
subTags: [
{
name: 'a',
content: '1111',
params: 'href="#"',
}
]
},
{
name: 'br',
content: ' some italic text ',
params: 'class="red"',
}]
}
function getHtml(structure){
//return '<p class="red"><u></u><i></i></p>';
if (isPair(structure.name)){
var result = "<" + structure.name + " " + structure.params + ">";
if ('subTags' in structure){
for (var i=0;i<structure.subTags.length;i++){
result += getHtml(structure.subTags[i]);
}
}
if ('content' in structure){
result += structure.content;
}
result += "</" + structure.name + ">";
}else{
result = ""
}
return result;
//return '<p></p>';
}
function isPair(tag1){
var validTagCounter = 0, invalidTagCounter = 0;
var tags = ['area','base','basefont','bgsound','br','col','command', 'embed','hr','img','input','isindex','keygen','link','meta','param','source','track','wbr'];
for (var i in tags){
if (tag1 == tags[i]){
return false;
function valid(){
invalidTagCounter++;
}
}
}
return [true,valid]
function valid(){
validTagCounter++;
}
}
alert(getHtml(htmlStructure))
elem.innerHTML = getHtml(htmlStructure); |
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import {BrowserRouter, Route, Redirect} from 'react-router-dom'
import Cookie from 'universal-cookie'
// Route Components
import Generic from './home/main.jsx'
const cookie = new Cookie()
export default class Router extends Component{
constructor(props){
super(props);
this.state = {
auth: false
}
}
render(){
return(
<div>
<BrowserRouter>
<div>
<Route exact path="/" component={Generic} />
<Route exact path="/dashboard" render={(props) => (
cookie.get("cookie_name") ? (
<Generic {...props} />
) : (
<Redirect to="/"/>
)
)}/>
</div>
</BrowserRouter>
</div>
)
}
}
|
function search(elements, value) {
let index = 1;
while (elements.elementAt(index) !== -1 && elements.elementAt(index) < value) {
index *= 2;
}
return binarySearch(elements, value, index / 2, index)
}
function binarySearch(list, value, low, high) {
let mid = undefined;
while (low <= high) {
mid = (low + high) / 2;
middle = list.elementAt[mid];
if(middle > value || middle !== -1){
high = middle - 1;
}else if(middle < value){
low = middle+1;
}else{
return mid;
}
}
return -1;
} |
import React, { Component, PropTypes } from 'react';
import { View,
Text,
StyleSheet,
Image,
TextInput,
TouchableHighlight,
ToastAndroid,
AsyncStorage
} from 'react-native';
export default class ChangeName extends Component {
static propTypes = {
uid: PropTypes.string
}
constructor(props) {
super(props);
this.state = {
firstN: '',
lastN: '',
}
}
saveName = () => {
if (this.state.firstN === '' && this.state.lastN === '') {
Alert.alert('Error', 'Please enter a new first and last name');
} else {
firebase.database().ref(`Users/${this.props.uid}`).update({
firstName: this.state.firstN,
lastName: this.state.lastN,
displayName: `${this.state.firstN} ${this.state.lastN}`
});
ToastAndroid.show('Saved', ToastAndroid.SHORT);
this.setState({firstN: '', lastN: ''});
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.inputs}>
<TextInput
value={this.state.firstN}
onChangeText={ (firstN) => this.setState({firstN}) }
style={[styles.input, {width: 160}]}
underlineColorAndroid='#02C39A'
placeholder="First name"
autoCapitalize="sentences"
/>
<TextInput
value={this.state.lastN}
onChangeText={ (lastN) => this.setState({lastN}) }
style={[styles.input, {width: 160}]}
underlineColorAndroid='#02C39A'
placeholder="Last name"
autoCapitalize="sentences"
/>
</View>
<View style={{flexDirection: 'row', justifyContent: 'flex-end', marginTop: 10, marginBottom: 5}}>
<TouchableHighlight style={styles.saveName} onPress={this.saveName}>
<Text style={styles.saveText}>Save</Text>
</TouchableHighlight>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
paddingRight: 16,
paddingLeft: 16
},
inputs: {
flexDirection: 'row',
justifyContent: 'space-between',
},
input: {
paddingBottom: 6,
fontSize: 16,
},
saveName: {
height: 40,
width: 70,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 6,
backgroundColor: '#02C39A'
},
saveText: {
color: 'white',
fontWeight: 'bold',
fontSize: 18
},
})
|
import * as constants from './constants';
export function userLogin(username, password) {
return {
type: constants.LOGIN_REQUEST,
payload: {
username,
password,
},
};
}
export function userLoginSuccess(cookie, username) {
return {
type: constants.LOGIN_SUCCESS,
payload: {
cookie,
username,
},
};
}
export function userLoginFailure(message, error) {
return {
type: constants.LOGIN_FAILURE,
payload: {
message,
error,
},
};
}
export function getUser(username) {
return {
type: constants.GET_USER_REQUEST,
payload: {
username,
},
};
}
export function getUserSuccess({ created, karma, about }) {
return {
type: constants.GET_USER_SUCCESS,
payload: {
created,
karma,
about,
},
};
}
export function getUserFailure(message, error) {
return {
type: constants.GET_USER_FAILURE,
payload: {
message,
error,
},
};
}
|
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const products = require('./routes/products');
const ENV = require('dotenv')
ENV.config();
const PORT = 5000;
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use('/products', products)
app.listen(PORT, function () {
console.log(`I'm starting on port ${PORT}`)
}) |
import React, {Component} from 'react';
import { Table, Icon, Divider } from 'antd';
import {Link} from 'react-router'
import './css/supplier.scss';
export default class AllMatt extends Component{
constructor(props){
super(props);
this.state={
data:null,
num:0,
}
}
//初始化加载
componentDidMount(){
}
changeToMysupply=(id)=>{
window.name = id;
window.location.href='#MyProcess?id='+id;
}
render(){
const conts = this.props.listCont;
console.log(999);
console.log(conts);
const cont = conts&&conts.length>0&&conts.map((item,index)=>(
item.NUM>0?<li key={index} style={{color:'rgba(0, 0, 0, 0.65)'}}><Link to={{pathname:'MyProcess',query:{id:item.EAF_ID}}}><i className="lineCont">{item.FLOW_NAME}</i><span>({item.NUM>0?<i className="reds">{item.NUM}</i>:<i>{item.NUM}</i>})</span></Link></li>:
<li key={index} style={{color:'rgba(0, 0, 0, 0.65)'}}><i className="lineCont">{item.FLOW_NAME}</i><span>({item.NUM>0?<i className="reds">{item.NUM}</i>:<i>{item.NUM}</i>})</span></li>
))
return (
<div>
<ul id="supp-ul">
{cont}
</ul>
</div>
)
}
}
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Slider from "react-slick";
import { withStyles, createStyleSheet } from 'material-ui/styles';
import Typography from 'material-ui/Typography';
import {Image} from 'cloudinary-react';
import {PrevArrow, NextArrow} from '../../arrows';
const styleSheet = createStyleSheet('MediaNews', theme => ({
bg: {
backgroundColor: '#DCDCDC',
padding: '20px 0'
},
item: {
display: 'flex',
justifyContent: 'center'
},
slider: {
width: '95%',
margin: '20px auto'
},
text: {
paddingBottom: 20,
fontWeight: 700,
letterSpacing: 1,
textAlign: window.screen.width < 900 ? 'center' : 'left',
},
logoMedia: {
width: '60%',
objectFit: 'contain',
textAlign: window.screen.width < 900 ? 'center' : 'left'
}
}));
class MediaNews extends Component {
render() {
const { classes, text } = this.props;
const settings = {
infinite: true,
slidesToShow: window.screen.width < 900 ? '2' : '3',
slidesToScroll: 1,
adaptativeHeight: true,
autoplay: true,
autoplaySpeed: 5000,
speed: 500,
arrows: false,
prevArrow: <PrevArrow white />,
nextArrow: <NextArrow white />,
}
return (
<div className="media-news">
<div className="container padding">
<Typography type="title" paragraph className="media-news-title">{text}</Typography>
<Slider {...settings} className={classes.slider}>
<div>
<a className={classes.item} rel="noopener noreferrer" target="_blank" href="https://catracalivre.com.br/geral/agenda/indicacao/startup-conecta-pessoas-que-tem-interesse-de-viajar-e-realizar-voluntariado-no-brasil/">
<Image
cloudName="vivala"
publicId="catracalivre-icone_ilcoly.png"
height={40}
crop="scale" alt="Logo Catraca Livre"
className={classes.logoMedia}
/>
</a>
</div>
<div>
<a className={classes.item} rel="noopener noreferrer" target="_blank" href="http://projetodraft.com/viagens-com-voluntariado-essa-e-a-proposta-da-vivala-para-se-destacar-no-mercado-do-turismo-de-experiencia/">
<Image
cloudName="vivala"
publicId="draft-icone_eqejjv"
height={40}
crop="scale" alt="Logo Projeto Draft.png"
className={classes.logoMedia}
/>
</a>
</div>
<div>
<a className={classes.item} rel="noopener noreferrer" target="_blank" href="https://www.freetheessence.com.br/unplug/inspire-se/vivala-viajar-voluntariado/">
<Image
cloudName="vivala"
publicId="freetheessence-icone_artmgm"
height={40}
crop="scale" alt="Logo Free The Esseence.png"
className={classes.logoMedia}
/>
</a>
</div>
<div>
<a className={classes.item} rel="noopener noreferrer" target="_blank" href="https://conteudo.startse.com.br/startups/julia_miozzo/trabalho-voluntrio-para-viajar-startup-conecta-usurios-a-oportunidades/">
<Image
cloudName="vivala"
publicId="startse-icone_qnheqy.png"
height={40}
crop="scale" alt="Logo StartSe"
className={classes.logoMedia}
/>
</a>
</div>
<div>
<a className={classes.item} rel="noopener noreferrer" target="_blank" href="http://www.fiesp.com.br/mobile/noticia/?id=216115">
<Image
cloudName="vivala"
publicId="fiesp-icone_oiocia"
height={40}
crop="scale" alt="Logo FIESP"
className={classes.logoMedia}
/>
</a>
</div>
</Slider>
</div>
</div>
);
}
}
MediaNews.propTypes = {
classes: PropTypes.object.isRequired,
text: PropTypes.string.isRequired,
items: PropTypes.object,
};
export default withStyles(styleSheet)(MediaNews);
|
import api from '../connect/api.jsx'
import daemon from './daemon.jsx'
import freeze from 'deep-freeze'
import Invalid from '../ui/page/invalid.jsx'
import package_json from '../package.json'
import React from 'react'
import {start, createTokenInfo} from '../util/index.jsx'
export default async function handshake() {
const data = {
app: package_json.name,
time: start.getTime(),
v: package_json.version,
}
const config = await api.send('token/handshake', data, createTokenInfo())
if (409 === config.status) {
Invalid.render()
return false
}
api.config = freeze(config)
api.setToken(api.config.token.id)
if (api.config.daemons instanceof Array && api.config.daemons.length > 0) {
daemon(api.config.daemons)
}
return true
}
|
// Utils
import { QColorizeMixin } from 'q-colorize-mixin'
import canRender from 'quasar/src/mixins/can-render'
import {
QSlider,
QBtn,
QTooltip,
QMenu,
QExpansionItem,
QList,
QItem,
QItemSection,
QIcon,
QSpinner,
ClosePopup,
Ripple
} from 'quasar'
const getMousePosition = function (e, type = 'x') {
if (type === 'x') {
return e.pageX
}
return e.pageY
}
const padTime = (val) => {
val = Math.floor(val)
if (val < 10) {
return '0' + val
}
return val + ''
}
const timeParse = (sec) => {
let min = 0
min = Math.floor(sec / 60)
sec = sec - min * 60
return padTime(min) + ':' + padTime(sec)
}
export default {
name: 'QMediaPlayer',
directives: {
ClosePopup,
Ripple
},
mixins: [QColorizeMixin, canRender],
props: {
type: {
type: String,
required: false,
default: 'video',
validator: v => ['video', 'audio'].includes(v)
},
mobileMode: Boolean,
source: String,
sources: {
type: Array,
default: () => []
},
poster: {
type: String,
default: ''
},
tracks: {
type: Array,
default: () => []
},
dense: Boolean,
autoplay: Boolean,
crossOrigin: {
type: [String, null],
default: null,
validator: v => v === null || ['anonymous', 'use-credentials'].includes(v)
},
volume: {
type: Number,
default: 60,
validator: v => v >= 0 && v <= 100
},
hideVolumeSlider: Boolean,
hideVolumeBtn: Boolean,
hidePlayBtn: Boolean,
hideSettingsBtn: Boolean,
hideFullscreenBtn: Boolean,
disabledSeek: Boolean,
preload: {
type: String,
default: 'metadata',
validator: v => ['none', 'metadata', 'auto'].includes(v)
},
noVideo: Boolean,
muted: Boolean,
playsinline: Boolean,
loop: Boolean,
trackLanguage: {
type: String,
default: 'off' // value for 'Off'
},
showTooltips: Boolean,
showBigPlayButton: {
type: Boolean,
default: true
},
showSpinner: {
type: Boolean,
default: true
},
spinnerSize: String,
noControls: Boolean,
nativeControls: Boolean,
bottomControls: {
type: Boolean,
default: false
},
controlsDisplayTime: {
type: Number,
default: 2000
},
playbackRates: Array,
// initial playback rate
playbackRate: {
type: Number,
default: 1
},
color: {
type: String,
default: 'white'
},
backgroundColor: {
type: String,
default: 'black'
},
bigPlayButtonColor: {
type: String,
default: 'white'
},
dark: Boolean,
radius: {
type: [Number, String],
default: 0
},
contentStyle: [String, Object, Array],
contentClass: [String, Object, Array],
contentWidth: Number,
contentHeight: Number
},
data () {
return {
lang: {
mediaPlayer: {}
},
iconSet: {
mediaPlayer: {}
},
$media: null, // the actual video/audio player
timer: {
// timer used to hide control during mouse inactivity
hideControlsTimer: null
},
state: {
errorText: null,
controls: false,
showControls: true,
volume: 60,
muted: false,
currentTime: 0.01,
duration: 1,
durationTime: '00:00',
remainingTime: '00:00',
displayTime: '00:00',
inFullscreen: false,
loading: true,
playReady: false,
playing: false,
playbackRates: [
{ label: '.5x', value: 0.5 },
{ label: 'Normal', value: 1 },
{ label: '1.5x', value: 1.5 },
{ label: '2x', value: 2 }
],
playbackRate: 1,
trackLanguage: 'Off',
showBigPlayButton: true,
metadataLoaded: false,
spinnerSize: '5em',
bottomControls: false
},
allEvents: [
'abort',
'canplay',
'canplaythrough',
'durationchange',
'emptied',
'ended',
'error',
'interruptbegin',
'interruptend',
'loadeddata',
'loadedmetadata',
'loadedstart',
'pause',
'play',
'playing',
'progress',
'ratechange',
'seeked',
'timeupdate',
'volumechange',
'waiting'
],
settingsMenuVisible: false
}
},
beforeMount () {
this.__setupLang()
this.__setupIcons()
document.body.addEventListener('mousemove', this.__mouseMoveAction, false)
},
mounted () {
this.$nextTick(function () {
this.__init()
if (this.$media) {
// eslint-disable-next-line vue/custom-event-name-casing
this.$emit('mediaPlayer', this.$media)
}
})
},
beforeDestroy () {
// make sure not still in fullscreen
this.exitFullscreen()
// make sure noScroll is not left in unintended state
document.body.classList.remove('no-scroll')
document.body.removeEventListener('mousemove', this.__mouseMoveAction)
this.__removeSourceEventListeners()
this.__removeMediaEventListeners()
// make sure no memory leaks
this.__removeTracks()
this.__removeSources()
this.$media = null
},
computed: {
__classes () {
return {
'q-media__fullscreen': this.state.inFullscreen,
'q-media__fullscreen--window': this.state.inFullscreen
}
},
__renderVideoClasses () {
return 'q-media--player' +
(!this.dense && this.state.bottomControls && this.state.inFullscreen ? ' q-media--player--bottom-controls--standard' : '') +
(this.dense && this.state.bottomControls && this.state.inFullscreen ? ' q-media--player--bottom-controls--dense' : '')
},
__videoControlsClasses () {
return {
'q-media__controls--dense': !this.$slots.controls && ((this.state.showControls || this.mobileMode) && this.dense),
'q-media__controls--standard': !this.$slots.controls && ((this.state.showControls || this.mobileMode) && !this.dense),
'q-media__controls--hidden': !this.state.showControls,
'q-media__controls--bottom-controls': this.state.bottomControls
}
},
__audioControlsClasses () {
return {
'q-media__controls--dense': this.dense,
'q-media__controls--standard': !this.dense,
'q-media__controls--bottom-controls': this.state.bottomControls
}
},
__contentStyle () {
const style = {}
if (this.state.inFullscreen !== true) {
if (this.contentStyle !== void 0) {
if (typeof this.contentStyle === 'string') {
const parts = this.contentStyle.replace(/\s+/g, '').split(';')
parts.forEach(part => {
if (part !== '') {
const data = part.split(':')
style[data[0]] = data[1]
}
})
}
else {
Object.assign(style, this.contentStyle)
}
}
if (this.bottomControls === true && style.height === void 0) {
// const size = this.dense === true ? 40 : 80
style.height = `calc(100% - ${this.__controlsHeight}px)`
}
if (style.height === void 0) {
style.height = '100%'
}
}
return style
},
// videoWidth () {
// if (this.$el) {
// return this.$el.getBoundingClientRect().width
// }
// return 0
// },
__volumeIcon () {
if (this.state.volume > 1 && this.state.volume < 70 && !this.state.muted) {
return this.iconSet.mediaPlayer.volumeDown
}
else if (this.state.volume >= 70 && !this.state.muted) {
return this.iconSet.mediaPlayer.volumeUp
}
else {
return this.iconSet.mediaPlayer.volumeOff
}
},
__selectTracksLanguageList () {
const tracksList = []
// provide option to turn subtitles/captions/chapters off
const track = {}
track.label = this.lang.mediaPlayer.trackLanguageOff
track.value = 'off'
tracksList.push(track)
for (let index = 0; index < this.tracks.length; ++index) {
const track = {}
track.label = track.value = this.tracks[index].label
tracksList.push(track)
}
return tracksList
},
__isAudio () {
return this.type === 'audio'
},
__isVideo () {
return this.type === 'video'
},
__settingsPlaybackCaption () {
let caption = ''
this.state.playbackRates.forEach((rate) => {
if (rate.value === this.state.playbackRate) {
caption = rate.label
}
})
return caption
},
__controlsHeight () {
if (this.$refs.controls) {
return this.$refs.controls.clientHeight
}
return this.dense ? 40 : 80
}
},
watch: {
poster () {
this.__updatePoster()
},
sources: {
handler () {
this.__updateSources()
},
deep: true
},
source () {
this.__updateSources()
},
tracks: {
handler () {
this.__updateTracks()
},
deep: true
},
volume () {
this.__updateVolume()
},
muted () {
this.__updateMuted()
},
trackLanguage () {
this.__updateTrackLanguage()
},
showBigPlayButton () {
this.__updateBigPlayButton()
},
playbackRates () {
this.__updatePlaybackRates()
},
playbackRate () {
this.__updatePlaybackRate()
},
$route (val) {
this.exitFullscreen()
},
'$q.lang.isoName' (val) {
this.__setupLang()
},
'$q.iconSet.name' (val) {
this.__setupIcons()
},
'$q.fullscreen.isActive' (val) {
// user pressed F11/ESC to exit fullscreen
if (!val && this.__isVideo && this.state.inFullscreen) {
this.exitFullscreen()
}
},
'state.playbackRate' (val) {
if (val && this.$media) {
this.$media.playbackRate = parseFloat(val)
// eslint-disable-next-line vue/custom-event-name-casing
this.$emit('playbackRate', val)
}
},
'state.trackLanguage' (val) {
this.__toggleCaptions()
// eslint-disable-next-line vue/custom-event-name-casing
this.$emit('trackLanguage', val)
},
'state.showControls' (val) {
if (this.__isVideo && !this.state.noControls) {
// eslint-disable-next-line vue/custom-event-name-casing
this.$emit('showControls', val)
}
},
'state.volume' (val) {
if (this.$media) {
const volume = parseFloat(val / 100.0)
if (this.$media.volume !== volume) {
this.$media.volume = volume
this.$emit('volume', val)
}
}
},
'state.muted' (val) {
this.$emit('muted', val)
},
'state.currentTime' (val) {
if (this.$media && this.state.playReady) {
if (isFinite(this.$media.duration)) {
this.state.remainingTime = timeParse(this.$media.duration - this.$media.currentTime)
}
this.state.displayTime = timeParse(this.$media.currentTime)
}
},
bottomControls (val) {
this.state.bottomControls = val
if (val) {
this.state.showControls = true
}
},
noControls (val) {
this.state.noControls = val
if (this.nativeControls === true) {
this.state.noControls = true
}
}
},
methods: {
loadFileBlob (fileList) {
if (fileList && this.$media) {
if (Object.prototype.toString.call(fileList) === '[object FileList]') {
const reader = new FileReader()
const self = this
reader.onload = (event) => {
self.$media.src = event.target.result
self.__reset()
self.__addSourceEventListeners()
self.$media.load()
self.state.loading = false
}
reader.readAsDataURL(fileList[0])
return true
}
else {
/* eslint-disable-next-line no-console */
console.error('QMediaPlayer: loadFileBlob method requires a FileList')
}
}
return false
},
showControls () {
if (this.state.bottomControls) {
return
}
if (this.timer.hideControlsTimer) {
clearTimeout(this.timer.hideControlsTimer)
this.timer.hideControlsTimer = null
}
if (this.state.noControls) {
return
}
this.state.showControls = true
this.__checkCursor()
if (this.controlsDisplayTime !== -1 && !this.mobileMode && this.__isVideo) {
this.timer.hideControlsTimer = setTimeout(() => {
if (!this.__showingMenu()) {
this.state.showControls = false
this.timer.hideControlsTimer = null
this.__checkCursor()
}
else {
this.showControls()
}
}, this.controlsDisplayTime)
}
},
hideControls () {
if (this.state.bottomControls) {
return
}
if (this.timer.hideControlsTimer) {
clearTimeout(this.timer.hideControlsTimer)
}
if (this.controlsDisplayTime !== -1) {
this.state.showControls = false
this.__checkCursor()
}
this.timer.hideControlsTimer = null
},
toggleControls () {
if (this.state.bottomControls) {
return
}
if (this.state.showControls) {
this.hideControls()
}
else {
this.showControls()
}
},
__reset () {
if (this.timer.hideControlsTimer && !this.state.bottomControls) {
clearTimeout(this.timer.hideControlsTimer)
}
this.timer.hideControlsTimer = null
this.state.errorText = null
this.state.currentTime = 0.01
this.state.durationTime = '00:00'
this.state.remainingTime = '00:00'
this.state.displayTime = '00:00'
this.state.duration = 1
this.state.playReady = false
this.state.playing = false
this.state.loading = true
this.state.metadataLoaded = false
this.__updateTrackLanguage()
this.showControls()
},
__toggleCaptions () {
this.__showCaptions(this.state.trackLanguage)
},
__showCaptions (lang) {
if (this.$media && this.__isVideo) {
for (let index = 0; index < this.$media.textTracks.length; ++index) {
if (this.$media.textTracks[index].label === lang) {
this.$media.textTracks[index].mode = 'showing'
this.$media.textTracks[index].oncuechange = this.__cueChanged
}
else {
this.$media.textTracks[index].mode = 'hidden'
this.$media.textTracks[index].oncuechange = null
}
}
}
},
play () {
if (this.$media && this.state.playReady) {
const hasPromise = typeof this.$media.play() !== 'undefined'
if (hasPromise) {
this.$media.play()
.then(() => {
this.state.showBigPlayButton = false
this.state.playing = true
this.__mouseLeaveVideo()
})
.catch((e) => {
})
}
else {
// IE11 + EDGE support
this.$media.play()
this.state.showBigPlayButton = false
this.state.playing = true
this.__mouseLeaveVideo()
}
}
},
pause () {
if (this.$media && this.state.playReady) {
if (this.state.playing) {
this.$media.pause()
this.state.showBigPlayButton = true
this.state.playing = false
}
}
},
mute () {
this.state.muted = true
if (this.$media) {
this.$media.muted = this.state.muted === true
}
},
unmute () {
this.state.muted = false
if (this.$media) {
this.$media.muted = this.state.muted !== true
}
},
togglePlay (e) {
this.__stopAndPrevent(e)
if (this.$media && this.state.playReady) {
if (this.state.playing) {
this.$media.pause()
this.state.showBigPlayButton = true
this.state.playing = false
}
else {
const hasPromise = typeof this.$media.play() !== 'undefined'
if (hasPromise) {
this.$media.play()
.then(() => {
this.state.showBigPlayButton = false
this.state.playing = true
this.__mouseLeaveVideo()
})
.catch((e) => {
})
}
else {
// IE11 + EDGE support
this.$media.play()
this.state.showBigPlayButton = false
this.state.playing = true
this.__mouseLeaveVideo()
}
}
}
},
toggleMuted (e) {
this.__stopAndPrevent(e)
this.state.muted = !this.state.muted
if (this.$media) {
this.$media.muted = this.state.muted === true
}
},
toggleFullscreen (e) {
if (this.__isVideo) {
this.__stopAndPrevent(e)
if (this.state.inFullscreen) {
this.exitFullscreen()
}
else {
this.setFullscreen()
}
this.$emit('fullscreen', this.state.inFullscreen)
}
},
setFullscreen () {
if (this.hideFullscreenBtn === true || !this.__isVideo || this.state.inFullscreen) {
return
}
if (this.$q.fullscreen !== void 0) {
this.state.inFullscreen = true
this.$q.fullscreen.request(this.$refs.media.parentNode) // NOTE error Not capable - on iPhone Safari
document.body.classList.add('no-scroll')
this.$nextTick(() => {
this.$forceUpdate()
})
}
},
exitFullscreen () {
if (this.hideFullscreenBtn === true || !this.__isVideo || !this.state.inFullscreen) {
return
}
if (this.$q.fullscreen !== void 0) {
this.state.inFullscreen = false
this.$q.fullscreen.exit()
document.body.classList.remove('no-scroll')
this.$nextTick(() => {
this.$forceUpdate()
})
}
},
currentTime () {
if (this.$media && this.state.playReady) {
return this.$media.currentTime
}
return -1
},
setCurrentTime (seconds) {
if (this.state.playReady) {
if (this.$media && isFinite(this.$media.duration) && seconds >= 0 && seconds <= this.$media.duration) {
this.state.currentTime = this.$media.currentTime = seconds
}
}
},
setVolume (volume) {
if (volume >= 0 && volume <= 100) {
this.state.volume = volume
}
},
__stopAndPrevent (e) {
if (e) {
e.cancelable !== false && e.preventDefault()
e.stopPropagation()
}
},
__setupLang () {
const isoName = this.$q.lang.isoName || 'en-us'
let lang
try {
// lang = require(`./lang/${isoName}`)
lang = this.__loadLang(isoName)
}
catch (e) {
lang = this.__loadLang('en-us')
}
if (lang !== void 0 && lang.lang !== void 0) {
this.lang.mediaPlayer = { ...lang.mediaPlayer }
this.__updatePlaybackRates()
this.__updateTrackLanguage()
}
},
__loadLang (lang) {
lang = lang || 'en-us'
let langList = {}
if (lang) {
// detect if UMD version is installed
if (window && window.QMediaPlayer && window.QMediaPlayer.Component) {
const name = lang.replace(/-([a-z])/g, g => g[1].toUpperCase())
if (window.QMediaPlayer.lang && window.QMediaPlayer.lang[name]) {
const selectedLang = window.QMediaPlayer.lang[name]
langList = selectedLang
}
else {
/* eslint-disable-next-line no-console */
console.error(`QMediaPlayer: no language loaded called '${lang}'`)
/* eslint-disable-next-line no-console */
console.error('Be sure to load the UMD version of the language in a script tag before using with UMD')
}
}
else {
try {
const langSet = require(`@quasar/quasar-ui-qmediaplayer/src/components/lang/${lang}.js`).default
langList = langSet
}
catch (e) {
/* eslint-disable-next-line no-console */
console.error(`QMediaPlayer: cannot find language file called '${lang}'`)
}
}
}
return langList
},
__setupIcons () {
const iconSetName = this.$q.iconSet.name || 'material-icons'
let iconSet
try {
iconSet = this.__loadIconSet(iconSetName)
}
catch (e) {}
iconSet !== void 0 && iconSet.name !== void 0 && (this.iconSet.mediaPlayer = { ...iconSet.mediaPlayer })
},
__loadIconSet (set) {
let iconsList = {}
if (set) {
// detect if UMD version is installed
if (window && window.QMediaPlayer && window.QMediaPlayer.Component) {
const name = set.replace(/-([a-z])/g, g => g[1].toUpperCase())
if (window.QMediaPlayer.iconSet && window.QMediaPlayer.iconSet[name]) {
const iconsSet = window.QMediaPlayer.iconSet[name]
iconsList = iconsSet
}
else {
/* eslint-disable-next-line no-console */
console.error(`QMediaPlayer: no icon set loaded called '${set}'`)
/* eslint-disable-next-line no-console */
console.error('Be sure to load the UMD version of the icon set in a script tag before using with UMD')
}
}
else {
try {
const iconsSet = require(`@quasar/quasar-ui-qmediaplayer/src/components/icon-set/${set}.js`).default
iconsList = iconsSet
}
catch (e) {
/* eslint-disable-next-line no-console */
console.error(`QMediaPlayer: cannot find icon set file called '${set}'`)
}
}
}
return iconsList
},
__init () {
this.$media = this.$refs.media
this.state.bottomControls = this.bottomControls
this.state.noControls = this.noControls
if (this.nativeControls === true) {
this.state.noControls = true
}
// set default track language
this.__updateTrackLanguage()
this.__updateSources()
this.__updateTracks()
// set big play button
this.__updateBigPlayButton()
// set the volume
this.__updateVolume()
// set muted
this.__updateMuted()
// set playback rates
this.__updatePlaybackRates()
// set playback rate default
this.__updatePlaybackRate()
// does user want cors?
this.crossOrigin && this.$media && this.$media.setAttribute('crossorigin', this.crossOrigin)
// make sure "controls" is turned off
this.$media && (this.$media.controls = false)
// set up event listeners on video
this.__addMediaEventListeners()
this.__addSourceEventListeners()
this.__toggleCaptions()
},
__addMediaEventListeners () {
if (this.$media) {
this.allEvents.forEach((event) => {
this.$media.addEventListener(event, this.__mediaEventHandler)
})
}
},
__removeMediaEventListeners () {
if (this.$media) {
this.allEvents.forEach((event) => {
this.$media.removeEventListener(event, this.__mediaEventHandler)
})
}
},
__addSourceEventListeners () {
if (this.$media) {
const sources = this.$media.querySelectorAll('source')
for (let index = 0; index < sources.length; ++index) {
sources[index].addEventListener('error', this.__sourceEventHandler)
}
}
},
__removeSourceEventListeners () {
if (this.$media) {
const sources = this.$media.querySelectorAll('source')
for (let index = 0; index < sources.length; ++index) {
sources[index].removeEventListener('error', this.__sourceEventHandler)
}
}
},
__sourceEventHandler (event) {
const NETWORK_NO_SOURCE = 3
if (this.$media && this.$media.networkState === NETWORK_NO_SOURCE) {
this.state.errorText = this.__isVideo ? this.lang.mediaPlayer.noLoadVideo : this.lang.mediaPlayer.noLoadAudio
}
// eslint-disable-next-line vue/custom-event-name-casing
this.$emit('networkState', event)
},
__mediaEventHandler (event) {
if (event.type === 'abort') {
this.$emit('abort')
}
else if (event.type === 'canplay') {
this.state.playReady = true
this.state.displayTime = timeParse(this.$media.currentTime)
this.__mouseEnterVideo()
this.$emit('ready')
}
else if (event.type === 'canplaythrough') {
// console.log('canplaythrough')
this.$emit('canplaythrough')
}
else if (event.type === 'durationchange') {
if (isFinite(this.$media.duration)) {
this.state.duration = this.$media.duration
this.state.durationTime = timeParse(this.$media.duration)
this.$emit('duration', this.$media.duration)
}
}
else if (event.type === 'emptied') {
this.$emit('emptied')
}
else if (event.type === 'ended') {
this.state.playing = false
this.$emit('ended')
}
else if (event.type === 'error') {
const error = this.$media.error
this.$emit('error', error)
}
else if (event.type === 'interruptbegin') {
// console.log('interruptbegin')
}
else if (event.type === 'interruptend') {
// console.log('interruptend')
}
else if (event.type === 'loadeddata') {
this.state.loading = false
this.$emit('loadeddata')
}
else if (event.type === 'loadedmetadata') {
// tracks can only be programatically added after 'loadedmetadata' event
this.state.metadataLoaded = true
this.__updateTracks()
// set default track language
this.__updateTrackLanguage()
this.__toggleCaptions()
this.$emit('loadedmetadata')
}
else if (event.type === 'stalled') {
this.$emit('stalled')
}
else if (event.type === 'suspend') {
this.$emit('suspend')
}
else if (event.type === 'loadstart') {
this.$emit('loadstart')
}
else if (event.type === 'pause') {
this.state.playing = false
this.$emit('paused')
}
else if (event.type === 'play') {
this.$emit('play')
}
else if (event.type === 'playing') {
this.state.playing = true
this.$emit('playing')
}
else if (event.type === 'progress') {
//
}
else if (event.type === 'ratechange') {
//
}
else if (event.type === 'seeked') {
//
}
else if (event.type === 'timeupdate') {
this.state.currentTime = this.$media.currentTime
this.$emit('timeupdate', this.$media.currentTime, this.state.remainingTime)
}
else if (event.type === 'volumechange') {
//
}
else if (event.type === 'waiting') {
this.$emit('waiting')
}
},
// for future functionality
__cueChanged (data) {
},
__checkCursor () {
if (this.state.inFullscreen && this.state.playing && !this.state.showControls) {
this.$el.classList.remove('cursor-inherit')
this.$el.classList.add('cursor-none')
}
else {
this.$el.classList.remove('cursor-none')
this.$el.classList.add('cursor-inherit')
}
},
__adjustMenu () {
const qmenu = this.$refs.menu
if (qmenu) {
setTimeout(() => {
qmenu.updatePosition()
}, 350)
}
},
__videoClick (e) {
this.__stopAndPrevent(e)
if (this.mobileMode !== true) {
this.togglePlay()
}
this.toggleControls()
},
__bigButtonClick (e) {
this.__stopAndPrevent(e)
if (this.mobileMode) {
this.hideControls()
}
this.togglePlay()
},
__settingsMenuShowing (val) {
this.settingsMenuVisible = val
},
__mouseEnterVideo (e) {
if (!this.bottomControls && !this.mobileMode && !this.__isAudio) {
this.showControls()
}
},
__mouseLeaveVideo (e) {
if (!this.bottomControls && !this.mobileMode && !this.__isAudio) {
this.hideControls()
}
},
__mouseMoveAction (e) {
if (!this.bottomControls && !this.mobileMode && !this.__isAudio) {
this.__showControlsIfValid(e)
}
},
__showControlsIfValid (e) {
if (this.__showingMenu()) {
this.showControls()
return true
}
const x = getMousePosition(e, 'x')
const y = getMousePosition(e, 'y')
const pos = this.$el.getBoundingClientRect()
if (!pos) return false
if (x > pos.left && x < pos.left + pos.width) {
if (y > pos.top + pos.height - (this.dense ? 40 : 80) && y < pos.top + pos.height) {
this.showControls()
return true
}
}
return false
},
__videoCurrentTimeChanged (val) {
this.showControls()
if (this.$media && this.$media.duration && val && val > 0 && val <= this.state.duration) {
if (this.$media.currentTime !== val) {
this.state.currentTime = this.$media.currentTime = val
}
}
},
__volumePercentChanged (val) {
this.showControls()
this.state.volume = val
},
__trackLanguageChanged (language) {
if (this.state.trackLanguage !== language) {
this.state.trackLanguage = language
}
},
__playbackRateChanged (rate) {
if (this.state.playbackRate !== rate) {
this.state.playbackRate = rate
}
},
__showingMenu () {
return this.settingsMenuVisible
},
__updateBigPlayButton () {
if (this.state.showBigPlayButton !== this.showBigPlayButton) {
this.state.showBigPlayButton = this.showBigPlayButton
}
},
__updateVolume () {
if (this.state.volume !== this.volume) {
this.state.volume = this.volume
}
},
__updateMuted () {
if (this.state.muted !== this.muted) {
this.state.muted = this.muted
if (this.$media) {
this.$media.muted = this.state.muted
}
}
},
__updateTrackLanguage () {
if (this.state.trackLanguage !== this.trackLanguage || this.lang.mediaPlayer.trackLanguageOff) {
this.state.trackLanguage = this.trackLanguage || this.lang.mediaPlayer.trackLanguageOff
}
},
__updatePlaybackRates () {
if (this.playbackRates && this.playbackRates.length > 0) {
this.state.playbackRates = [...this.playbackRates]
}
else {
this.state.playbackRates.splice(0, this.state.playbackRates.length)
this.state.playbackRates.push({ label: this.lang.mediaPlayer.ratePoint5, value: 0.5 })
this.state.playbackRates.push({ label: this.lang.mediaPlayer.rateNormal, value: 1 })
this.state.playbackRates.push({ label: this.lang.mediaPlayer.rate1Point5, value: 1.5 })
this.state.playbackRates.push({ label: this.lang.mediaPlayer.rate2, value: 2 })
}
this.state.trackLanguage = this.lang.mediaPlayer.trackLanguageOff
},
__updatePlaybackRate () {
if (this.state.playbackRate !== this.playbackRate) {
this.state.playbackRate = this.playbackRate
}
},
__updateSources () {
this.__removeSources()
this.__addSources()
},
__removeSources () {
if (this.$media) {
this.__removeSourceEventListeners()
// player must not be running
this.$media.pause()
this.$media.src = ''
if (this.$media.currentTime) {
// otherwise IE11 has exception error
this.$media.currentTime = 0
}
const childNodes = this.$media.childNodes
for (let index = childNodes.length - 1; index >= 0; --index) {
if (childNodes[index].tagName === 'SOURCE') {
this.$media.removeChild(childNodes[index])
}
}
this.$media.load()
}
},
__addSources () {
if (this.$media) {
let loaded = false
if (this.source && this.source.length > 0) {
this.$media.src = this.source
loaded = true
}
else {
if (this.sources.length > 0) {
this.sources.forEach((source) => {
const s = document.createElement('SOURCE')
s.src = source.src ? source.src : ''
s.type = source.type ? source.type : ''
this.$media.appendChild(s)
if (!loaded && source.src) {
this.$media.src = source.src
loaded = true
}
})
}
}
this.__reset()
this.__addSourceEventListeners()
this.$media.load()
}
},
__updateTracks () {
this.__removeTracks()
this.__addTracks()
},
__removeTracks () {
if (this.$media) {
const childNodes = this.$media.childNodes
for (let index = childNodes.length - 1; index >= 0; --index) {
if (childNodes[index].tagName === 'TRACK') {
this.$media.removeChild(childNodes[index])
}
}
}
},
__addTracks () {
// only add tracks to video
if (this.__isVideo && this.$media) {
this.tracks.forEach((track) => {
const t = document.createElement('TRACK')
t.kind = track.kind ? track.kind : ''
t.label = track.label ? track.label : ''
t.src = track.src ? track.src : ''
t.srclang = track.srclang ? track.srclang : ''
this.$media.appendChild(t)
})
this.$nextTick(() => {
this.__toggleCaptions()
})
}
},
__updatePoster () {
if (this.$media) {
this.$media.poster = this.poster
}
},
__bigButtonPositionHeight () {
if (this.$refs.media) {
// top of video
return this.$refs.media.clientTop +
// height of video / 2
(this.$refs.media.clientHeight / 2).toFixed(2) -
// big button is 48px -- so 1/2 of that
24 + 'px'
}
return '50%'
},
__renderVideo (h) {
const slot = this.$slots.oldbrowser
const attrs = {
poster: this.poster,
preload: this.preload,
playsinline: this.playsinline === true,
loop: this.loop === true,
autoplay: this.autoplay === true,
muted: this.mute === true,
width: this.contentWidth || undefined,
height: this.contentHeight || undefined
}
this.$nextTick(() => {
if (this.$refs.media && this.nativeControls === true) {
this.$refs.media.controls = true
}
})
return h('video', {
ref: 'media',
staticClass: this.__renderVideoClasses,
class: this.contentClass,
style: {
...this.__contentStyle
},
attrs
}, [
this.__isVideo && (slot || h('p', this.lang.mediaPlayer.oldBrowserVideo))
])
},
__renderAudio (h) {
const slot = this.$slots.oldbrowser
const attrs = {
preload: this.preload,
playsinline: this.playsinline === true,
loop: this.loop === true,
autoplay: this.autoplay === true,
muted: this.mute === true,
width: this.contentWidth || undefined,
height: this.contentHeight || undefined
}
this.$nextTick(() => {
if (this.$refs.media && this.nativeControls === true) {
this.$refs.media.controls = true
}
})
// This is on purpose (not using audio tag).
// The video tag can also play audio and works better if dynamically
// switching between video and audio on the same component.
// That being said, if audio is truly needed, use the 'nop-video'
// property to force the <audio> tag.
return h(this.noVideo === true ? 'audio' : 'video', {
ref: 'media',
staticClass: 'q-media--player',
class: this.contentClass,
style: this.contentStyle,
attrs
}, [
this.__isAudio && (slot || h('p', this.lang.mediaPlayer.oldBrowserAudio))
])
},
__renderSources (h) {
return this.sources.map((source) => {
return h('source', {
attrs: {
key: source.src + ':' + source.type,
src: source.src,
type: source.type
}
})
})
},
__renderTracks (h) {
return this.tracks.map((track) => {
return h('track', {
attrs: {
key: track.src + ':' + track.kind,
src: track.src,
kind: track.kind,
label: track.label,
srclang: track.srclang
}
})
})
},
__renderOverlayWindow (h) {
const slot = this.$slots.overlay
if (slot) {
return h('div', {
staticClass: 'q-media__overlay-window fit'
}, slot)
}
},
__renderErrorWindow (h) {
const slot = this.$slots.errorWindow
return h('div', {
staticClass: 'q-media__error-window'
}, [
slot || h('div', this.state.errorText)
])
},
__renderPlayButton (h) {
if (this.hidePlayBtn === true) return
const slot = this.$slots.play
return slot || h(QBtn, {
staticClass: 'q-media__controls--button',
props: {
icon: this.state.playing ? this.iconSet.mediaPlayer.pause : this.iconSet.mediaPlayer.play,
textColor: this.color,
size: '1rem',
disable: !this.state.playReady,
flat: true,
padding: '4px'
},
on: {
click: this.togglePlay
}
}, [
this.showTooltips && this.state.playing && h(QTooltip, this.lang.mediaPlayer.pause),
this.showTooltips && !this.state.playing && this.state.playReady && h(QTooltip, this.lang.mediaPlayer.play)
])
},
__renderVideoControls (h) {
const slot = this.$slots.controls
if (slot) {
// we need to know the controls height for fullscreen, stop propagation to video component
return h('div', {
ref: 'controls',
staticClass: 'q-media__controls',
class: this.__videoControlsClasses,
on: {
click: this.__stopAndPrevent
}
},
slot
)
}
return h('div', {
ref: 'controls',
staticClass: 'q-media__controls',
class: this.__videoControlsClasses,
on: {
click: this.__stopAndPrevent
}
}, [
// dense
this.dense && h('div', {
staticClass: 'q-media__controls--row row col content-start items-center'
}, [
h('div', [
this.__renderPlayButton(h),
this.showTooltips && !this.state.playReady && h(QTooltip, this.lang.mediaPlayer.waitingVideo)
]),
this.__renderVolumeButton(h),
this.__renderVolumeSlider(h),
this.__renderDisplayTime(h),
this.__renderCurrentTimeSlider(h),
this.__renderDurationTime(h),
this.__renderSettingsButton(h),
this.$q.fullscreen !== void 0 && this.hideFullscreenBtn !== true && this.__renderFullscreenButton(h)
]),
// sparse
!this.dense && h('div', {
staticClass: 'q-media__controls--row row col items-center justify-between'
}, [
this.__renderDisplayTime(h),
this.__renderCurrentTimeSlider(h),
this.__renderDurationTime(h)
]),
!this.dense && h('div', {
staticClass: 'q-media__controls--row row col content-start items-center'
}, [
h('div', {
staticClass: 'row col'
}, [
h('div', [
this.__renderPlayButton(h),
this.showTooltips && !this.state.playReady && h(QTooltip, this.lang.mediaPlayer.waitingVideo)
]),
this.__renderVolumeButton(h),
this.__renderVolumeSlider(h)
]),
h('div', [
this.__renderSettingsButton(h),
this.$q.fullscreen !== void 0 && this.hideFullscreenBtn !== true && this.__renderFullscreenButton(h)
])
])
])
},
__renderAudioControls (h) {
const slot = this.$slots.controls
return slot || h('div', {
ref: 'controls',
staticClass: 'q-media__controls',
class: this.__audioControlsClasses
}, [
this.dense && h('div', {
staticClass: 'q-media__controls--row row col content-start items-center'
}, [
// dense
h('div', [
this.__renderPlayButton(h),
this.showTooltips && !this.state.playReady && h(QTooltip, this.lang.mediaPlayer.waitingAudio)
]),
this.__renderVolumeButton(h),
this.__renderVolumeSlider(h),
this.__renderDisplayTime(h),
this.__renderCurrentTimeSlider(h),
this.__renderDurationTime(h)
]),
// sparse
!this.dense && h('div', {
staticClass: 'q-media__controls--row row col items-center justify-between'
}, [
this.__renderDisplayTime(h),
this.__renderCurrentTimeSlider(h),
this.__renderDurationTime(h)
]),
!this.dense && h('div', {
staticClass: 'q-media__controls--row row col content-start items-center'
}, [
h('div', [
this.__renderPlayButton(h),
this.showTooltips && !this.state.playReady && h(QTooltip, this.lang.mediaPlayer.waitingAudio)
]),
this.__renderVolumeButton(h),
this.__renderVolumeSlider(h)
])
])
},
__renderVolumeButton (h) {
if (this.hideVolumeBtn === true) {
return
}
const slot = this.$slots.volume
return slot || h(QBtn, {
staticClass: 'q-media__controls--button',
props: {
icon: this.__volumeIcon,
textColor: this.color,
size: '1rem',
disable: !this.state.playReady,
flat: true,
padding: '4px'
},
on: {
click: this.toggleMuted
}
}, [
this.showTooltips && !this.state.muted && h(QTooltip, this.lang.mediaPlayer.mute),
this.showTooltips && this.state.muted && h(QTooltip, this.lang.mediaPlayer.unmute)
])
},
__renderVolumeSlider (h) {
if (this.hideVolumeSlider === true || this.hideVolumeBtn === true) {
return
}
const slot = this.$slots.volumeSlider
return slot || h(QSlider, {
staticClass: 'col',
style: {
width: '20%',
margin: '0 0.5rem',
minWidth: this.dense ? '20px' : '50px',
maxWidth: this.dense ? '50px' : '200px'
},
props: {
value: this.state.volume,
color: this.color,
dark: this.dark,
min: 0,
max: 100,
disable: !this.state.playReady || this.state.muted
},
on: {
input: this.__volumePercentChanged
}
})
},
__renderSettingsButton (h) {
if (this.hideSettingsBtn === true) {
return
}
const slot = this.$slots.settings
return slot || h(QBtn, {
staticClass: 'q-media__controls--button',
props: {
icon: this.iconSet.mediaPlayer.settings,
textColor: this.color,
size: '1rem',
disable: !this.state.playReady,
flat: true,
padding: '4px'
}
}, [
this.showTooltips && !this.settingsMenuVisible && h(QTooltip, this.lang.mediaPlayer.settings),
this.__renderSettingsMenu(h)
])
},
__renderFullscreenButton (h) {
const slot = this.$slots.fullscreen
return slot || h(QBtn, {
staticClass: 'q-media__controls--button',
props: {
icon: this.state.inFullscreen ? this.iconSet.mediaPlayer.fullscreenExit : this.iconSet.mediaPlayer.fullscreen,
textColor: this.color,
size: '1rem',
disable: !this.state.playReady,
flat: true,
padding: '4px'
},
on: {
click: this.toggleFullscreen
}
}, [
this.showTooltips && h(QTooltip, this.lang.mediaPlayer.toggleFullscreen)
])
},
__renderLoader (h) {
if (this.spinnerSize === void 0) {
if (this.__isVideo) this.state.spinnerSize = '3em'
else this.state.spinnerSize = '1.5em'
}
else {
this.state.spinnerSize = this.spinnerSize
}
const slot = this.$slots.spinner
return slot || h('div', {
staticClass: this.__isVideo ? 'q-media__loading--video' : 'q-media__loading--audio'
}, [
h(QSpinner, {
props: {
size: this.state.spinnerSize,
color: this.color
}
})
])
},
__renderBigPlayButton (h) {
const slot = this.$slots.bigPlayButton
return slot || h('div', this.setBorderColor(this.bigPlayButtonColor, {
staticClass: this.state.bottomControls === true ? 'q-media--big-button q-media--big-button-bottom-controls' : 'q-media--big-button',
style: {
top: this.__bigButtonPositionHeight()
}
}), [
h(QIcon, this.setTextColor(this.bigPlayButtonColor, {
props: {
name: this.iconSet.mediaPlayer.bigPlayButton
},
staticClass: 'q-media--big-button-icon',
on: {
click: this.__bigButtonClick
},
directives: [
{
name: 'ripple',
value: true
}
]
}))
])
},
__renderCurrentTimeSlider (h) {
const slot = this.$slots.positionSlider
return slot || h(QSlider, {
staticClass: 'col',
style: {
margin: '0 0.5rem'
},
props: {
value: this.state.currentTime,
color: this.color,
dark: this.dark,
min: 0,
max: this.state.duration ? this.state.duration : 1,
disable: !this.state.playReady || this.disabledSeek
},
on: {
input: this.__videoCurrentTimeChanged
}
})
},
__renderDisplayTime (h) {
const slot = this.$slots.displayTime
return slot || h('span', {
staticClass: 'q-media__controls--video-time-text' + ' text-' + this.color
}, this.state.displayTime)
},
__renderDurationTime (h) {
if (this.$media === void 0) return
const slot = this.$slots.durationTime
const isInfinity = this.$media !== void 0 && !isFinite(this.$media.duration)
return slot || h('span', {
staticClass: 'q-media__controls--video-time-text' + ' text-' + this.color,
style: {
width: isInfinity ? '30px' : 'auto'
}
}, [
this.$media && isInfinity !== true && this.state.durationTime,
this.$media && isInfinity === true && this.__renderInfinitySvg(h)
])
},
__renderInfinitySvg (h) {
return h('svg', {
attrs: {
height: '16',
viewbox: '0 0 16 16'
}
}, [
h('path', {
attrs: {
fill: 'none',
stroke: '#ffffff',
strokeWidth: '2',
d: 'M8,8 C16,0 16,16 8,8 C0,0 0,16 8,8z'
}
})
])
},
__renderSettingsMenu (h) {
const slot = this.$slots.settingsMenu
return h(QMenu, {
ref: 'menu',
props: {
anchor: 'top right',
self: 'bottom right'
},
on: {
show: () => {
this.__settingsMenuShowing(true)
},
hide: () => {
this.__settingsMenuShowing(false)
}
}
}, [
slot || h('div', [
this.state.playbackRates.length && h(QExpansionItem, {
props: {
group: 'settings-menu',
expandSeparator: true,
icon: this.iconSet.mediaPlayer.speed,
label: this.lang.mediaPlayer.speed,
caption: this.__settingsPlaybackCaption
},
on: {
show: this.__adjustMenu,
hide: this.__adjustMenu
}
}, [
h(QList, {
props: {
highlight: true
}
}, [
this.state.playbackRates.map((rate) => {
return h(QItem, {
attrs: {
key: rate.value
},
props: {
clickable: true
},
on: {
click: (e) => {
this.__stopAndPrevent(e)
this.__playbackRateChanged(rate.value)
}
},
directives: [
{
name: 'ripple',
value: true
},
{
name: 'close-popup',
value: true
}
]
}, [
h(QItemSection, {
props: {
avatar: true
}
}, [
rate.value === this.state.playbackRate && h(QIcon, {
props: {
name: this.iconSet.mediaPlayer.selected
}
})
]),
h(QItemSection, rate.label)
])
})
])
]),
// first item is 'Off' and doesn't count unless more are added
this.__selectTracksLanguageList.length > 1 && h(QExpansionItem, {
props: {
group: 'settings-menu',
expandSeparator: true,
icon: this.iconSet.mediaPlayer.language,
label: this.lang.mediaPlayer.language,
caption: this.state.trackLanguage
},
on: {
show: this.__adjustMenu,
hide: this.__adjustMenu
}
}, [
h(QList, {
props: {
highlight: true
}
}, [
this.__selectTracksLanguageList.map((language) => {
return h(QItem, {
attrs: {
key: language.value
},
props: {
clickable: true
},
on: {
click: (e) => {
this.__stopAndPrevent(e)
this.__trackLanguageChanged(language.value)
}
},
directives: [
{
name: 'ripple',
value: true
},
{
name: 'close-popup',
value: true
}
]
}, [
h(QItemSection, {
props: {
avatar: true
}
}, [
language.value === this.state.trackLanguage && h(QIcon, {
props: {
name: this.iconSet.mediaPlayer.selected
}
})
]),
h(QItemSection, language.label)
])
})
])
])
])
])
}
},
render (h) {
return h('div', {
staticClass: 'q-media bg-' + this.backgroundColor,
class: this.__classes,
style: {
borderRadius: !this.state.inFullscreen ? this.radius : 0,
height: this.__isVideo ? 'auto' : this.dense ? '40px' : '80px'
},
on: {
mousemove: this.__mouseMoveAction,
mouseenter: this.__mouseEnterVideo,
mouseleave: this.__mouseLeaveVideo,
click: this.__videoClick
}
}, this.canRender === true
? [
this.__isVideo && this.__renderVideo(h),
this.__isAudio && this.__renderAudio(h),
this.__renderOverlayWindow(h),
this.state.errorText && this.__renderErrorWindow(h),
this.__isVideo && !this.state.noControls && !this.state.errorText && this.__renderVideoControls(h),
this.__isAudio && !this.state.noControls && !this.state.errorText && this.__renderAudioControls(h),
this.showSpinner && this.state.loading && !this.state.playReady && !this.state.errorText && this.__renderLoader(h),
this.__isVideo && this.showBigPlayButton && this.state.playReady && !this.state.playing && this.__renderBigPlayButton(h)
]
: void 0)
}
}
|
import React, { Component } from "react";
import { Nav, NavItem, Button } from "reactstrap";
import { Blockie, EthAddress } from "rimble-ui";
class Header extends Component {
constructor(props, context) {
super(props);
const { accounts } = props.drizzleState;
this.state = {
account: accounts[0],
hasBalance: false,
balance: 0
};
}
componentDidMount() {
window.ethereum.on('accountsChanged', function (accounts) {
window.location.reload();
})
this.checkOwner();
}
async checkOwner() {
const { MLModel } = this.props.drizzle.contracts;
const owner = await MLModel.methods.owner().call();
console.log("owner", owner);
var isOwner = owner === this.state.account ? true : false;
this.setState({ isOwner });
}
async cashOut(){
const { MLModel } = this.props.drizzle.contracts;
console.log("cash out")
await MLModel.methods.cashOut.cacheSend(
{
from: this.state.account,
}
);
}
render() {
const {isOwner, account} = this.state;
return (
<Nav>
<NavItem >
<Blockie opts={{
seed: account,
color: "#dfa",
bgcolor: "#a71",
size: 10,
scale: 5,
spotcolor: "#000"
}}/>
</NavItem>
<NavItem >
<EthAddress address={account} />
</NavItem>
{isOwner && (
<NavItem >
<Button mr={3} mt={3} mb={3} height={"auto"} onClick= {()=> this.cashOut()}>
Cash Out
</Button>
</NavItem>
)}
</Nav>
);
}
}
export default Header; |
import React from 'react';
import { connect } from 'dva';
import { Table, Popconfirm, Button } from 'antd';
import HomePlayControlBar from '../../components/HomePlayControlBar/HomePlayControlBar';
import HomePageToolBar from '../../components/HomePageToolBar/HomePageToolBar';
import HomePageSliderMenu from '../../components/HomePageSliderMenu/HomePageSliderMenu';
import HomePageRecommend from '../../components/HomePageRecommend/HomePageRecommend';
import style from './HomePage.less';
class HomePage extends React.Component {
constructor(props) {
super(props);
this.state = {
openSliderMenu: false,
}
}
handleListButtonClick() {
this.setState({
openSliderMenu: true
});
}
closeSliderMenu() {
this.setState({
openSliderMenu: false
});
}
render() {
return(
<div className={style.container}>
<HomePageSliderMenu open={this.state.openSliderMenu} closeSliderMenu={()=>this.closeSliderMenu()}/>
<HomePageToolBar className={style.homePageToolBar} open={this.state.openSliderMenu} handleListButtonClick={()=>this.handleListButtonClick()}/>
<HomePageRecommend className={style.homePageRecommend}/>
<HomePlayControlBar className={style.homePlayControlBar}/>
</div>
)
}
}
HomePage.propTypes = {
};
export default connect()(HomePage);
|
import React, {Component, Fragment} from 'react'
import "./Person.css"
class Person extends Component{
constructor(props){
super(props)
this.state = {
dx:0,
curFrame:0
}
this.getImage = this.getImage.bind(this);
this.nextFrame = this.nextFrame.bind(this);
setInterval(this.nextFrame, 1000/this.props.fps);
}
nextFrame(){
this.setState((prev, props) => ({
curFrame: (prev.curFrame + 1) % 2,
dx: 180 * ((prev.curFrame + 1) % 2),
}));
}
getImage(){
const {dx} = this.state;
return {
position:'absolute',
left:0,
cursor :'pointer',
top:0,
transform: "translate( -"+ dx +"px,0px )"
}
}
soundHandler(){
let myAudio = new Audio(this.props.clkSound);
myAudio.play();
}
render(){
const person = {
display:'flex',
position:'relative',
overflow:'hidden',
height:180 + 'px',
width:180 + 'px',
justifyContent:'center',
alignItems:'center',
zIndex:1
}
return (
<div className={'animated ' + this.props.anim + ' infinite'} onClick={this.soundHandler.bind(this)} style={person}>
<img src={this.props.img} style={this.getImage()} alt="Responsive person"/>
</div>
)
}
}
export default Person |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.