text stringlengths 7 3.69M |
|---|
module.exports = (req, res) => {
return res.render('main/index', {
title: 'Admin Ecommerce',
layout: 'layouts/base',
})
} |
Ext.define('Crossings.news.model.NewsModel',{
getAllNews: function(params, callback) {
setTimeout(function() {
callback({test: 'all news', name: '<b>Tester</b>', age: true, time: new Date()})
}, 1)
}
}) |
/*
In this kata, your goal is to write a function which will reverse the vowels in a string.
Any characters which are not vowels should remain in their original position.
Here are some examples:
reverseVowels("Hello!"); // "Holle!"
reverseVowels("Tomatoes"); // "Temotaos"
reverseVowels("Reverse Vowels In A String") // "RivArsI Vewols en e Streng"
For simplicity, you can treat the letter y as a consonant, not a vowel.
Good luck!
*/
function reverseVowels(str) {
let result = "";
let stack = [];
for (let i = 0; i < str.length; i++) {
let letter = str[i];
if (isVowel(letter) === true) stack.push(letter);
}
for (let i = 0; i < str.length; i++) {
let letter = str[i];
if (isVowel(letter) === true) {
result += stack.pop();
}
else {
result += letter;
}
}
return result;
}
function isVowel(letter) {
switch(letter.toLowerCase()) {
case "a":
return true;
case "e":
return true;
case "i":
return true;
case "o":
return true;
case "u":
return true;
default:
return false;
}
}
|
import React, { Component, PropTypes } from 'react';
import { View, Text, ListView, ActivityIndicator, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import { fetchPostList } from '../../modules/Post';
import { showProgress, showBackgroundProgress } from '../../modules/Progress';
import PostItem from '../Item/PostItem';
const styles = StyleSheet.create({
container: {
flex: 1,
},
list: {
flex: 1,
},
});
class PostList extends Component {
constructor({ posts }) {
super();
this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = { page: 0 };
this.paginate = this.paginate.bind(this);
this.renderHeader = this.renderHeader.bind(this);
this.onClickItem = this.onClickItem.bind(this);
}
componentWillMount() {
const {
posts,
group,
url,
fetchPostList,
showProgress,
showBackgroundProgress,
} = this.props;
posts.length < 20 ? showProgress() : showBackgroundProgress();
fetchPostList(url, group);
}
componentWillReceiveProps(nextProps) {
const {
posts,
group,
url,
fetchPostList,
showProgress,
showBackgroundProgress,
} = this.props;
if (group != nextProps.group) {
posts.length < 20 ? showProgress() : showBackgroundProgress();
fetchPostList(nextProps.url, nextProps.group);
}
}
onClickItem(url) {
this.props.navigator.push({ name: 'view', passProps: { url } })
}
paginate() {
const { url, group } = this.props
const { page } = this.state;
this.props.fetchPostList(`${url}&page=${page + 1}`, group);
this.setState({ page: page + 1 });
}
renderHeader() {
const { progress } = this.props;
return (
<View>
{ progress && <ActivityIndicator animating={ true } style={ { padding: 8 } } size="large" color="#fa5d63"/> }
</View>
);
}
render() {
const { progress, posts, group } = this.props;
const { page } = this.state;
const dataSource = this.ds.cloneWithRows(posts.filter(p => p.menu === group).slice(0, 20 * (page + 1)));
return (
<View style={ styles.container }>
<ListView
style={ styles.list }
pageSize={ 10 }
initialListSize={ 20 }
dataSource={ dataSource }
renderRow={ (data) => <PostItem { ...data } onClick={ this.onClickItem } /> }
renderHeader={ () => this.renderHeader() }
renderFooter={ () => <View>{ !progress && <ActivityIndicator animating={ true } style={ { padding: 8 } } size="large" color="#fa5d63"/> }</View> }
onEndReached={ () => this.paginate() }
onEndReachedThreshold={ 1000 }
enableEmptySections={ true }
removeClippedSubviews={ false }
/>
</View>
);
}
}
export default connect(
({ Post, Progress }) => ({
posts: Post.posts,
progress: Progress.backgroundShowing || Progress.showing,
}),
{ fetchPostList, showProgress, showBackgroundProgress },
)(PostList);
|
class InformationsWHR {
constructor() {
this.inputsRadio = [...document.getElementsByName('gender')]
this.inputWaist = document.querySelector('input.waistwhr');
this.inputHips = document.querySelector('input.hipswhr');
this.btnStartWHR = document.querySelector('button.startwhr');
this.waist = this.inputWaist.value;
this.hips = this.inputHips.value;
if (this.inputWaist.value === "" && this.inputHips.value !== "") {
alert("Nie podano wartości obwodu talii")
}
if (this.inputHips.value === "" && this.inputWaist.value !== "") {
alert("Nie podanao wartości obwodu bioder")
}
if (this.inputHips.value === "" && this.inputWaist.value === "") {
alert("Nie podanao wartości obwodu talii i obwodu bioder")
}
if (this.inputHips.value === 0 || this.inputWaist.value === 0) {
alert("Podana wartość jest za niska")
}
}
} |
import React, { Component } from 'react';
import axios from 'axios';
import {
BrowserRouter,
Route,
Redirect,
Switch
} from 'react-router-dom';
// import { AuthConsumer } from 'react-check-auth';
// import { AuthProvider } from "react-check-auth";
import Menu from './components/Menu';
import Homepage from './components/Homepage';
import Portfolio from './components/Portfolio';
import PortfolioItemAdd from './components/PortfolioItemAdd';
import Contact from './components/Contact';
import About from './components/About';
import Login from './components/Login';
import NotFound from './components/NotFound';
import PrivateRoute from './components/PrivateRoute';
import './css/resume.css';
import './css/style.css';
class App extends Component {
constructor() {
super()
this.state = {
username: "",
password: "",
authed: false,
component: <PortfolioItemAdd />,
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleLoginChange = this.handleLoginChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
handleLoginChange = e =>
this.setState({
username: e.target.value
})
handlePasswordChange = e =>
this.setState({
password: e.target.value
})
handleLogout = (e) => {
e.preventDefault;
var token = window.localStorage.getItem('HASURA_AUTH_TOKEN');
alert('clicked');
axios.post(`https://auth.deterioration37.hasura-app.io/v1/user/logout`, {
headers: {
"Content-Type": "application/json",
"Authorization": 'Bearer ' + window.localStorage.getItem('HASURA_AUTH_TOKEN') },
body: ''
}).then(data => {
console.log(data);
window.localStorage.removeItem('HASURA_AUTH_TOKEN');
window.localStorage.removeItem('currentUser');
}).catch(error => {
console.log('Request Failed:' + error);
})
}
handleSubmit = e => {
alert('prevented');
e.preventDefault();
var url = `https://auth.deterioration37.hasura-app.io/v1/login`;
var authToken;
axios.post(url, {
"provider": "username",
"data": {
"username": this.state.username,
"password": this.state.password
}
}
).then((data) => {
this.setState({
authed: true
}, function(){
console.log(this.state.currUser);
})
authToken = data.data.auth_token;
window.localStorage.setItem('HASURA_AUTH_TOKEN', authToken);
window.localStorage.setItem('currentUser', JSON.stringify(data.data));
}).catch(function (error) {
console.log(error);
})
}
render(){
let user = window.localStorage.getItem('currentUser') || false;
return(
<BrowserRouter>
<div className="App" id="page-top">
{ React.version }
<div className="container-fluid p-0">
<Switch>
<Route exact path="/" component={Homepage} />
<Route exact path="/portfolio" render={() => <Portfolio />}/>
<Route exact path="/about" render={() => <About />}/>
<Route exact path="/contact" render={() => <Contact />}/>
<PrivateRoute authed={user} path='/portfolioitemadd' component={PortfolioItemAdd} />
<Route exact path="/login" render={() =>
user
?
<Redirect to={{pathname: '/portfolioitemadd'}} />
:
<Login
handleLoginChange={this.handleLoginChange}
handlePasswordChange={this.handlePasswordChange}
handleSubmit={this.handleSubmit}/>}
/>
/>
<Route component={ NotFound }/>
</Switch>
</div>
<Menu userLogOut={this.handleLogout}/>
</div>
</BrowserRouter>
)
}
}
export default App;
|
import { DATA_LOADING, GET_WEATHER_DATA } from '../Constants/constants';
const intState = {
city: '',
country: '',
temp: '',
max_temp: '',
min_temp: '',
day: '',
date: '',
time: '',
loading: false
};
export const weather = (state = intState, action) => {
switch (action.type) {
case GET_WEATHER_DATA:
const getDay = () => {
let res = new Date();
let result = `${res.toLocaleString('default', { weekday: 'short' })}`;
return result;
};
const getDate = () => {
let res = new Date();
let result = `${res.getDate()} ${res.toLocaleString('default', { month: 'short' })}`;
return result;
};
const getTime = () => {
let res = new Date();
let result = `${res.toLocaleString('default', { timeStyle: 'short' })}`;
return result;
};
const weatherType = () => {
return action.payload.weather[0].main;
}
return {
...state,
city: action.payload.name,
country: action.payload.sys.country,
temp: parseFloat(action.payload.main.temp - 273.15).toFixed(2),
max_temp: parseFloat(action.payload.main.temp_max - 273.15).toFixed(2),
min_temp: parseFloat(action.payload.main.temp_min - 273.15).toFixed(2),
day: getDay(),
date: getDate(),
time: getTime(),
weather_type: weatherType(),
loading: false
}
case DATA_LOADING:
return {
...state,
loading: true
}
default:
return state;
}
} |
import React from "react";
import PropTypes from "prop-types";
import styles from "./styles.module.scss";
import {
Divider,
Button,
} from 'semantic-ui-react'
import ReactSVG from 'react-svg';
import {
NETWORK,
NETWORK_TYPE
} from "../../config/constants"
const ModelVerifier = (props, context) => {
return(
<div className={styles.RootDivision}>
<div className={styles.OutterDivision}>
<div className={styles.SelectFileFormDivision}>
<RenderSelectFile {...props} />
</div>
<RenderSubmitButton {...props} />
<RenderContentInfo {...props}/>
<RenderBlockChainInfo {...props}/>
</div>
</div>
)
}
const RenderBlockChainInfo = (props, context) => {
if (props.blockchain_metadata === null || props.blockchain_metadata === undefined) {
return null
} else {
return (
<React.Fragment>
<RenderTitle
icon={require("images/icons/svg/home_music_icon.svg")}
titleText={context.t("Blockchain Info.")}
/>
<div className={styles.BlockchainInfoDivision}>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Hashright ID.")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>
{props.db_model_photo.blockchain_id}
</p>
</div>
</div>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Transction ID.")}
</p>
</div>
<div className={styles.RightDivision}>
{
NETWORK === NETWORK_TYPE.ROPSTEN ?
(
<a
href={`https://ropsten.etherscan.io/tx/${props.db_model_photo.blockchain_txid}`}
target="_blank"
rel="noopener noreferrer"
className={styles.TxidText}
>
{props.db_model_photo.blockchain_txid}
</a>
) :
(
<a
href={`https://etherscan.io/tx/${props.db_model_photo.blockchain_txid}`}
target="_blank"
rel="noopener noreferrer"
className={styles.TxidText}
>
{props.db_model_photo.blockchain_txid}
</a>
)
}
</div>
</div>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Type of contents")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>
{props.blockchain_metadata.properties.contents_type}
</p>
</div>
</div>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Hash")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>
{props.blockchain_metadata.hash}
</p>
</div>
</div>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Publisher.")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>
{props.blockchain_metadata.properties.publisher}
</p>
</div>
</div>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Country.")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>
{props.blockchain_metadata.properties.country}
</p>
</div>
</div>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Vender.")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>
{props.blockchain_metadata.properties.vender}
</p>
</div>
</div>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Vender Homepage.")}
</p>
</div>
<div className={styles.RightDivision}>
<a
href={`${props.blockchain_metadata.properties.vender_homepage}`}
target="_blank"
rel="noopener noreferrer"
className={styles.Text}
>
{props.blockchain_metadata.properties.vender_homepage}
</a>
</div>
</div>
</div>
</React.Fragment>
)
}
}
const RenderContentInfo = (props, context) => {
if (props.db_hash === null || props.db_hash === undefined || props.db_hash === "") {
return null
} else {
return (
<React.Fragment>
<Divider />
<RenderTitle
icon={require("images/icons/svg/home_music_icon.svg")}
titleText={context.t("Content Info.")}
/>
<div className={styles.TagDivision}>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("TAG Info.")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>
{props.db_copyright}
</p>
</div>
</div>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Hash.")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>
{props.db_hash}
</p>
</div>
</div>
<RenderModelPhotoInfo {...props} />
</div>
</React.Fragment>
)
}
}
const RenderModelPhotoInfo = (props, context) => {
if (props.db_model_photo === undefined || props.db_model_photo === null) {
return (
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Model photo")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}></p>
</div>
</div>
)
} else {
return (
<React.Fragment>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Modeler")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>{props.db_model_photo.modeler.nickname}</p>
</div>
</div>
<div className={styles.InnerDivision}>
<div className={styles.LeftDivision}>
<p className={styles.Text}>
{context.t("Photo Type")}
</p>
</div>
<div className={styles.RightDivision}>
<p className={styles.Text}>{props.db_model_photo.photo_type}</p>
</div>
</div>
</React.Fragment>
)
}
}
const RenderTitle = (props, context) => {
return (
<div className={styles.TitleDivision}>
<ReactSVG
className={styles.LeftSvgIcon}
src={props.icon}
svgStyle={{width: "50px", height: "50px"}}
/>
<p className={styles.Text}>{context.t(`${props.titleText}`)}</p>
</div>
)
}
const RenderSubmitButton = (props, context) => {
return (
<div className={styles.SubmitDivision}>
<Button
disabled={props.selected_model_photo_file === null || props.selected_model_photo_file === undefined}
className={styles.SubmitButton}
onClick={props.handleOnSubmit}
>
{context.t('VERIFY')}
</Button>
</div>
)
}
const RenderSelectFile = (props, context) => {
let modelPhotoFileRef = React.createRef();
return (
<div className={styles.SelectFileDivision}>
<div className={styles.SelectedInput}>
<input
type='file'
accept="image/jpeg"
onChange={props.handleInputChange}
id='selected_model_photo_file'
ref={modelPhotoFileRef}
/>
<p className={
(props.selected_model_photo_file === undefined || props.selected_model_photo_file === null)
? styles.FilenamePlaceholderText : styles.FilenameText}
>
<span className={styles.StarText}>*</span>
{
props.selected_model_photo_file === undefined || props.selected_model_photo_file === null
? context.t('파일선택 (Choose Your File)')
: props.selected_model_photo_file.name
}
</p>
</div>
<div className={styles.FileRegisterRightDivision}>
<div
className={styles.DefaultIconDivision}
onClick={()=> {
modelPhotoFileRef.current.click()
}}
>
<p className={styles.DefaultIconText}>{context.t("REGISTER")}</p>
</div>
</div>
</div>
)
}
ModelVerifier.propTypes = {
handleInputChange: PropTypes.func.isRequired,
handleOnSubmit: PropTypes.func.isRequired,
selected_model_photo_file: PropTypes.any,
db_copyright: PropTypes.string.isRequired,
db_hash: PropTypes.string.isRequired,
db_model_photo: PropTypes.object,
blockchain_metadata: PropTypes.object,
}
ModelVerifier.contextTypes = {
t: PropTypes.func.isRequired
};
RenderModelPhotoInfo.contextTypes = {
t: PropTypes.func.isRequired
};
RenderSubmitButton.contextTypes = {
t: PropTypes.func.isRequired
};
RenderSelectFile.contextTypes = {
t: PropTypes.func.isRequired
};
RenderTitle.contextTypes = {
t: PropTypes.func.isRequired,
}
RenderContentInfo.contextTypes = {
t: PropTypes.func.isRequired,
}
RenderBlockChainInfo.contextTypes = {
t: PropTypes.func.isRequired,
}
export default ModelVerifier; |
var ajv = require('ajv');
var _ = require('lodash');
var model_data = require('../../data/data-models/sample_model');
var env = new ajv();
var transformErrorMessage = function(errorArray){
var message = ""
errorArray.reduce(function(errormessage,error){
message += "Exception in "
errormessage + _.forOwn(error,function(value,key,object){
message += key + ":" + value + "," ;
})
message += "\n";
},"");
return message;
}
var validator = function(name,response){
var schema = model_data[name];
var validate = env.compile(schema);
var valid = validate(response);
if(!valid) return transformErrorMessage(validate.errors);
return valid;
};
module.exports = {
'validateSchema':validator
} |
import './scss/style.scss'
import bootstrap from 'bootstrap'
import $ from 'jquery'
import Flickity from 'flickity'
import imagesLoaded from 'flickity-imagesloaded'
import BeerSlider from 'beerslider'
/* SLIDER */
const slider = new BeerSlider(document.getElementById('beer-slider'))
/* CAROUSEL */
const mainCarousel = document.querySelector('.main-carousel')
const flick = new Flickity(mainCarousel, {
// cellAlign: 'left',
contain: true,
imagesLoaded: true,
draggable: false,
// autoPlay: true,
prevNextButtons: true,
pageDots: false,
arrowShape: {
x0: 5,
x1: 30, y1: 25,
x2: 35, y2: 20,
x3: 15
}
})
// Displaying selected image
const imagePreview = document.querySelector('.image-preview')
flick.on('select', (index) => {
imagePreview.src = flick.selectedElement.src
})
flick.on('staticClick', (e, pointer, cellElement, cellIndex) => {
flick.select(cellIndex, false, false)
})
/* NAVBAR BUTTON */
$('.navbar__menu-button').on('click', expandNav)
function expandNav () {
$('.navbar').toggleClass('navbar_expanded')
$('.navbar__menu-title').toggleClass('d-lg-inline')
$('.navbar__menu-button').toggleClass([
// remove
'order-lg-2',
'px-lg-2',
// add
'order-lg-0',
'px-lg-1',
'align-self-lg-end'
])
$('.navbar-collapse>ul').toggleClass([
'text-lg-start',
'px-lg-2'
])
$('.address-info').toggleClass('pb-lg-1')
$('.address-info__number').toggleClass('pb-lg-0')
}
|
import React from 'react';
import { connect } from 'react-redux';
import { Col, Row, Table } from 'antd';
function NewProgressCharts(props) {
//hardcoded child data
const childData = [
{
name: 'SubmarineBoy',
MissionsCompleted: 7,
TotalPoints: 460,
TotalWords: 100,
key: '1',
},
{
name: 'Pinky Winky',
MissionsCompleted: 6,
TotalPoints: 500,
TotalWords: 115,
key: '2',
},
{
name: 'Dad',
MissionsCompleted: 8,
TotalPoints: 390,
TotalWords: 80,
key: '3',
},
];
//Data structure
const columns = [
{ title: 'Name', dataIndex: 'name', key: 'key' },
{
title: 'Missions Completed',
dataIndex: 'MissionsCompleted',
key: 'key',
sorter: (a, b) => a.MissionsCompleted - b.MissionsCompleted,
},
{
title: 'Total Points',
dataIndex: 'TotalPoints',
key: 'key',
sorter: (a, b) => a.TotalPoints - b.TotalPoints,
},
{
title: 'Total Words',
dataIndex: 'TotalWords',
key: 'key',
sorter: (a, b) => a.TotalWords - b.TotalWords,
},
];
// FAKE DATA WILL NEED TO BE REPLACED WITH ACCURATE CHILD DATA
return (
<div className="ProgressContainer">
<div className="ProgressHeader">
<h2>Progress Charts</h2>
</div>
<div className="ProgressBox">
<Table
pagination={false}
columns={columns}
dataSource={childData}
></Table>
</div>
</div>
);
}
export default connect(
state => ({
child: state.child,
}),
{}
)(NewProgressCharts);
|
/**
* Insertion Sort
*
* Sort an array of numbers in ascending order
*
* Time complexity: O(n^2) worst and average case, O(n) best case
* Space complexity: O(1)
*/
/**
* @param {number[]} arr
* @return {number[]}
*/
const insertionSort = arr => {
for (let i = 1; i < arr.length; i++) {
let val = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > val) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = val;
}
return arr;
};
module.exports = {
insertionSort
};
|
import Filter from './Filter.js';
import { useTranslation } from "react-i18next";
function Filters( props ) {
const { t } = useTranslation();
const updateState = ( state ) => {
props.setState( state );
props.setCounty( '' );
}
return (
<div className="filters o-well block block__sub">
<h2>{ t( 'filters.legend' ) }</h2>
<Filter id="state-select"
label={ t( 'filters.state.label' ) }
onChange={ updateState }
options={ props.stateOptions }
placeholder={ t( 'filters.state.placeholder' ) }
value={ props.state }/>
{ props.countyOptions.length > 0 &&
<Filter id="county-select"
helperText={ t( 'filters.county.helper_text' ) }
label={ t( 'filters.county.label' ) }
onChange={ props.setCounty }
options={ props.countyOptions }
placeholder={ t( 'filters.county.placeholder' ) }
value={ props.county }/>
}
<div className="block
block__sub
block__border-top
block__padded-top
block__flush-bottom">
<Filter id="tribe-select"
helperText={ t( 'filters.tribe.helper_text' ) }
label={ t( 'filters.tribe.label' ) }
onChange={ props.setTribe }
options={ props.tribeOptions }
placeholder={ t( 'filters.tribe.placeholder' ) }
value={ props.tribe }/>
</div>
</div>
);
}
export default Filters;
|
/**
* 将 平级的 array 数据 转化成 树形数据
*/
export const convertArrayToTree = (arrayDatas, id = 'id', pId = 'parentId') => {
function exists(data, parentId) {
for (let i = 0; i < data.length; i++) {
const element = data[i];
if (element[id] == parentId) return true;
}
return false;
}
if (!arrayDatas || !arrayDatas.length) return [];
const nodes = [];
// get the top level nodes
for (let i = 0; i < arrayDatas.length; i++) {
const row = arrayDatas[i];
if (!exists(arrayDatas, row[pId])) {
nodes.push(row);
}
}
const toDo = [];
for (let i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
const node = toDo.shift(); // the parent node
// get the children nodes
for (let i = 0; i < arrayDatas.length; i++) {
const row = arrayDatas[i];
if (row[pId] == node[id]) {
const child = row;
if (node.children) {
node.children.push(child);
} else {
node.children = [child];
}
toDo.push(child);
}
}
}
console.log(nodes);
return nodes;
}; |
/* Server software for handling remote account manager and private
* SDN.
*/
require('./sdn.js');
require('./manager.js');
require('./accounts.js');
|
import axios from 'axios';
const getLoggedInUser = async () => {
try {
const { data } = await axios.get('/catsapi/v1/auth/me');
return data;
} catch (error) {
return false;
}
};
export default getLoggedInUser;
|
/**
* Created by zrz on 2016/5/31.
* @version 1.0.0 created 动态化参数传递
*/
"use strict";
//根据形参内容的不同生成不同key的实例
var Good = function (_) {
var that = this;
if (_ && typeof _ === 'object' && Object.keys(_).length > 0) {
for (var i in _) {
if (_.hasOwnProperty(i)) {
that[i] = _[i];
}
}
}
};
//计算总价
Good.prototype.sum = function () {
return parseFloat(parseFloat((this.amount || 0) * (this.price || 0)).toFixed(2));
};
var good1 = new Good({
name: '雪碧'
, unit: '箱'
, price: 125.00
, amount: 0
, info: '雪碧很好喝'
});
var good2 = new Good({
name: '可口可乐'
, unit: '箱'
, price: 10
, amount: 0
, productTime: '2016-5-31'
});
good1.name = '哈哈哈';
console.info(good1, good1.name);
console.info(good2, good2.sum());
good2.amount = 1.15645231;//改变数量
console.info(good2, good2.sum());
good2.price = 12.13651;//改变价格
console.info(good2, good2.sum());
|
import React from 'react';
import PropTypes from 'prop-types';
function TestCount(props) {
return (
<div className="testCount">
VALIDATION <span>{props.counter}</span> of <span>{props.total}</span>
</div>
);
}
TestCount.propTypes = {
counter: PropTypes.number.isRequired,
total: PropTypes.number.isRequired
};
export default TestCount; |
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const LocalStrategy =require('passport-local');
const expressSession =require('express-session');
const User = require("./models/userModel");
const app = express();
const bodyParser = require('body-parser');
const indexRoutes = require("./routes/indexRoutes");
const adminRoutes = require("./routes/adminRoutes");
const blogRoutes = require("./routes/blogRoutes");
mongoose.connect('mongodb://localhost/BlogApp',{ useUnifiedTopology: true, useNewUrlParser: true });
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:true}));
const passportLocalMongoose =require('passport-local-mongoose');
app.use(require("express-session")({
secret:"bu bizim güvenlik cümlemizdir",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use((req, res, next)=>{
res.locals.currentUser=req.user;
next();
});
app.use(indexRoutes);
app.use(adminRoutes);
app.use(blogRoutes);
app.listen(3000, ()=>{
console.log("3000 portundan server çalışıyor");
});
|
function alphabeticalOrder(input) {
return (''+input).split('').sort().join('');
}
module.exports.alphabeticalOrder = alphabeticalOrder; |
var user = {
login : "Vitaliy",
password : 0990094989,
loginOk : function() {
alert(this.login + "Enter in site");
},
loginFail : function() {
alert(this.login + "Failed in site");
},
checkPassword : function() {
ask("Your password?",this.password, this.loginOk.bind(this), this.loginFail.bind(this));
}
};
function ask(question, answer, ok, fail) {
var result = prompt(question, ' ');
if(result.toLowerCase() == answer.toLowerCase()){
ok();
}
else{
fail();
}
}; |
function dropElements(arr, func) {
var trueAtIndex = -1;
// Loop until func is true
for (var i = 0; i < arr.length; i++) {
if (func(arr[i])) {
trueAtIndex = i;
break;
}
}
// if func was never true
if (trueAtIndex === -1) {
return [];
}
return arr.slice(trueAtIndex, arr.length);
}
dropElements([0, 1, 0, 1], function(n) {return n === 1;});
|
var searchData=
[
['execcommand',['execCommand',['../sh__command_8c.html#a1431ad5263e7ffa4775841cd4d172944',1,'sh_command.c']]]
];
|
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/user');
// REGISTER new USER
router.post('/', (req, res, next) => {
const user = new User({
_id: mongoose.Types.ObjectId(),
rut: req.body.rut,
email: req.body.email,
password: req.body.password,
firstname: req.body.firstname,
lastname1: req.body.lastname1,
lastname2: req.body.lastname2,
institution: req.body.institution,
birthdate: req.body.birthdate,
gender: req.body.gender,
phone: req.body.phone,
type: req.body.type
});
user.save()
.then(result => {
console.log(result)
res.status(201).json({
message: 'Successfully created user',
created: result,
});
})
.catch(err => {
console.log(err)
res.status(500).json({ error: err });
});
});
module.exports = router; |
"use strict";define(['jquery','knockout'],function($,ko){var init=function(koObject){}
var onSave=function(koObject){}
return{init:init,onSave:onSave}}); |
function DlgSelectDataset2(mapContainer,obj,options) {
options=options||{};
options.rtl=(app.layout=='rtl');
options.showOKButton=false;
options.dialogSize=BootstrapDialog.SIZE_WIDE;
options.cancelButtonTitle='Close';
DlgTaskBase.call(this, 'DlgSelectDataset2'
//,(options.title || 'Select Document')
,(options.title || app.i18n['SelecteDataset'] || 'Select dataset')
, mapContainer,obj,options);
var settings= this.obj ||{};
this.url= settings.url || "/datasets?format=json";
this.initFilters= options.initFilters || [];
}
DlgSelectDataset2.prototype = Object.create(DlgTaskBase.prototype);
DlgSelectDataset2.prototype.createUI=function(){
var self=this;
if(app.cache && app.cache['datasets.vash']){
self.createUI_inner( app.render(app.cache['datasets.vash']));
}else{
$.ajax({
url : "/client_views/datasets.vash",
dataType: "text",
success : function (data) {
app.cache= app.cache||{};
app.cache['datasets.vash']=data;
self.createUI_inner( app.render(app.cache['datasets.vash']));
},
error: function (xhr, textStatus, errorThrown) {
alert('error');
}
});
}
}
DlgSelectDataset2.prototype.createUI_inner=function(view){
var self=this;
var htm='<div class="scrollable-content" ><form id="'+self.id+'_form" class="modal-body form-horizontal">';
htm+= view;
htm += '</form>';
htm+=' </div>';
var content=$(htm).appendTo( this.mainPanel);
this.content=content;
content.find('#cmdAddNewGroupLayer').click(function(){
app.mapContainer.addNewGroupLayer();
});
content.find('#cmdAddNewWMS').click(function(){
app.mapContainer.addNewWMS();
});
content.find('#cmdAddNewWFS').click(function(){
app.mapContainer.addNewWFS();
});
content.find('#cmdAddNewOSMXML').click(function(){
app.mapContainer.addNewOSMXML();
});
content.find('#cmdAddGeoJSON').click(function(){
app.mapContainer.addGeoJSON();
});
content.find('#cmdWCS').click(function(){
app.mapContainer.downloadDataFromWCS();
});
var $form = $(content.find('#'+self.id +'_form'));
$form.on('submit', function(event){
// prevents refreshing page while pressing enter key in input box
event.preventDefault();
});
this.beforeApplyHandlers.push(function(evt){
var origIgone= $.validator.defaults.ignore;
$.validator.setDefaults({ ignore:'' });
$.validator.unobtrusive.parse($form);
$.validator.setDefaults({ ignore:origIgone });
$form.validate();
if(! $form.valid()){
evt.cancel= true;
var errElm=$form.find('.input-validation-error').first();
if(errElm){
var offset=errElm.offset().top;
//var tabOffset= tabHeader.offset().top;
var tabOffset=0;
//tabOffset=self.mainPanel.offset().top;
tabOffset=$form.offset().top;
self.mainPanel.find('.scrollable-content').animate({
scrollTop: offset - tabOffset //-60//-160
}, 1000);
}
}
});
this.applyHandlers.push(function(evt){
});
this.changesApplied=false;
var _autoSearchUrl = this.url;
var _lastSelectedItem;
var cache =undefined;// {};
this.onAfterPageCreated();
}
DlgSelectDataset2.prototype.onAfterPageCreated=function(){
var self= this;
var content=self.content
this.filterExpression='';
this.applyMapExtent=false;
this.mapExtent={
minx: -180,
miny: -90,
maxx: 180,
maxy: 90
}
var dataStr=$('#items').val();
this.items= [];
this.data={};
this.pagination={
start:1,
limit:20
};
try{
}catch(ex){}
content.find( "#tblItems_search").on("keyup", function (evt) {
evt.stopPropagation();
evt.preventDefault();
if (evt.which == 13) {
var value = $(this).val().toLowerCase();
self.filterExpression= value;
self.applyFilters();
}
});
content.find("#text_search_btn").on("click", function () {
var value = content.find("#tblItems_search").val().toLowerCase();
self.filterExpression= value;
self.applyFilters();
});
content.find('#pnlExtentMap').addClass('collapse');
content.find('#pnlExtentMapCmd').addClass('collapsed');
// this.fillUI();
// var url=self.getFiltersUrl();
// self.last_url=url;
// self.getFromUrl(url);
// self.getCachedItems();
this.fillUI();
var url=self.getFiltersUrl();
self.last_url=url;
// history.pushState({url:url}, document.title, url);
// window.addEventListener('popstate', function(e){
// if(e.state && e.state.url && !e.state.confirmDialog)
// self.getFromUrl(e.state.url,true);
// });
this.applyFilters ();
};
DlgSelectDataset2.prototype.showWaiting=function(){
var self=this;
var detailsContainer= $('#tblItems');
var html='<div class="col-xs-18 col-sm-12 col-md-12 "> <div class="thumbnail waitbar_h" style="height:30px" ></div> </div>';
detailsContainer.html(html);
}
DlgSelectDataset2.prototype.fillItems=function(items){
var self=this;
var detailsContainer= $('#tblItems');
var html='';
html+= this.get_pageToolbar(this.pagination);
html+='<div style="clear:both;"></div>';
for(var i=0;i<items.length;i++){
var item= items[i];
html+='<div class="media selectable"';
html+=' data-id="'+item.id+'"';
html+=' data-subtype="'+item.subtype+'"';
html+=' data-datatype="'+item.fileType+'"';
html+=' data-keywords="'+item.keywords+'"';
html+=' data-ext_north="'+item.ext_north+'"';
html+=' data-ext_east="'+item.ext_east+'"';
html+=' data-ext_west="'+item.ext_west+'"';
html+=' data-ext_south="'+item.ext_south+'"';
html+='>';//1
// html+=' <div class="listItem-select-box"><button type="button" class="btn btn-default btn-sm"> <span data-id="' + item.id+'" class="glyphicon glyphicon-unchecked"></span></button></div>';
html+=' <div class="media-right pull-right" data-id="' + item.id+'">';//3
if(item.thumbnail){
html+=' <img class="media-object" src="'+item.thumbnail+'" style="width:100px" />';
}else{
}
html+=' </div>';//3
html+='<div class="media-body">';
html+='<h4 class="media-heading">';
if(item.dataType=='table'){
html+=' <span class=" glyphicon glyphicon-list-alt"> </span>';
}else if(item.subType=='MultiPolygon'){
html+=' <span class="layerSubtype">▭</span>';
}
if(item.subType=='MultiLineString'){
html+=' <span class="layerSubtype">▬</span>';
}
if(item.subType=='Point'){
html+=' <span class="layerSubtype">◈</span>';
}
if(item.dataType=='raster'){
html+=' <span class="layerSubtype">▦</span>';
}
html+=' '+item.name;
html+='</h4>';
html+=' <p class="item-description" >'+ (item.description || '').replace(/(?:\r\n|\r|\n)/g, '<br />') +'</p>';
html+=' <ul class="list-inline">';
if(item.updatedAt){
var val=item.updatedAt +''
var date = new Date(val);
var str=date.toString();
str=date.toLocaleString();
// var timeOnly= date.toLocaleTimeString('fa',{hour12:true});
if (app.language=='fa'){
try{
// var timeOnly= date.toLocaleTimeString('en',{hour12:false});
// var jdate = new window['jdate'].default(date);
// //str= jdate.format('dddd DD MMMM YYYY') + ' '+ timeOnly; // => پنجشنبه 12 شهریور 1394
// str= jdate.format('YYYY/MM/DD') + ' '+ timeOnly; // => پنجشنبه 12 شهریور 1394
moment.locale('fa');
str= moment.from(date).format('YYYY/MM/DD HH:mm:ss');
}catch(exx){}
}
//str=date.toLocaleString('en', { timeZone: 'UTC' });
//str=date.toLocaleString('en', { timeZone: 'Asia/Tehran' });
//str=date.toLocaleString('en', { timeZone: 'Europe/Stockholm' });
//str=date.toLocaleString('en', { timeZone: 'Asia/Bishkek' });
var title= ' ('+date.toLocaleString('en', { timeZone: 'UTC' })+' GMT)';
html+=' <li style="direction:ltr">';
html+=' <i class="fa fa-calendar fa-calendar-o"></i><span class="convertTolocalDateTime__" title="Definition modified at '+ title +'" >'+str+'</span>';
html+=' </li>';
}
html+=' <li>';
html+=' <i class="fa fa-user" title="مالک" ></i>';
if(app.identity.id==item.OwnerUser.id){
html+=' <b> <span title="مالک" >'+item.OwnerUser.userName+'</span></b>';
}else{
html+=' <span title="مالک">'+item.OwnerUser.userName+'</span>';
}
html+=' </li>';
html+=' <li>';
html+=' <button type="button" data-dataset-id="'+item.id+'" class="btn btn-xs btn-primary add_dataset_to_map " title="افزودن به نقشه"><span class="glyphicon glyphicon-plus"></span></button>';
html+=' </li>';
html+=' </ul>';
html+='</div>';
html+='</div>';//1 media
}
if(items.length){
html+='<div class="col-xs-18 col-sm-12 col-md-12">';
html+=this.get_pagination(this.pagination,true);
html+='</div>';
}
detailsContainer.html(html);
// detailsContainer.find('.media').unbind('click').click(function(){
// $(this).toggleClass('selected');
// })
detailsContainer.find('.media .add_dataset_to_map').unbind('click').click(function(){
var datasetId=$(this).data('datasetId');
var selfThis=this;
$(this).addClass('wait-icon-with-padding');
app.mapContainer.addLayerById(datasetId,function(status,info){
$(selfThis).removeClass('wait-icon-with-padding');
});
})
detailsContainer.find('.page-link').unbind('click').click(function(){
if(!$(this).parent().hasClass('disabled')){
var url= $(this).data('url');
if(url){
self.getFromUrl(url);
}
}
});
detailsContainer.find('.delete-item').unbind('click').click(function(){
var itemId= $(this).data('id');
if(itemId){
self.deleteItem(itemId);
}
});
}
DlgSelectDataset2.prototype.fillUI=function(){
var self=this;
this.fillingUI=true;
this.fillStatistics(this.data.statistics,this.data.pagination);
$("#tblItems_search").val(this.pagination.filterExpression);
if(this.pagination.extent){
var extent= this.pagination.extent.split(',');
self.mapExtent={
minx: extent[0],
miny: extent[1],
maxx: extent[2],
maxy: extent[3]
}
self.applyMapExtent=true;
}
this.fillItems(this.items);
this.fillOrderByList(this.data.pagination);
this.fillingUI=false;
$('.panel-group').has('.list-group-item').removeClass('has-active-filter');
$('.panel-group').has('.list-group-item.active').addClass('has-active-filter');
$('.panel-group .clear-filter').unbind('click').click(function(e){
e.stopPropagation();
e.preventDefault();
var panelGroup= $(this).closest('.panel-group');
panelGroup.find('.list-group-item').removeClass('active');
panelGroup.find('input').val(undefined);
panelGroup.find('input').removeClass('active');
self.applyFilters();
});
$('.clear-filter').addClass('hidden');
$('.list-group-item.active').closest('.panel-group').find('.clear-filter').removeClass('hidden');
}
DlgSelectDataset2.prototype.get_pageToolbar=function(pagination){
var self=this;
var html='<div class="col-xs-18 col-sm-12 col-md-12">';
html+=this.get_pagination(pagination);
html+=this.get_pageCommandbar(pagination);
html+='</div>'
return html;
}
DlgSelectDataset2.prototype.get_pageCommandbar=function(pagination){
var self=this;
var html='';
// if(!pagination){
// return html;
// }
// if(!pagination.limit)
// return html;
// if(!pagination.totalItems)
// return html;
// html+='<ul style="margin-top: 0;" class="pagination pagination-sm pull-left">';
// html+=' <li class="page-item ">';
// html+=' <div class="listItem-select-all-box"><button type="button" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-unchecked"></span></button></div>';
// html+=' </li>';
// html+='</ul>';
return html;
}
DlgSelectDataset2.prototype.get_pagination=function(pagination,footer){
var self=this;
var html='';
if(!pagination){
return html;
}
if(!pagination.limit)
return html;
if(!pagination.totalItems){
if(footer){
return ''
}else{
return '<div class="panel-heading"><legend>No item found!</legend></div>';
}
}
if(!pagination.start)
pagination.start=1;
var totalPages = Math.ceil(pagination.totalItems / pagination.limit);
if(footer && totalPages<=1){
return '';
}
var currentPage = Math.floor((pagination.start-1) / pagination.limit)+1;
if (currentPage>totalPages){
currentPage=totalPages;
}
var limit= pagination.limit;
var firstPage=1;
var lastPage=totalPages;
var prevPage= currentPage-1;
var nextPage= currentPage+1;
if(prevPage<firstPage)prevPage=firstPage;
if(nextPage>lastPage)nextPage=lastPage;
var filter='';
html+='<ul style="margin-top: 8px;margin-bottom: 8px;" class="pagination pagination-sm pull-right">';
html+=' <li class="page-item first-item '+ ((firstPage==currentPage)?'disabled':'')+'">';
html+=' <span class="page-link" href="#" data-url="'+self.getFiltersUrl({start:((firstPage-1)*limit +1)}) +'">'+ '<<' +'</span>';
//html+=' <button type="button" class="page-link" href="?limit='+limit+ '&start='+((firstPage-1)*limit +1)+'&' + filter +'">'+ '<<' +'</a>';
html+=' </li>';
html+=' <li class="page-item previous-item '+ ((prevPage==currentPage)?'disabled':'')+'">';
html+=' <span class="page-link" href="#" data-url="'+self.getFiltersUrl({start:((prevPage-1)*limit +1)}) +'">'+ '<' +'</span>';
html+=' </li>';
html+=' <li class="page-item next-item ">';
html+=' <span class="page-link" href="#" data-url=""'+self.getFiltersUrl({start:((currentPage-1)*limit +1)}) +'">'+ 'Page '+ currentPage + '/' +totalPages +' of '+pagination.totalItems+ ' itmes </span>';
html+=' </li>';
html+=' <li class="page-item next-item '+ ((nextPage==currentPage)?'disabled':'')+'">';
html+=' <span class="page-link" href="#" data-url="'+self.getFiltersUrl({start:((nextPage-1)*limit +1)}) +'">'+ '>' +'</span>';
html+=' </li>';
html+=' <li class="page-item last-item '+ ((lastPage==currentPage)?'disabled':'')+'">';
html+=' <span class="page-link" href="#" data-url="'+self.getFiltersUrl({start:((lastPage-1)*limit +1)})+'">'+ '>>' +'</span>';
html+=' </li>';
html+='</ul>';
return html;
}
DlgSelectDataset2.prototype.fillStatistics=function(statistics,pagination){
this.fillStatistics_projects(statistics,pagination);
this.fillStatistics_authors(statistics,pagination);
this.fillStatistics_datasettypes(statistics,pagination);
this.fillStatistics_themes(statistics,pagination);
this.fillStatistics_keywords(statistics,pagination);
}
DlgSelectDataset2.prototype.fillStatistics_projects=function(statistics,pagination){
var self=this;
var html='';
if(!statistics)
return;
if(!statistics.projects)
return;
var items= statistics.projects;
for(var i=0;i< items.length /*&& i<10*/;i++){
var item=items[i];
html+= '<li>';
html+=' <span class="list-group-item" data-filtertype="project" data-filter="'+ item.id+'" >'+ item.caption + '<span class="badge pull-right">'+ item.total+ '</span></span>';
html+= '</li>';
}
$("#projects").html(html);
$("#projects .list-group-item").unbind('click').click(function(){
$(this).toggleClass('active');
self.applyFilters();
});
if(pagination && pagination.projects){
for(var i=0;i<pagination.projects.length;i++){
var cc=$("#projects .list-group-item[data-filter='" +pagination.projects[i]+"']");
$('#projects .list-group-item[data-filter="' +pagination.projects[i]+'"]').addClass('active');
}
}
}
DlgSelectDataset2.prototype.fillStatistics_authors=function(statistics,pagination){
var self=this;
var html='';
if(!statistics)
return;
if(!statistics.authors)
return;
var items= statistics.authors;
for(var i=0;i< items.length /*&& i<10*/;i++){
var item=items[i];
html+= '<li>';
html+=' <span class="list-group-item" data-filtertype="author" data-filter="'+ item.name+'" >'+ item.name + '<span class="badge pull-right">'+ item.total+ '</span></span>';
html+= '</li>';
}
$("#authors").html(html);
$("#authors .list-group-item").unbind('click').click(function(){
$(this).toggleClass('active');
self.applyFilters();
});
if(pagination && pagination.authors){
for(var i=0;i<pagination.authors.length;i++){
var cc=$("#authors .list-group-item[data-filter='" +pagination.authors[i]+"']");
$('#authors .list-group-item[data-filter="' +pagination.authors[i]+'"]').addClass('active');
}
}
}
DlgSelectDataset2.prototype.fillStatistics_themes=function(statistics,pagination){
var self=this;
var html='';
if(!statistics)
return;
if(!statistics.themes)
return;
var items= statistics.themes;
for(var i=0;i< items.length /*&& i<10*/;i++){
var item=items[i];
html+= '<li>';
html+=' <span class="list-group-item" data-filtertype="theme" data-filter="'+ item.name +'" >'+ app.i18n['Table.Theme.'+item.name] || item.name + '<span class="badge pull-right">'+ item.total+ '</span></span>';
html+= '</li>';
}
$("#themes").html(html);
$("#themes .list-group-item").unbind('click').click(function(){
$(this).toggleClass('active');
self.applyFilters();
});
if(pagination && pagination.themes){
for(var i=0;i<pagination.themes.length;i++){
var cc=$("#themes .list-group-item[data-filter='" +pagination.themes[i]+"']");
$('#themes .list-group-item[data-filter="' +pagination.themes[i]+'"]').addClass('active');
}
}
},
DlgSelectDataset2.prototype.fillStatistics_datasettypes=function(statistics,pagination){
var self=this;
var html='';
if(!statistics)
return;
if(!statistics.datasetTypes)
return;
var items= statistics.datasetTypes;
for(var i=0;i< items.length /*&& i<10*/;i++){
var item=items[i];
html+= '<li>';
html+=' <span class="list-group-item" data-filtertype="datasetType" data-filter="'+ item.name+'" >'+ (app.i18n['Dataset.Type.'+item.name] || item.name) + '<span class="badge pull-right">'+ item.total+ '</span></span>';
html+= '</li>';
}
$("#datasetTypes").html(html);
$("#datasetTypes .list-group-item").unbind('click').click(function(){
$(this).toggleClass('active');
self.applyFilters();
});
if(pagination && pagination.datasetTypes){
for(var i=0;i<pagination.datasetTypes.length;i++){
$('#datasetTypes .list-group-item[data-filter="' +pagination.datasetTypes[i]+'"]').addClass('active');
}
}
}
DlgSelectDataset2.prototype.fillStatistics_keywords=function(statistics,pagination){
var self=this;
var html='';
if(!statistics)
return;
if(!statistics.keywords)
return;
var items= statistics.keywords;
for(var i=0;i< items.length /*&& i<10*/;i++){
var item=items[i];
html+= '<li>';
html+=' <span class="list-group-item" data-filtertype="keyword" data-filter="'+ item.name+'" >'+ item.name + '<span class="badge pull-right">'+ item.total+ '</span></span>';
html+= '</li>';
}
$("#keywords").html(html);
$("#keywords .list-group-item").unbind('click').click(function(){
$(this).toggleClass('active');
self.applyFilters();
});
if(pagination && pagination.keywords){
for(var i=0;i<pagination.keywords.length;i++){
$('#keywords .list-group-item[data-filter="' +pagination.keywords[i]+'"]').addClass('active');
}
}
}
DlgSelectDataset2.prototype.fillOrderByList=function(pagination){
var self=this;
var html='';
html+= '<li>';
html+=' <span class="list-group-item glyphicon glyphicon-sort-by-attributes" data-filtertype="orderby" data-filter="name" ><span style="font-family:Tahoma;"> @model.i18n["OrderByName"]</span></span>';
//html+=' <span class="list-group-item glyphicon glyphicon-sort-by-attributes-alt" data-filtertype="orderby" data-filter="-name" > نـــام</span>';
// html+=' <span class="list-group-item glyphicon glyphicon-sort-by-attributes" data-filtertype="orderby" data-filter="size" > انــدازه</span>';
//html+=' <span class="list-group-item glyphicon glyphicon-sort-by-attributes-alt" data-filtertype="orderby" data-filter="-size" > انــدازه</span>';
html+=' <span class="list-group-item glyphicon glyphicon-sort-by-attributes" data-filtertype="orderby" data-filter="updatedAt" ><span style="font-family:Tahoma;"> @model.i18n["OrderByDate"]</span></span>';
//html+=' <span class="list-group-item glyphicon glyphicon-sort-by-attributes-alt" data-filtertype="orderby" data-filter="-updatedAt" > تــاریخ</span>';
html+= '</li>';
$("#orderbys").html(app.render(html));
$("#orderbys .list-group-item").unbind('click').click(function(){
var alreadyIsActive=$(this).hasClass('active');
$("#orderbys .list-group-item").removeClass('active');
$(this).addClass('active');
var filter= $(this).data('filter');
if(filter && alreadyIsActive){ // switch order
if (filter.indexOf('-')==0){
filter=filter.substring(1);
$(this).removeClass('glyphicon-sort-by-attributes-alt');
$(this).addClass('glyphicon-sort-by-attributes');
}else
{
filter='-'+filter;
$(this).removeClass('glyphicon-sort-by-attributes');
$(this).addClass('glyphicon-sort-by-attributes-alt');
}
$(this).data('filter',filter);
}
self.applyFilters();
});
if(pagination && pagination.orderby){
var filter=pagination.orderby;
var key=filter;
var reverse=false;
if (filter.indexOf('-')==0){
key=filter.substring(1);
reverse=true;
}
var elem=$('#orderbys .list-group-item[data-filter="' +key+'"]');
elem.addClass('active');
if(reverse){
elem.removeClass('glyphicon-sort-by-attributes');
elem.addClass('glyphicon-sort-by-attributes-alt');
}
elem.data('filter',filter);
}
}
DlgSelectDataset2.prototype.createExtMap=function(){
var self=this;
var map = this.map = new ol.Map({
target: 'extMap',
layers: [
new ol.layer.Tile({
title: "OSM",
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([(app.initMap_Lon|| 0), (app.initMap_Lat ||0)])
//center: ol.proj.fromLonLat([53,32])
//,zoom:1
,zoom: app.initMap_Zoom || 4
//,extent:ol.proj.get("EPSG:3857").getExtent()
//,extent: ol.proj.transform([-180,-90,180,90],'EPSG:4326', 'EPSG:3857')
,extent: ol.extent.applyTransform([-180,-90,180,90], ol.proj.getTransform("EPSG:4326","EPSG:3857"))
})
});
map.on('moveend', function(evt) {
var map = evt.map;
var view = map.getView();
var mapProjectionCode = view.getProjection().getCode();
var extent = map.getView().calculateExtent(map.getSize());
extent = ol.extent.applyTransform(extent, ol.proj.getTransform(mapProjectionCode, "EPSG:4326"));
self.mapExtent={
minx: extent[0],
miny: extent[1],
maxx: extent[2],
maxy: extent[3]
}
if(self.applyMapExtent){
self.applyFilters();
}
//
});
}
DlgSelectDataset2.prototype.applyFilters_local=function(){
var self=this;
var mapExtent=self.mapExtent;
var expr= self.filterExpression;
$("#tblItems .listItem").filter(function () {
if(self.checkFilterExpression(this,expr)
&& self.checkFilterExtent(this,mapExtent )
){
$(this).toggle(true);
}else{
$(this).toggle(false);
}
});
}
DlgSelectDataset2.prototype.checkFilterExpression=function(item, expr){
if(!item )
return true;
if(!expr){
return true;
}
expr= (expr+'').toLowerCase();
return $(item).text().toLowerCase().indexOf(expr) > -1
}
DlgSelectDataset2.prototype.checkFilterExtent=function(item, extent){
if(!this.applyMapExtent){
return true;
}
if(!item )
return true;
if(!extent){
return true;
}
var minx= $(item).data('ext_west');
var maxx= $(item).data('ext_east');
var miny= $(item).data('ext_south');
var maxy= $(item).data('ext_north');
try{
minx= parseFloat(minx);miny= parseFloat(miny);
maxx= parseFloat(maxx);maxy= parseFloat(maxy);
if(minx> extent.maxx|| maxx< extent.minx || miny>extent.maxy || maxy<extent.miny ){
return false;
}else{
return true
}
}catch(ex){
return true
}
}
DlgSelectDataset2.prototype.applyFilters=function(){
var self=this;
if(this.fillingUI){
return;
}
var url=self.getFiltersUrl();
// window.location=url;
self.getFromUrl(url);
}
DlgSelectDataset2.prototype.getFiltersUrl=function(options){
options= options ||{};
var self=this;
var mapExtent=self.mapExtent;
var filterExpression= self.filterExpression;
if(options.filterExpression ){
filterExpression=options.filterExpression;
}
var extent;
if(this.applyMapExtent && mapExtent){
extent= mapExtent.minx+','+mapExtent.miny+','+mapExtent.maxx+','+mapExtent.maxy;
}
if(options.extent ){
extent=options.extent;
}
var args=[];
var start= 1;
if(options.start){
start= options.start;
}else if(this.pagination)
{
start=this.pagination.start;
}
start=start||1;
args.push('start='+ start);
var limit;
if(options.limit){
limit= options.limit;
}else if(this.pagination)
{
limit=this.pagination.limit ;
}
args.push('limit='+ limit);
if(extent){
args.push('extent='+ extent);
}
if(filterExpression){
args.push('filterExpression='+ encodeURIComponent(filterExpression));
}
var hasFilter=false;
$(".list-group-item.active").each(function(){
var filterType= $(this).data('filtertype');
if(filterType){
var filterValue= $(this).data('filter');
args.push(filterType+'='+encodeURIComponent(filterValue));
hasFilter=true;
self.initFilters=null;
}
})
if(!hasFilter && this.initFilters){
for(var f=0;f<this.initFilters.length;f++ ){
args.push(this.initFilters[f]);
}
}
var url= '?'+ args.join('&');
// window.location=url;
return url;
}
DlgSelectDataset2.prototype.getFromUrl=function(url,skipPushState){
var self= this;
self.last_url=url;
self.showWaiting();
if(self._lastRequest && self._lastRequest.abort){
self._lastRequest.abort();
}
self._lastRequest= $.ajax( { url: '/datasets'+url+'&format=json', dataType: 'json', success: function (data) {
if(!skipPushState){
// history.pushState({url:url}, document.title, url);
}
if(data){
self.data= data;
self.items=data.items;
self.pagination=data.pagination;
self.fillUI();
}
},error: function (xhr, textStatus, errorThrown) {
var msg=errorThrown ||textStatus ||"Failed";
if(msg=='abort'){
return;
}
if(xhr && xhr.responseJSON && xhr.responseJSON.error){
msg=xhr.responseJSON.error;
}
$.notify({
message: msg
},{
type:'danger',
delay:2000,
animate: {
enter: 'animated fadeInDown',
exit: 'animated fadeOutUp'
}
});
}
});
return;
}
|
var mongoose = require('mongoose');
var Token = require('../models/token');
var Staff = require('../models/staff');
var Agent = require('../models/agent');
var fs = require('fs');
var SHA256 = require("crypto-js/sha256");
var moment = require('moment');
// Insert a new Slider record
exports.IsTokenValid = function(AccessToken,accessReferer,callBack){
Token.find({_id:AccessToken, isActived:true}, function(err,result){
if(err){
console.log('-------- IsTokenValid() Error ---------');
console.log(AccessToken);
console.log(err);
callBack(false);
}else{
if(err) {
console.log(err)
callBack(false);
}
else {
if(result.length != 1) callBack(false);
else {
var type = result[0].type;
var matchUrl = null;
if(type == 'Staff') matchUrl = 'admin'
else if(type =='Agent') matchUrl = 'agent'
var res = accessReferer.split('/');
if(res.indexOf(matchUrl) > -1){
callBack(true);
}
else callBack(false);
}
}
}
});
}
exports.IsTokenValidForInActivedUser = function(AccessToken, callBack){
Token.find({_id:AccessToken, isActived:false}, function(err,result){
if(err){
console.log('-------- IsTokenValidForInActivedUser() Error ---------');
console.log(AccessToken);
console.log(err);
callBack(false);
}else{
if(result.length != 1)
//return false;
callBack(false);
else{
var tokenObj = result[0];
callBack(true);
}
}
});
}
|
require("angular-paging/dist/paging");
angular.module("Blog", [
"bw.paging"
]);
require("../controllers/blogController");
require("../controllers/commentController");
|
/* eslint-disable unicorn/prevent-abbreviations */
async function logout(request, res) {
request.session.data = null;
return res.status(200).json();
}
const mockRequest = (sessionData) => {
return {
session: {data: sessionData}
};
};
const mockResponse = () => {
const res = {};
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};
test('should set session.data to null', async () => {
const request = mockRequest({username: 'hugo'});
const res = mockResponse();
await logout(request, res);
expect(request.session.data).toBeNull();
});
test('should 200', async () => {
const request = mockRequest({username: 'hugo'});
const res = mockResponse();
await logout(request, res);
expect(res.status).toHaveBeenCalledWith(200);
});
|
/*
* ROOTSCOPE VARIABLES (maintained throughout trip):
* loop (East or West) --> post to server at start of trip
* copilotID (Brother kerberos) --> post to server at start of trip
* currentLocation (String name of location))
* Route (Array of locations objects)
* isDriving (true or false) - indicates whether the driving block should display
* initiating (true of false) - indicates whether the create route block should display
* enroute (true or false) - indicates whether the done button should display
*
*
* SCOPE VARIABLES (pulled and posted from server):
* selectingLoop - Indicates whether the loop options should display
* selectingCopilot - Indicates whether the copilotID selection options should display
*
*/
angular.module('txiRushApp')
.controller('drivingController', ['$scope', '$http', '$rootScope', '$interval', '$route', '$location', 'parseLogic',
function($scope, $http, $rootScope, $interval, $route, $location, parseLogic) {
if ($rootScope.notLogged || !$rootScope.isBrother || !$rootScope.configComplete){
$location.path("/login");
}
$rootScope.pageName = "Driving";
$rootScope.showFooter = false;
$rootScope.canRefresh = true;
$scope.initiating = true;
$scope.selectingLoop=true;
$scope.selectingCopilot=false;
console.log("STARTING DRIVING PAGE: ", $rootScope.isDriving);
parseLogic.getRequests();
//Visibility Functions
$scope.formComplete = function(){
return $scope.loop!=null && $scope.copilotID!=null;
};
$scope.routeAvailable = function(){
return !$rootScope.isDriving;
};
$scope.toggleSelectLoop = function(){
$scope.selectingLoop = ($scope.selectingLoop) ? false : true;
};
$scope.toggleSelectCopilot = function(){
$scope.selectingCopilot = ($scope.selectingCopilot) ? false : true;
};
$scope.setVisibility = function(driving, initiating, enRoute){
$rootScope.isDriving = driving;
$scope.initiating = initiating;
$rootScope.enRoute = enRoute;
};
$scope.hasRequests = function(location){
return $rootScope.requests[location].length > 0;
}
$scope.locationComplete = function(index){
return $rootScope.currentVan.get("location") > index;
}
//selection functions
$rootScope.clearSelectedLoops = function(){
var east = document.getElementById('East');
east.className = "startButton loopButton";
var west = document.getElementById('West');
west.className = "startButton loopButton";
var all = document.getElementById('All');
all.className = "startButton loopButton";
};
$rootScope.selectLoop = function(loop){
$scope.loop = $rootScope.routes[loop];
$rootScope.clearSelectedLoops();
var element = document.getElementById(loop);
element.className += " selected";
$scope.selectingCopilot = true;
};
$rootScope.clearSelectedCopilots = function(){
var brothers = $rootScope.brothers;
for (i=0; i<brothers.length; i++){
var brother = document.getElementById(brothers[i].id);
brother.className = "startButton brotherOptions";
}
};
$rootScope.selectCopilot = function(id, index){
$scope.copilot = $rootScope.brothers[index];
$scope.copilotID = id;
$scope.clearSelectedCopilots();
var element = document.getElementById(id);
element.className += " " + "selected";
};
//Trip functions
$scope.startRoute = function(){
//change visibility variables
$scope.setVisibility(true, false, true);
$scope.full=false;
$rootScope.currentRoute = $scope.loop;
$rootScope.requestHistory = [];
$scope.copilot.set("isDriving", true);
$scope.copilot.save();
parseLogic.submitNewVan($scope.copilotID, $scope.copilot.get("contact"), $scope.loop);
};
$scope.complete = function(status){
if (status==='done'){
return true;
}
else{
return false;
}
};
$scope.dot = function(first, last, loc){
var location = $rootScope.currentRoute.indexOf(loc);
if ($rootScope.currentVan.get("location") > location){
if (first){
return 'img/dots/closedDotTop.png';
}
else if (last){
return 'img/dots/closedDotBottom.png';
}
else{
return 'img/dots/closedDot.png';
}
}
else if ($scope.full && !loc.done){
return 'img/dots/line.png'
}
else{
if (first){
return 'img/dots/openDotTop.png';
}
else if (last){
return 'img/dots/openDotBottom.png';
}
else{
return 'img/dots/openDot.png';
}
}
};
$scope.next = function(){
if ($rootScope.currentVan.get("location") >= $rootScope.currentRoute.length - 1){
$scope.done();
} else {
var location = $rootScope.currentRoute[$rootScope.currentVan.get("location")]
var requests = $rootScope.requests[location];
$rootScope.requestHistory.push(requests);
for (var i=0; i < requests.length; i++){
console.log(requests[i]);
requests[i].destroy();
}
$rootScope.currentVan.increment("location");
$rootScope.currentVan.save();
$rootScope.refresh();
}
};
$scope.back = function(){
var lastRequests = $rootScope.requestHistory.pop();
for (var i=0; i < lastRequests.length; i++){
console.log(lastRequests[i]);
var Request = Parse.Object.extend("Request");
var request = new Request();
request.set("location", lastRequests[i].get("location"));
request.set("contact", lastRequests[i].get("contact"));
request.set("name", lastRequests[i].get("name"));
request.save()
}
$rootScope.refresh();
$rootScope.currentVan.increment("location", -1);
$rootScope.currentVan.save();
};
$scope.done = function(){
$scope.setVisibility(false, true, false);
$rootScope.selectingCopilot=true;
$rootScope.currentVan.destroy({
success : function(object){
object.get("copilot").set("isDriving", false);
object.get("copilot").save();
$rootScope.currentUser.set("isDriving", false);
$rootScope.currentUser.set("vanID", '');
$rootScope.currentUser.save();
console.log("TRIP ENDED AND VAN DESTROYED.");
},
error : function(object, error){
console.log("TRIP ENDED BUT VAN WAS NOT SUCCESSFULLY DESTROYED: ", error);
}
})
};
}]); |
$(document).ready(function() {
$( "#testMessage" ).click(function() {
var d = "message=" + $( "#message" ).val();
$.post( "/administration/send_test_message", d, function( data ) {
alert( data );
});
});
}); |
export default {
typography: {},
};
|
/*
Description:
Your task is to remove all consecutive duplicate words from string, leaving only first words entries.
Example:
Input:
'alpha beta beta gamma gamma gamma delta alpha beta beta gamma gamma gamma delta'
Output:
'alpha beta gamma delta alpha beta gamma delta'
*/
const removeConsecutiveDuplicates = s => {
let str = "";
let words = s.split(" ");
for (let i = 0; i < words.length; i++) {
let curr = words[i];
let folo = words[i+1];
if (curr !== folo) str += curr + " ";
}
return str.trim();
}
|
/**
* A simple store that has predefined data. It uses the {@link Example.model.Kitten}
* model for it's fields definition.
*/
Ext.define('Premio.store.Kittens', {
extend: 'Ext.data.Store',
requires: ['Premio.model.Kitten'],
config: {
model: 'Premio.model.Kitten',
data: [
{ name: 'abdus 1', image: '', cuteness: 70 },
{ name: 'abdus 1', image: '', cuteness: 70 },
{ name: 'abdus 1', image: '', cuteness: 70 },
{ name: 'abdus 1', image: '', cuteness: 70 },
{ name: 'abdus 1', image: '', cuteness: 70 },
{ name: 'abdus 1', image: '', cuteness: 70 }
//../../resources/images/PizzaDetail.png
]
}
});
|
'use strict';
/**
* @ngInject
*/
function OnConfig($stateProvider, $locationProvider, $urlRouterProvider) {
$locationProvider.html5Mode(true);
$stateProvider
.state('Game', {
url: '/',
title: 'Game',
views: {
'game': {
templateUrl: 'game.html',
controller: 'GameCtrl as game'
},
'sidebar': {
templateUrl: 'sidebar.html',
controller: 'SidebarCtrl as sidebar'
}
}
});
$urlRouterProvider.otherwise('/');
}
module.exports = OnConfig; |
$(document).ready(function(){
$('#best_move_button').click(function(){
console.log($('#color :selected').val())
chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {message: "bestMove"});
});
});
}); |
import { RESTDataSource } from "apollo-datasource-rest";
export class NewsAPI extends RESTDataSource {
articleReducer({ source, author, title, url, publishedAt } = {}) {
return {
id: `news-${source.id}`,
title,
author,
url,
time: publishedAt,
source: "News",
};
}
async getAllArticles() {
const result = await this.get(
"https://newsapi.org/v2/top-headlines?country=ng&apiKey=738426735e384909a922a09ef3f2c22f"
);
return result?.articles?.map((article) => this.articleReducer(article));
}
}
|
import "./App.css";
import Header from "./Component/Header";
import { Box, Grid } from "@material-ui/core";
import ProfileStatus from "./Component/ProfileStatus";
import ProfileDetails from "./Component/ProfileDetails";
import GeneralInfo from "./Component/GeneralInfo";
function App() {
return (
<div className="App">
<Box sx={{ flexGrow: 1 }}>
<Grid container spacing={1}>
<Grid item xs={12}>
<item>
<Header />
</item>
</Grid>
<Grid item xs={2}>
<item>
<ProfileStatus />
</item>
</Grid>
<Grid item xs={10}>
<Grid display="flex" container>
<Grid item xs={12}>
<item>
<ProfileDetails />
</item>
</Grid>
<Grid item xs={12}>
<item>
<GeneralInfo />
</item>
</Grid>
</Grid>
</Grid>
</Grid>
</Box>
</div>
);
}
export default App;
|
import React from 'react';
//Does not do much at the moment
const Layout = (props) => {
// const styledChildren = props.children.map((c, i) => {
// console.log(c.props.height);
// const cloneProps = {
// key: i,
// style: {
// height: `${c.props.height}%`
// }
// };
// const clone = React.cloneElement(c, cloneProps);
// return clone;
// });
// return styledChildren;
return props.children;
}
export default Layout; |
var Clan = require('./routes/clan');
var Dashboard = require('./routes/dashboard');
var Event = require('./routes/event');
var Giftcode = require('./routes/giftcode');
var Leaderboard = require('./routes/leaderboard');
var Message = require('./routes/message');
var Tracking = require('./routes/tracking');
var User = require('./routes/user');
var routes = {
clan: new Clan(),
dashboard: new Dashboard(),
event: new Event(),
giftcode: new Giftcode(),
leaderboard: new Leaderboard(),
message: new Message(),
tracking: new Tracking(),
user: new User(),
init: function(app) {
app.get('/auth', this.user.authenticate);
app.get('/clan', this.clan.get);
app.get('/dashboard', this.dashboard.get);
app.get('/event', this.event.get);
app.get('/giftcode', this.giftcode.get);
app.get('/leaderboard', this.leaderboard.get);
app.get('/message', this.message.get);
app.get('/tracking', this.tracking.get);
}
}
module.exports = routes; |
var class_eye_poke_handler =
[
[ "SetEyePokeEnabledState", "d0/d61/class_eye_poke_handler.html#a4e2133c5a000939cf5969d01abed5f50", null ],
[ "Start", "d0/d61/class_eye_poke_handler.html#a9b17c44168a2a33e96881d9745368e8b", null ],
[ "StopMouthMoving", "d0/d61/class_eye_poke_handler.html#a74e5f44df7517892602c705883d27bc6", null ],
[ "Update", "d0/d61/class_eye_poke_handler.html#a9366020ddf70c937b1e1d83a5e69c6f1", null ],
[ "audioClip", "d0/d61/class_eye_poke_handler.html#aad45030bf203d1dcaaea15c721563028", null ],
[ "audioSource", "d0/d61/class_eye_poke_handler.html#ab7e922d08065b97b421b11c99dc0b80b", null ],
[ "EYE_POKE_ENABLED", "d0/d61/class_eye_poke_handler.html#a88fc124e47ea9f73d0d6ac10ab7afffc", null ],
[ "eyelidController", "d0/d61/class_eye_poke_handler.html#a342c1385af69ac8727548597ded6c257", null ],
[ "mouthController", "d0/d61/class_eye_poke_handler.html#ab0828f7b5481ae0abec599b2cc06941e", null ]
]; |
import React, { Component } from 'react';
import { Button, Table, Input, Select, message } from 'antd';
import { Link } from 'react-router';
const Option = Select.Option;
const { TextArea } = Input;
export default class Check extends Component {
constructor(props) {
super(props);
this.state = {
data: null,
loading: false,//归档按钮加载标识
gdFlag: false,//归档意见框、归档按钮的显示隐藏标识(默认是执行(归档)可编辑)
gdValue: "",//归档意见框文本值
gdyj: '',
sup_name:""//供应商名称
}
this.eafId = "";//归档时需要的参数
this.columns = [{
title: '序号',
dataIndex: 'key',
key: 'key',
render: (text, record, index) => (<span>{index + 1}</span>)
}, {
title: '不符合项描述',
dataIndex: 'DESCRIBERSION',
key: 'DESCRIBERSION',
// render: text => <a href="javascript:;"> <Input disabled={true} value={text} /></a>,
render: text => <div> <TextArea autosize={{ minRows: 1, maxRows: 6 }} disabled={true} defaultValue={text} /></div>,
}, {
title: '整改资料',
dataIndex: 'SUP_FILE_NAME',
key: 'SUP_FILE_NAME',
render: (text, record) => <a download target='_blank' href={"http://47.93.29.230:82" + record.SUP_FILE_PATH}>{text}</a>,
}, {
title: '确认情况',
dataIndex: 'CONFIRM_STATUS',
key: 'CONFIRM_STATUS',
//render:text => <a href="javascript:;"> <Input disabled={true} value={text}/></a>
render: (text, record, index) => {
if (text == "1") {
return (
<span>
<Select defaultValue="已完成" style={{ width: 120 }} disabled>
<Option value="1">已完成</Option>
</Select>
</span>
)
} else {
return (
<span>
<Select defaultValue="未完成" style={{ width: 120 }} disabled>
<Option value="0">未完成</Option>
</Select>
</span>
)
}
}
}, {
title: '确认人员',
dataIndex: 'CONFIRM_USER',
key: 'CONFIRM_USER',
render: (text, record) => {
return <a href="javascript:;"> <Input disabled={true} value={text} /></a>
}
}];
}
componentDidMount() {
const _this = this;
const query = JSON.parse(localStorage.obj);
// let url=null;
// // if(query.operation == "执行(流程终止)")
// // 执行(流程终止):归档意见文本框禁用,归档按钮隐藏
// if(query.operation == "执行(流程终止)"){
// this.setState({gdFlag:true});
// url = "/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.checkConformanceInWFEnd&colname=json&refresh=eval(Math.random())colname1={'dataform':'eui_form_data'}";
// }else{//归档 初始化接口
// url = "/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.initSupplierUpload&colname=json&refresh=eval(Math.random())&colname1={'dataform':'eui_datagrid_data'}";
// }
_this.setState({ gdyj: query && query.LINK_STATE ? query.LINK_STATE : '8' });
let url = null;
this.eafId = query.EAF_ID;
const wfInstance = {
"eaf_id": query.EAF_ID
};
// if(query.operation == "执行(查看回执)")
// 执行(查看回执):归档意见文本框禁用,归档按钮隐藏
if (query.operation == "查看") {
this.setState({ gdFlag: true });
url = "/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.checkConformanceInWFEnd&colname=json&refresh=eval(Math.random())&colname1={'dataform':'eui_form_data'}";
// url="/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.inspactionFormAgainDispaly&colname=json&refresh=eval(Math.random())&colname1={'dataform':'eui_form_data'}";
ajax({
url: url,
dataType: "json",
type: "GET",
data: { "wfInstance": JSON.stringify(wfInstance) },
success: function (res) {
console.log(111);
console.log(res);
// console.log(result.result.list);
if (res.EAF_ERROR) {
message.error(res.EAF_ERROR);
return;
}
_this.setState({ data: res.result.list, gdValue: res.result.opinion,sup_name:res.result.sup_name });
},
error: function (res) {
message.error(res.EAF_ERROR);
}
});
} else {//归档 初始化接口
url = "/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.initSupplierUpload&colname=json&refresh=eval(Math.random())&colname1={'dataform':'eui_datagrid_data'}";
ajax({
url: url,
dataType: "json",
type: "GET",
data: { "wfInstance": JSON.stringify(wfInstance) },
success: function (res) {
console.log(res);
if (res.EAF_ERROR) {
message.error(res.EAF_ERROR);
return;
}
_this.setState({ data: res.rows,sup_name:res&&res.rows.length>0?res.rows[0].SUP_NAME:''})
},
error: function (res) {
message.error(res.EAF_ERROR);
}
});
}
}
//归档文本框失焦时获取值
gdBlur = (e) => {
console.log(0);
console.log(e);
this.setState({
gdValue: e.target.value
});
}
// 点击归档,终止流程
handleOk = () => {
if(this.state.gdValue.trim()){
this.setState({
loading: true,
});
const wfInstance = {
"eaf_id": this.eafId,
"archival_opinion": this.state.gdValue.trim()
};
const _this = this;
ajax({
url: "/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.saveArchivalOption&colname=json&refresh=eval(Math.random())&colname1={'dataform':'eui_form_data'}",
dataType: "json",
type: "GET",
data: { "wfInstance": JSON.stringify(wfInstance) },
success: function (result) {
console.log(result);
if (result.EAF_ERROR) {
message.error(result.EAF_ERROR);
return;
}
// _this.setState({data:result})
message.success("归档成功");
window.location.href = "#Supervision";
},
error: function (res) {
message.error(res.EAF_ERROR);
}
});
}else{
message.warning('归档意见不能为空');
}
}
render() {
const data = this.state.data && this.state.data ? this.state.data : [];
const loading = this.state.data;
return (
<div>
<h1 style={{ textAlign: "center", fontWeight: "bold" }}>{this.state.sup_name}不符合项整改完成情况表</h1>
<div style={{ textAlign: "right" }}>
<Link style={{ marginRight: "10px" }} to={{ pathname: "PlanDetail", query: {EAF_ID:JSON.parse(localStorage.obj).EAF_ID }}}>监督计划</Link>
<Link to={{ pathname: "EveryBranch", query: {EAF_ID:JSON.parse(localStorage.obj).EAF_ID }}}>各部门执行</Link>
</div>
<Table loading={!loading} rowKey={record => record.EAF_ID} columns={this.columns} pagination={false} dataSource={data} />
{/*
{(this.state.gdyj == "8" || this.state.gdyj == "9") ? <h3 style={{ margin: '1%' }}>归档意见</h3> : null}
*/}
<h3 style={{ margin: '1%' }}>归档意见</h3>
<div id="gdyj">
{(this.state.gdFlag || this.state.gdyj == "9"
?
<TextArea maxLength="200" rows="7" value={this.state.gdValue} disabled={true} />
:
(this.state.gdyj == "8" ? <TextArea maxLength="200" rows="7" onBlur={this.gdBlur} /> : null)
)
}
</div>
<div style={{ textAlign: "center", marginTop: 20 }}>
<Button type="primary" loading={this.state.loading} onClick={this.handleOk} style={{ marginRight: 30, display: this.state.gdFlag ? "none" : "inline-block" }}>
归档
</Button>
{/*
<Button type="primary" loading={this.state.loading} onClick={this.handleOk} style={{marginRight:30}}>
归档
</Button>
*/}
<Link to="Supervision">
<Button type="default" htmlType="submit">
返回
</Button>
</Link>
</div>
</div>
)
}
}
|
'use strickt';
let clock = document.getElementById("clock");
let color = document.getElementById("color");
function getTime() {
let time = new Date();
let h = time.getHours();
let m = time.getMinutes().toString().length < 2 ? "0" + time.getMinutes().toString() : time.getMinutes().toString();
let s = time.getSeconds();
let array = [h,m,s];
return array;
}
function out(array) {
console.log(array);
}
function changeTime(array) {
let innerArray = array;
console.log("Такие пироги " + innerArray);
clock.textContent = innerArray[0] + ":" + innerArray[1] + ":" + innerArray[2];
color.textContent = "#" + innerArray[0] + innerArray[1] + innerArray[2];
document.body.style.background = color.textContent;
}
setInterval(changeTime(getTime()), 1);
|
var name;
var track;
var achievements;
var points;
var student;
var message;
var search;
var searchTrack;
var on = true;
function print(message){
var output = document.getElementById('output');
output.innerHTML = message;
}
function getStudentReport(student){
var report = "<h2>Name: " + student.name + "</h2>";
report += "<p>track: " + student.track + "</p>";
report += "<p>achievements: " + student.achievements + "</p>";
report += "<p>Points: " + student.points + "</p>";
return report;
}
while(true){
search = prompt("Choose a name?");
if(search === null || search.toLowerCase() === 'quit'){
break;
}
for(var i = 0; i < students.length; i++){
student = students[i];
if(student.name === search){
message = getStudentReport(student);
print(message);
}
// two names
// if there isn't a name found
// // console.log(students[i]);
// print(message);
}
}
// function fetchStudent(students){
// for(var i = 0; i < students.length; i++){
// student = students[i];
// // console.log(students[i]);
// message += "<h2>Name: " + student.name + "</h2>";
// message += "<p>track: " + student.track + "</p>";
// message += "<p>achievements: " + student.achievements + "</p>";
// message += "<p>Points: " + student.points + "</p>";
// }
// return message;
// }
// fetchStudent(students);
print(message);
// for(var i = 0; i < students.length; i++){
// student = students[i]
// // name = students[i].name;
// // track = students[i].track;
// // achievements = students[i].achievements;
// // points = students[i].points;
//
// // message += "<h2>name: " + name + "</h2>";
// // message += "<p>track: " + track + "</p>";
// // message += "<p>achievements: " + achievements + "</p>";
// // message += "<p>points: " + points+ "</p>";
//
// /// daves work
// message += "<h2>name: " + student.name + "</h2>";
// message += "<p>track: " + student.track + "</p>";
// message += "<p>achievements: " + student.achievements + "</p>";
// message += "<p>points: " + student.points+ "</p>";
//
// }
// print(message);
// html = "<p>" + name + "</p>";
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// document.write(html);
|
import express from 'express';
import methods from './methods';
import validation from './validation';
const router = express.Router();
// Routing for the resource
router.get('/', validation.getList, methods.getList);
router.get('/:userId', validation.get, methods.get);
export default router;
|
'use strict';
function Promise(fn){
let value = null,
deferreds = [],
state = 'pending',
handle = (deferred)=>{
if(state == 'pending'){
deferreds.push(deferred);
return;
}
var ret = deferred.onFulfilled(value);
deferred.resolve(ret);
},
resolve = (newValue)=>{
if(newValue && typeof newValue === 'objcet' || typeof newValue === 'function'){
var then = newValue.then;
if(typeof then === 'function'){
then.call(newValue,resolve);
return;
}
}
state = 'fulfilled';
value = newValue;
setTimeout(()=>deferreds.forEach(deferred=>handle(deferred)),0);
};
this.then = onFulfilled => new Promise(resolve=>handle({onFulfilled,resolve}))
fn(resolve);
}
new Promise(resolve=>{
setTimeout(()=>{
console.log('timeout done!');
resolve();
},3000);
}).then(()=>{
return new Promise(function (resolve) {
setTimeout(()=>{
console.log('1 timeout then');
resolve();
})
},4000);
}).then(()=>{
return new Promise(function (resolve) {
setTimeout(()=>{
console.log('2 timeout then');
resolve();
})
},1000);
}).then(()=>{
console.log('3 timeout then');
}) |
import React, {useState, useEffect} from "react"
import {StyleSheet, ScrollView} from "react-native";
import LikeCard from '../components/LikeCard';
import Loading from '../components/Loading';
import {firebase_db} from '../firebaseConfig';
import Constants from 'expo-constants';
export default function LikePage({navigation}) {
const [tip, setTip] = useState([])
const [ready,setReady] = useState(true)
useEffect(()=>{
navigation.setOptions({
title: "꿀팁 찜",
})
const user_id = Constants.installationId;
firebase_db.ref('/like/'+user_id).once('value').then((snapshot) => {
console.log("파이어베이스에서 데이터 가져왔습니다!!")
let tip = snapshot.val();
console.log(tip)
let tip_list = Object.values(tip)
if(tip_list.length > 0){
setTip(tip_list)
setReady(false)
}
})
},[])
const reload = () => {
const user_id = Constants.installationId;
firebase_db.ref('/like/'+user_id).once('value').then((snapshot) => {
if(snapshot.exists()){
let tip = snapshot.val();
let tip_list = Object.values(tip)
setTip(tip_list)
}else{
setReady(true)
setTip([])
}
})
}
return ready ? <Loading /> : (
<ScrollView style={styles.cardContainer}>
{
tip.map((tipItems,i)=>{
return ( <LikeCard content={tipItems} reload={reload} key={i} navigation={navigation}/> )
})
}
</ScrollView>
)
}
const styles = StyleSheet.create({
cardContainer: {
backgroundColor: "#fff",
},
}) |
import React, { useState, useEffect } from "react";
import { useParams } from "react-router";
import Layout from "../components/layout.jsx";
import DetailsLayout from "../components/detailsLayout.jsx";
import conf from '../configs/user.js';
import axios from '../utils/axios.js';
export default function User(props){
const { organization_id, user_id } = useParams();
const [deletable, setDeletabel] = useState(false);
const [updatable, setUpdatable] = useState(false);
useEffect(async () => {
try {
const res = await axios.get(`/api/admin/organization/${organization_id}/role`);
res.data.forEach((role) => {
switch(role){
case 'update':
setUpdatable(true);
break;
case 'delete':
setDeletabel(true);
break;
}
});
} catch(err) {
alert(err);
}
}, []);
return (
<Layout header="User">
<DetailsLayout
apiPath={`/api/admin/organization/${organization_id}/user/${user_id}`}
disabled={!updatable}
conf={conf}
delete={deletable}
root={`/organization/${organization_id}`}
hash="#users"
/>
</Layout>
)
} |
import React from 'react';
import './Dashboard.css';
import employeeList from "../data/EmployeeList.json";
import Employee from './Employee';
function DashboardPage() {
return (
<div className="employeeContainer">
{Object.keys(employeeList.user).map((key)=>{
return <Employee employee ={employeeList.user[key]} key={employeeList.user[key].id}/>
})}
</div>
);
}
export default DashboardPage; |
import React from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
import * as constants from "@paprika/constants/lib/Constants";
import * as sc from "./Textarea.styles";
const Textarea = React.forwardRef((props, ref) => {
const textareaRef = React.useRef(null);
const resize = () => {
if (textareaRef.current && textareaRef.current.style) {
textareaRef.current.style.height = 0;
textareaRef.current.style.height = `${textareaRef.current.scrollHeight + 2}px`;
}
};
const {
a11yText,
className,
canExpand,
hasError,
isDisabled,
onChange,
isReadOnly,
maxHeight,
size,
...moreProps
} = props;
React.useEffect(() => {
if (canExpand) {
resize();
window.addEventListener("resize", resize);
}
return function cleanup() {
window.removeEventListener("resize", resize);
};
}, []);
React.useEffect(() => {
if (canExpand) {
resize();
}
}, [canExpand]);
const setRef = node => {
textareaRef.current = node;
if (ref) {
ref(node);
}
};
if (moreProps.value) {
delete moreProps.defaultValue;
} else {
delete moreProps.value;
}
const handleChange = e => {
if (canExpand) {
resize();
}
onChange(e);
};
if (a11yText) moreProps["aria-label"] = a11yText;
const rootClasses = classNames(
"form-textarea",
`form-textarea--${size}`,
{ "form-textarea--is-disabled": isDisabled },
{ "form-textarea--is-readonly": isReadOnly },
{ "form-textarea--has-error": hasError },
className
);
return (
<sc.Textarea className={rootClasses}>
<textarea
aria-invalid={hasError}
className="form-textarea__textarea"
data-pka-anchor="textarea"
disabled={isDisabled}
readOnly={isReadOnly}
onChange={handleChange}
ref={setRef}
style={{ maxHeight }}
{...moreProps}
/>
</sc.Textarea>
);
});
Textarea.types = {
size: constants.defaultSize,
};
const propTypes = {
/** Descriptive a11y text for assistive technologies. By default, text from children node will be used. */
a11yText: PropTypes.string,
/** Indicate if the textarea is expandable */
canExpand: PropTypes.bool,
/** Sets class name */
className: PropTypes.string,
/** Do not use in conjunction with value prop */
defaultValue: PropTypes.string,
hasError: PropTypes.bool,
/** If the textarea is disabled */
isDisabled: PropTypes.bool,
/** If the textarea is read-only */
isReadOnly: PropTypes.bool,
/** Indicates the maximum height of the textarea */
maxHeight: PropTypes.string,
onChange: PropTypes.func,
size: PropTypes.oneOf([Textarea.types.size.SMALL, Textarea.types.size.MEDIUM, Textarea.types.size.LARGE]),
/** Do not use in conjunction with defaultValue prop */
value: PropTypes.string,
};
const defaultProps = {
a11yText: null,
canExpand: true,
className: null,
defaultValue: "",
hasError: false,
isDisabled: false,
isReadOnly: false,
maxHeight: "300px",
onChange: () => {},
size: Textarea.types.size.MEDIUM,
value: null,
};
Textarea.displayName = "Textarea";
Textarea.propTypes = propTypes;
Textarea.defaultProps = defaultProps;
export default Textarea;
|
function rm2SafeMode() {
var walls = Game.rooms.W5S18.find(FIND_STRUCTURES, {
filter: (s) => (s.structureType == STRUCTURE_WALL || s.structureType == STRUCTURE_RAMPART) && s.hits < 100
});
var t = Game.getObjectById('605821ec0c8afa45c192ab92');
var enemiesInRoom = t.pos.findInRange(FIND_HOSTILE_CREEPS, 40);
//console.log(enemiesInRoom.length);
//console.log(walls.length);
if(enemiesInRoom.length >= 1 && walls.length >= 1){
Game.rooms.W5S18.controller.activateSafeMode();
console.log('Activating safe mode in rm2, under attack.');
}
};
function rm1SafeMode(){
var walls = Game.rooms.W6S18.find(FIND_STRUCTURES, {
filter: (s) => (s.structureType == STRUCTURE_WALL || s.structureType == STRUCTURE_RAMPART) && s.hits < 100
});
var t = Game.getObjectById('6052d875d79c931c5a37c3df');
var enemiesInRoom = t.pos.findInRange(FIND_HOSTILE_CREEPS, 40);
if(enemiesInRoom.length >= 1 && walls.length >= 1){
Game.rooms.W6S18.controller.activateSafeMode();
console.log('Activating safe mode in rm1, under attack.');
}
}
module.exports.rm1 = rm1SafeMode;
module.exports.rm2 = rm2SafeMode; |
Content.makeFrontInterface(568, 320);
//declarations
const var Label1 = Content.getComponent("Label1");
const var Panel2 = Content.getComponent("Panel2");
const var Panel3 = Content.getComponent("Panel3");
//sampler
const var sampleList = Sampler.getSampleMapList();
const var sampler1 = Synth.getSampler("Sampler1");
const var sampler2 = Synth.getSampler("Sampler2");
//combobox
const var ComboBox1 = Content.getComponent("ComboBox1");
Content.getComponent("ComboBox1").set("text","...");
inline function onComboBox1Control(component, value)
{
if(ComboBox1.getItemText() == "..."){
blank();
Content.getComponent("Label1").set("text","Kalinga Instruments");
}
else{
if(ComboBox1.getItemText() == "Tongali") tongali();
if(ComboBox1.getItemText() == "Kolitong") kolitong();
Content.getComponent("Label1").set("text",ComboBox1.getItemText());
};
}
Content.getComponent("ComboBox1").setControlCallback(onComboBox1Control);
//instrument functions
function tongali(){
Panel2.showControl(1);
Panel3.showControl(0);
sampler1.loadSampleMap("tongali");
sampler2.loadSampleMap("blanco");
}
function kolitong(){
Panel2.showControl(0);
Panel3.showControl(1);
sampler1.loadSampleMap("blanko");
sampler2.loadSampleMap("kolitong");
}
function blank(){
Panel2.showControl(0);
Panel3.showControl(0);
}function onNoteOn()
{
}
function onNoteOff()
{
}
function onController()
{
}
function onTimer()
{
}
function onControl(number, value)
{
}
|
import "./index.css";
class BreadCrumbs {
constructor(props) {
this.breadCrumbWrapper = document.createElement("div");
this.listBreadCrumb = [...props.listBreadCrumb];
this.OnSelected = props.onSelected;
}
getCurrentBreadCrumb() {
return this.listBreadCrumb[this.listBreadCrumb.length - 1];
}
getPreviousBreadCrum() {
return this.listBreadCrumb[this.listBreadCrumb.length - 2];
}
reRenderBreadCrumb() {
this.resetBreadCrumb();
this.renderItemBreadCrumb();
this.removeLastArrow();
}
resetBreadCrumb() {
let childBreadcrumb = this.breadCrumbWrapper.children;
for (let i = childBreadcrumb.length - 1; i >= 0; i--) {
this.breadCrumbWrapper.removeChild(childBreadcrumb[i]);
}
}
removeLastArrow() {
let elmChildWrap = this.breadCrumbWrapper.children;
let elmLastArrow = elmChildWrap[elmChildWrap.length - 1];
let isLastArrowExist = elmLastArrow && elmLastArrow.children[1];
if (isLastArrowExist) {
elmLastArrow.removeChild(elmLastArrow.children[1]);
}
}
removeBreadCrumb(elmNameAndArrow) {
let elmIndex = [...this.breadCrumbWrapper.children].indexOf(elmNameAndArrow);
let elmChildWrapper = this.breadCrumbWrapper.children;
for (let i = elmChildWrapper.length - 1; i >= 0; i--) {
if (i > elmIndex) {
this.breadCrumbWrapper.removeChild(elmChildWrapper[i]);
}
}
}
addBreadCrumb(id, name) {
this.listBreadCrumb.push({ id, name });
this.reRenderBreadCrumb();
}
handleSelect(elmNameAndArrow, breadCrumId) {
this.removeBreadCrumb(elmNameAndArrow, breadCrumId);
this.removeLastArrow();
let indexBreadCrumb = this.listBreadCrumb.findIndex(breadCrumb => breadCrumb.id === breadCrumId);
let newListBreadCrumb = this.listBreadCrumb.slice(0, indexBreadCrumb + 1);
this.listBreadCrumb = newListBreadCrumb;
let currentBreadCrumb = this.getCurrentBreadCrumb();
this.OnSelected(currentBreadCrumb);
}
renderArrow(nameAndArrow, folder) {
let arrowRight = document.createElement("div");
arrowRight.textContent = ">";
let isNotLastElm = folder.id !== this.listBreadCrumb.length - 1;
if (isNotLastElm) {
nameAndArrow.appendChild(arrowRight);
}
}
renderItemBreadCrumb() {
if (this.listBreadCrumb && this.listBreadCrumb.length === 0) {
return;
}
this.listBreadCrumb.map(breadCrumb => {
let nameAndArrow = document.createElement("div");
nameAndArrow.className = "name-arrow";
let elmFolderName = document.createElement("div");
elmFolderName.className = "bread-crumb-name";
elmFolderName.textContent = breadCrumb.name;
nameAndArrow.appendChild(elmFolderName);
this.renderArrow(nameAndArrow, breadCrumb);
elmFolderName.onclick = () => this.handleSelect(nameAndArrow, breadCrumb.id);
this.breadCrumbWrapper.appendChild(nameAndArrow);
});
}
render() {
this.breadCrumbWrapper.className = "bread-crumb-wrap";
this.renderItemBreadCrumb();
this.removeLastArrow();
return this.breadCrumbWrapper;
}
}
export default BreadCrumbs;
|
/* global: window.ChessBoard */
import { Meteor } from 'meteor/meteor'
import { $ } from 'meteor/jquery'
import React from 'react'
import { Antares } from '/imports/antares/'
import Actions from '/imports/antares/actions'
const chessboardId = 'chessboard-js'
let rebindChessBoard = ({ game, orientation }) => {
let { position } = game
new window.ChessBoard(chessboardId, {
draggable: true,
position: position,
orientation: orientation.toLowerCase(),
onDrop: (from, to) => {
if (from === to || (to === 'offboard')) { return }
Antares.announce(Actions.Game.move({ from, to }))
}
})
}
export default class ChessBoard extends React.Component {
render() {
return (
<div>
<div id={ chessboardId } style={ {width: 450} }></div>
</div>
)
}
// Lifecycle hooks to initialize the 3rd party chess lib the first, and later times
componentDidMount() {
rebindChessBoard(this.props)
}
componentDidUpdate() {
rebindChessBoard(this.props)
}
}
|
var mongoose = require('mongoose');
var express = require("express");
var app = express();
var cors = require("./config/cors");
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(cors);
const passport = require("passport");
app.use(passport.initialize());
app.use(passport.session());
require("./config/passport")(passport);
mongoose.connect('mongodb://localhost:27017', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: true
}).then(() => console.log('connection successful'))
.catch((err) => console.error(err));
var friend = require("./routes/friend");
var auth = require("./routes/auth");
var profile = require("./routes/profile");
var search = require("./routes/search");
var request = require("./routes/friendRequest");
//********************************************************************** */
// Auth related
app.post('/auth/login', auth.login);
app.post('/auth/register', auth.register);
// Profile related
app.get('/profile',passport.authenticate('jwt', { session : false}), profile.get);
app.post('/profile', passport.authenticate('jwt', { session: false }), profile.post);
app.get('/search', passport.authenticate('jwt', { session: false }), search.get);
// Friends related
app.get('/friends',passport.authenticate('jwt', { session : false}), friend.getFriends);
app.post('/friends/remove/:friend_id', friend.removeFriend);
app.post('/friends', passport.authenticate('jwt', { session : false}), friend.post);
app.get('/friendrequest', passport.authenticate('jwt', { session: false }), request.get);
app.post('/friendrequest/:user_id', passport.authenticate('jwt', { session: false }), request.post);
app.post('/friendrequest/removerequest/:id', passport.authenticate('jwt', { session: false }),request.delete);
var port = 4020;
app.listen(port, () => {
console.log("Le serveur est opérationnel sur le numéro de port" + port);
});
|
jQuery(document).ready(function () {
jQuery("#block-menu-menu-iseek3-main-menu > ul.nav > li.leaf:nth-child(6) > a").click(function (e) {
e.preventDefault();
e.stopPropagation();
jQuery('#toolkit-anchor').ScrollTo({
duration: 0,
easing: 'linear'
});
});
});
|
export default {
player: 'html5-video-player',
mainContainer: 'video-container'
}
|
import AuthService from "./service";
import BaseResponse from "../../middleware/base-response";
import BasicAuthMiddleware from "../../middleware/basic-auth";
export default class AuthController extends BaseResponse {
login = async (req, res) => {
const { login, password } = req.body;
try {
const user = await AuthService.login(login, password);
const token = await BasicAuthMiddleware.generateToken(
user.login,
password
);
await this.response(null, res, {
token,
user
});
} catch (e) {
await this.response(e, res, null);
}
};
test = async (req, res) => {
await this.response(null, res, {
vasya: "vvv"
});
};
}
|
import React from 'react'
import './SideStories.css'
function SideStories() {
return (
<div className="side-area">
<div className="top-side">
<h3 className="side-story-headline">
How Toyota Went From Making the Prius to Resisting an All-Electric Push
</h3>
<p className="paragraph">
The auto giant bet on hydrogen power, but as the world moves toward electric cars, the company is fighting regulations in an apparent effort to buy time.
</p>
</div>
<div className="bottom-side">
<h3 className="side-story-headline">
Scorching Temperatures are Forecast for the Great Plains and the Midwest this week. Follow extreme weather updates.
</h3>
</div>
</div>
)
}
export default SideStories
|
const mongoose = require("mongoose");
// import country model
const Country = mongoose.model("countries");
// function to handle a request to get all countries
const getAllCountries = async (req, res) => {
try {
const all_countries = await Country.find();
res.render('countries.pug', {
title: 'Country List',
countries: all_countries
});
} catch (err) {
res.status(400);
return res.send("Database query failed");
}
};
// remember to export the functions
module.exports = {
getAllCountries
};
|
// Used to toggle the menu on small screens when clicking on the menu button
function myFunction() {
var x = document.getElementById("navDemo");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
} else {
x.className = x.className.replace(" w3-show", "");
}
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('timeDisplay').innerHTML =
h + ":" + m + ":" + s;
var timers = document.getElementsByClassName('timer');
for (var x=0; x<timers.length; x++){
timers[x].innerHTML = 24-h + " hours and " + (60-m) + " minutes and " + (60-s) + " seconds left" ;
}
var t = setTimeout(startTime, 500);
if (h=="00" && m=="00"){
loopNodesList();
}
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
var xhttp = new XMLHttpRequest();
var xmlDoc;
var nodesLengthList = [];
var books = ["BAN", "DA", "CG", "CD", "Ed", "1MCP", "2MCP", "PP", "PK", "AA", "MH", "GC", "LDE", "POLITICS", "SPORTS", "CL"];
var bookTitles = [];
bookTitles.push("Birthdays, Anniversaries, New Year");
bookTitles.push("Desire of Ages");
bookTitles.push("Child Guidance");
bookTitles.push("Counsels on Diets and Foods");
bookTitles.push("Education");
bookTitles.push("Mind, Character and Personality Volume 1");
bookTitles.push("Mind, Character and Personality Volume 2");
bookTitles.push("Patriarchs and Prophets");
bookTitles.push("Prophets and Kings");
bookTitles.push("Acts of the Apostles");
bookTitles.push("Ministry of Healing");
bookTitles.push("Great Controversy");
bookTitles.push("Last Day Events");
bookTitles.push("Politics");
bookTitles.push("Sports");
bookTitles.push("Country Living");
var startingDates = [];
var daDate = new Date(2016, 11, 30, 14, 45, 0, 0);
var otherDates = new Date(2018, 5, 22, 14, 45, 0, 0);
startingDates.push(otherDates); //BAN
startingDates.push(daDate); //DA
startingDates.push(otherDates); //CD
startingDates.push(otherDates); //CG
startingDates.push(otherDates); //Ed
startingDates.push(otherDates); //1MCP
startingDates.push(otherDates); //2MCP
startingDates.push(otherDates); //PP
startingDates.push(otherDates); //PK
startingDates.push(otherDates); //AA
startingDates.push(otherDates); //MH
startingDates.push(otherDates); //GC
startingDates.push(otherDates); //LDE
startingDates.push(otherDates); //Politics
startingDates.push(otherDates); //Sports
startingDates.push(otherDates); //Country Living
var nodesList = [];
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// // Typical action to be performed when the document is ready:
xmlDoc = xhttp.responseXML;
loadNodesList();
loopNodesList();
}
document.getElementById("error").innerHTML = this.status.toString();
};
xhttp.open("GET", "test.xml", true);
xhttp.send();
function loadNodesList() {
try{
for (var i=0; i<books.length; i++){
getBook(i);
}
} catch(err) {
document.getElementById("error").innerHTML = err.message;
}
}
function getBook(bookIndex){
try{
var book = books[bookIndex];
var path = "//egw//item[@code='"+book+"']";
var nodes = xmlDoc.evaluate(path, xmlDoc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var length = nodes.snapshotLength;
var paragraphs = [];
for (var i=0; i<nodes.snapshotLength; i++){
var bookSource = nodes.snapshotItem(i).childNodes[0].parentElement.getAttribute("source");
var pageNumber = nodes.snapshotItem(i).childNodes[0].parentElement.getAttribute("page");
var paragraphNumber = nodes.snapshotItem(i).childNodes[0].parentElement.getAttribute("paragraph");
var word = nodes.snapshotItem(i).childNodes[0].nodeValue;
var full = word + " (" + bookSource + ", page " + pageNumber + ", paragraph " + paragraphNumber + ")";
paragraphs.push(full);
}
nodesLengthList.push(length);
nodesList.push(paragraphs);
}
catch(err) {
document.getElementById("error").innerHTML = err.message;
}
}
function loopNodesList(){
var txt ="";
txt += "<hr>";
try{
for (var i=0;i<nodesList.length; i++){
var paragraph = displayMinuteParagraph(i);
txt+= paragraph;
}
document.getElementById("paragraphDisplay").innerHTML = txt;
} catch(err) {
document.getElementById("error").innerHTML = err.message;
}
}
function displayMinuteParagraph(nodesIndex){
try{
var txt = "";
var total = nodesLengthList[nodesIndex];
var currentID = getCurrentID(total, nodesIndex);
// document.getElementById("currentID").innerHTML = currentID;
var heading = bookTitles[nodesIndex];
var word = nodesList[nodesIndex][currentID];
var title = "<h1>" + heading + "</h1><p class='timer'></p>";
var counter = "<p>" + currentID + " of " + total + " paragraphs </p>";
txt += title + "<div id='"+nodesIndex +"'>" + counter + word + "<br><br>";
var previousParagraph = "previousParagraph(";
previousParagraph += nodesIndex + "," + currentID;
previousParagraph += ")";
var nextParagraph = "nextParagraph(";
nextParagraph += nodesIndex + "," + currentID;
nextParagraph += ")";
txt += "<button onclick='"+previousParagraph+"'>previous</button>";
txt += "<button onclick='"+nextParagraph+"'>next</button>";
txt += "<hr></div>";
return txt;
}
catch(err) {
document.getElementById("error").innerHTML = err.message;
}
}
function previousParagraph(nodesIndex, currentID){
try{
var txt = "";
var total = nodesLengthList[nodesIndex];
var currentID = currentID - 1;
// document.getElementById("currentID").innerHTML = currentID;
var heading = bookTitles[nodesIndex];
var word = nodesList[nodesIndex][currentID];
// var title = "<h1>" + heading + "</h1><p class='timer'></p>";
var counter = "<p>" + currentID + " of " + total + " paragraphs </p>";
txt += "<div id='"+nodesIndex +"'>" + counter + word + "<br><br>";
var previousParagraph = "previousParagraph(";
previousParagraph += nodesIndex + "," + currentID;
previousParagraph += ")";
var nextParagraph = "nextParagraph(";
nextParagraph += nodesIndex + "," + currentID;
nextParagraph += ")";
txt += "<button onclick='"+previousParagraph+"'>previous</button>";
txt += "<button onclick='"+nextParagraph+"'>next</button>";
txt += "<hr></div>";
document.getElementById(nodesIndex).innerHTML = txt;
}
catch(err) {
document.getElementById("error").innerHTML = err.message;
}
}
function nextParagraph(nodesIndex, currentID){
try{
var txt = "";
var total = nodesLengthList[nodesIndex];
var currentID = currentID + 1;
// document.getElementById("currentID").innerHTML = currentID;
var heading = bookTitles[nodesIndex];
var word = nodesList[nodesIndex][currentID];
// var title = "<h1>" + heading + "</h1><p class='timer'></p>";
var counter = "<p>" + currentID + " of " + total + " paragraphs </p>";
txt += "<div id='"+nodesIndex +"'>" + counter + word + "<br><br>";
var previousParagraph = "previousParagraph(";
previousParagraph += nodesIndex + "," + currentID;
previousParagraph += ")";
var nextParagraph = "nextParagraph(";
nextParagraph += nodesIndex + "," + currentID;
nextParagraph += ")";
txt += "<button onclick='"+previousParagraph+"'>previous</button>";
txt += "<button onclick='"+nextParagraph+"'>next</button>";
txt += "<hr></div>";
document.getElementById(nodesIndex).innerHTML = txt;
}
catch(err) {
document.getElementById("error").innerHTML = err.message;
}
}
function getCurrentID(totalVerses, dateIndex){
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var date1 = new Date();
var year = date1.getFullYear();
var month = date1.getMonth();
var day = date1.getDate();
document.getElementById("dateDisplay").innerHTML = monthNames[month] + " " + day + ", " + year;
var date2 = startingDates[dateIndex];
var difference = date1.getTime() - date2.getTime();
var minutesDifference = Math.floor(difference/1000/60/60/24);
var currentID=minutesDifference;
// difference -= minutesDifference*1000*60;
while (currentID > totalVerses){
currentID = currentID - totalVerses;
}
// document.getElementById("demo").innerHTML = "hello";
// }
// catch (e) {
// document.getElementById("demo").innerHTML = "hello1";
//
//
return currentID;
}
|
/**
* This is the navigator you will modify to display the logged-in screens of your app.
* You can use RootNavigator to also display an auth flow or other user flows.
*
* You'll likely spend most of your time in this file.
*/
import React from 'react';
import {
Text,
StyleSheet,
TouchableOpacity,
View,
SafeAreaView,
} from 'react-native';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {responsive} from '@/utils';
import {color} from '@/theme';
import {palette} from '@/theme/palette';
import {useIsLoggedIn} from '@/hooks/useIsLoggedIn';
const BOTTOM_TAB_BAR_HEIGHT = responsive.getHeight(50);
const Tab = createBottomTabNavigator();
const TAB_BAR_NAMES = Object.freeze({});
const styles = StyleSheet.create({
badge: {
alignItems: 'center',
backgroundColor: color.error,
borderRadius: 20,
height: 20,
justifyContent: 'center',
position: 'absolute',
right: 3,
top: 0,
width: 20,
},
badgeTx: {
color: color.palette.white,
fontSize: 10,
fontWeight: '600',
marginLeft: 1,
},
img1: {
height: responsive.getWidth(20),
width: responsive.getWidth(20),
},
img2: {
height: responsive.getWidth(40),
width: responsive.getWidth(40),
},
tabBarButton: {alignItems: 'center', flex: 1},
tabBarContent: {
alignItems: 'center',
flexDirection: 'row',
height: BOTTOM_TAB_BAR_HEIGHT,
},
tabBarItem1: {alignItems: 'center'},
tabBarLabel: {
color: palette.grey,
marginTop: 4,
fontSize: 11,
},
tabBarRoot: {
backgroundColor: 'white',
height: 70,
},
focusedStyle: {
color: palette.primary,
},
});
const ICON_SIZE = responsive.getFontSize(25);
const TabBarItem = props => {
const {name, icon, isFocused} = props;
const iconColor = isFocused ? palette.primary : palette.grey;
return (
<View style={styles.tabBarItem1}>
<MaterialCommunityIcons color={iconColor} name={icon} size={ICON_SIZE} />
<Text style={styles.tabBarLabel}>{name}</Text>
</View>
);
};
const TabBarButton = props => {
const {state, descriptors, navigation} = props;
return (
<SafeAreaView style={styles.tabBarRoot}>
<View style={styles.tabBarContent}>
{state.routes.map((route, index) => {
const {options} = descriptors[route.key];
const isFocused = state.index === index;
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key,
canPreventDefault: true,
});
if (!isFocused && !event.defaultPrevented) {
navigation.navigate(route.name);
}
};
const barItem = () => {
switch (index) {
//Tab bar item here
default:
return null;
}
};
return (
<TouchableOpacity
key={index}
accessibilityRole="button"
accessibilityState={isFocused ? {selected: true} : {}}
accessibilityLabel={options.tabBarAccessibilityLabel}
testID={options.tabBarTestID}
onPress={onPress}
style={styles.tabBarButton}>
{barItem()}
</TouchableOpacity>
);
})}
</View>
</SafeAreaView>
);
};
/**
* All Tab bar below.
*/
export function MainTabBar() {
const {isLoggedIn} = useIsLoggedIn();
return (
<Tab.Navigator tabBar={TabBarButton}>
</Tab.Navigator>
);
}
|
import React from 'react'
import SubNav from "./subNav";
import MyVideo from "./myVideo";
import MyColumn from "./myColumn";
import MyFavorite from "./myFavorite";
import MyPhoto from "./myPhoto";
import MyInfo from "./myInfo";
import '../css/main.scss'
import MyData from "./myData";
import Post from "./post";
import renzheng from '../static/home/小图标/个人认证1.psd.png'
import Dianliang from "./dianliang";
import goTop from '../static/home/回到顶部.png'
class Main extends React.Component{
render() {
return(
<div id={'background'}>
<div id={'mainContainer'}>
<div className={'main'}>
<SubNav />
<MyVideo />
<MyColumn />
<MyFavorite />
<MyPhoto />
</div>
<div id={'sidebar'}>
<MyInfo />
<MyData />
<Post />
<div className={'renzheng'}>
<p><img src={renzheng} alt={'jj'}/>bilibili个人认证:bilibili 2018百大UP主、高能联盟成员</p>
</div>
<Dianliang />
<div className={'myLive'}>
<h2>我的直播间</h2>
<a id={'myLiveOpen'} href={'/'}>开启</a>
<p id={'myLiveBottom'}><a href={'/'}>查看往期直播</a></p>
</div>
<img src={goTop} alt={'eer'} id={'goTop'}/>
</div>
</div>
</div>
);
}
}
export default Main |
import React, { useReducer } from 'react';
import { authReducer, initialState } from '../reducers/authReducer';
import { login,logout } from '../actions/authAction';
export const Login = () => {
const[state, dispatch] = useReducer(authReducer, initialState)
return (
<div>
<h1>Login</h1>
<hr />
<button
className="btn btn-primary"
onClick={()=>dispatch(login('123456','Anlli Gallardo'))}
>
Login
</button>
<button
className="btn btn-danger"
onClick={()=>dispatch(logout())}
>
Logout
</button>
</div>
)
} |
'use strict';
/**
* @ngdoc function
* @name githubExplorerApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the githubExplorerApp
*/
angular.module('githubExplorerApp')
.controller('MainCtrl', function ($scope, $location) {
var _parseRepo = function(repoStr) {
repoStr = repoStr.replace('https://github.com/', '');
return repoStr;
};
$scope.getRepo = function () {
$location.path('/repos/' + _parseRepo($scope.repo));
};
});
|
/**
* Using the useTransition for locking a button while waiting a result and not locking the UI
* @module Experiences/Experience2
*/
import React, { useTransition, useState, Suspense } from 'react'
import { dataFetcher } from '@services/FakeApi'
const initialData = {
read: () => {
return { foo: 'initial' }
}
}
/**
* @function Experience
* Try clicking on the first button and then interacting with the second one
* @return {Object} Return the dom
*/
const Experience = () => {
const [data, setData] = useState(initialData)
const [count, setCount] = useState(0)
const [isPending, startTransition] = useTransition({
timeoutMs: 3000
})
return (
<>
<Suspense fallback={<p>Loading...</p>}>
<button
disabled={isPending}
onClick={() =>
startTransition(() => {
setData(dataFetcher())
})
}
>
Increment
</button>
<div>{data?.read()?.foo}</div>
</Suspense>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
<div>{count}</div>
</>
)
}
export default Experience
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Constraint= Matter.Constraint
var bob1
var bob2
var bob3
var bob4
var bob5
var rope1,rope2,rope3,rope4
var holder1,holder2,holder3,holder4
var f
function setup() {
createCanvas(800, 700);
f=true
engine = Engine.create();
world = engine.world;
bob1= new Bob(200,500,false)
bob2= new Bob(240,500,false)
bob3= new Bob(280,500,false)
bob4= new Bob(320,500,false)
bob5= new Bob(360,500,false)
holder1= new Holder(200,100,100,20)
holder2= new Holder(240,100,100,20)
holder3= new Holder(280,100,100,20)
holder4= new Holder(320,100,100,20)
holder5= new Holder(360,100,100,20)
rope1= new Rope(bob1.body,holder1.body,70,0)
rope2= new Rope(bob2.body,holder2.body,0,0)
rope3= new Rope(bob3.body,holder3.body,0,0)
rope4= new Rope(bob4.body,holder4.body,0,0)
rope5= new Rope(bob5.body,holder5.body,0,0)
// holder= new Holder(width/2,100,400,20)
Engine.run(engine);
world.gravity.y=20;
}
function draw() {
rectMode(CENTER);
background(0);
if(keyDown(UP_ARROW)){
bob1.update();
}
bob1.display();
bob3.display()
bob4.display()
bob2.display()
holder1.show()
holder2.show()
holder3.show()
holder4.show()
holder5.show()
rope1.show()
rope2.show()
rope3.show()
rope4.show()
rope5.show()
bob5.display()
}
|
/** @jsxImportSource theme-ui */
import Link from "next/link";
import { useRouter } from "next/router";
import { Button } from "theme-ui";
const Page = () => {
const router = useRouter();
const { id } = router.query;
return (
<div sx={{ variant: "containers.page" }}>
<h1>Note {id}</h1>
{/* <Button variant="simple" type="button" onClick={() => router.back()}>
<p>Go back</p>
</Button>
<Link href={"/"}>
<a>Go to Home</a>
</Link> */}
</div>
);
};
export default Page;
|
//------------------------------------------------------------------------------
// FINANCIAL MANAGER v1.0
//------------------------------------------------------------------------------
// by Alex Dyagilev
//------------------------------------------------------------------------------
// Account.js -- model for accounts
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Require mongoose
var mongoose = require("mongoose");
// Create Schema class
var Schema = mongoose.Schema;
// Create account schema
var AccountSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
var Account = mongoose.model("Account", AccountSchema);
module.exports = Account;
|
module.exports = {
h2oCw: {
title: "H2O Plus",
id: "h2o-cw",
slug: "h2o-plus-e-commerce-website",
type: "page",
subtitle: "e-commerce site",
description: "Continuously evolving a brand to stay relevant and raising the quality to compete with prestige brands",
thumbnail: {
filename: "h2o-plus-website-thumbnail.jpg"
},
roles: [
"Visual Design",
"Front-End Development",
"Photography"
],
tools: [
"Photoshop",
"Html/Css",
"Javascript/jQuery"
],
platforms: [
"MarketLive"
],
headImages: [
{
filename: "serum-splash.jpg",
alt: "Serum bottle emerging from a rippling pool of water.",
widths: [ 524, 1048, 1572],
mobileWidth: '90vw',
defaultWidth: '524px'
},
{
filename: "shiny-products.jpg",
alt: "A trio of highly reflective skincare jars and tube.",
widths: [240, 278, 526, 804],
mobileWidth: '45vw',
defaultWidth: '278px'
},
{
filename: "shampoo-texture.jpg",
alt: "A creamy green shampoo texture.",
widths: [240, 365, 690, 1055],
mobileWidth: '45vw',
defaultWidth: '365px'
}
],
content: {
section1: {
header: "Growing & Evolving with a Brand Online",
body: [
"For eight years as the in-house web designer at H2O Plus I grew along with the brand. As design trends, marketing techniques and technologies grew, as well as changes in the beauty market I grew and evolved with them, always raising bar and embracing new challenges every day.",
"The latest site visual update. The intention was to lighten the visual feel of the site. After the last rebranding the focus was on deep sea ingredients and water. This was too heavy for the water. Also the previous website template relied to much on keeping all content above the fold."
],
images: [
{
filename: "h20-plus-classic-homepage-0.jpg",
alt: "H2O Plus earliest homepage from the 90's",
widths: [245, 384, 768, 1152],
mobileWidth: '68vw',
defaultWidth: '384px'
},
{
filename: "h20-plus-classic-homepage-1.jpg",
alt: "H2O Plus classic homepage, with a lighter cleaner feel.",
widths: [218, 384, 768, 1152],
mobileWidth: '68vw',
defaultWidth: '384px'
},
{
filename: "h20-plus-classic-homepage-2.jpg",
alt: "H2O Plus transistional homepage with a deep undersea background.",
widths: [231, 360, 720, 1080],
mobileWidth: '64vw',
defaultWidth: '360px'
},
{
filename: "h20-plus-classic-homepage-3.jpg",
alt: "H2O Plus rebranding homepage with a boxless look and a deep water-like background.",
widths: [260, 390, 780, 1170],
mobileWidth: '72vw',
defaultWidth: '390px'
},
{
filename: "h20-plus-classic-homepage-4.jpg",
alt: "H2O Plus rebranding homepage cleaning up the previous homepage and creating a fresh clinical look.",
widths: [310, 462, 924, 1386],
mobileWidth: '86vw',
defaultWidth: '462px'
}
]
},
section2: {
header: "Bigger, Brighter & Clearer",
body: [
"The homepage focused several large dynamic visuals, bold typography and quick copy to introduce the latest promotion. Although the current platform was not responsive, I was able to make the homepage adaptive, stretching the key visuals to feel the page maximizing the impage.",
"In addition to cleaning up the header, a larger footer was incorporated in two parts. The first to additional offers such as free shipping and more extensive site navigation at the bottom."
],
images: [
{
filename: "h2o-plus-homepage.jpg",
alt: "H2O Plus homepage. The fruition of a brand repositioning, for a clean, clinical look.",
widths: [360, 600, 1200, 1800],
mobileWidth: '100vw',
defaultWidth: '600px'
},
]
},
section3: {
header: "A Clean, Bold, & Clinical Look was the Focus",
body: [
"Changing the background to white necessitated codifying a color scheme as well establishing a typographic system with the already chose typeface Trade Gothic Condensed.",
"Adding a light cerulean blue and soft greys allowed for the effect of a lighter cleaners water visual. <Light, Clean, Water, Science>. Partial boarders and complementing verticle and horizontal lines instead of full border helped define discrete spaces yet keep an open look."
],
images: [
{
filename: "h2o-plus-typography-headers.svg",
alt: "H2O Plus header typography - with Trade Gothic Condensed."
},
{
filename: "h2o-plus-typography-paragraph.svg",
alt: "H2O Plus paragraph typography — with Trade Gothic Condensed."
},
{
filename: "h20-plus-gateway.jpg",
alt: "H2O Plus gateway page featuring the different skin care collections.",
widths: [360, 600, 1200, 1800],
mobileWidth: '100vw',
defaultWidth: '360px'
}
]
},
section4: {
header: "You Can Be Information Dense without Being Heavy",
body: [
"We did a complete overhaul of the product details page. The goal was to information dense, while remaining easy to read and still feel light.",
"A well established hierarchy was necessary for a road map for the page layout. Vital concise info was present above the fold. Horizontal and vertical lines where used to define separate spaces while keeping everything open. And establishing a tight typographic scale for consistency and rhythm. "
],
images: [
{
filename: "h2o-plus-product-details.jpg",
alt: "H2O Plus product details page, featuring a product description, suggested products above the fold, key elements and full ingredients, videos, media appearances and reviews.",
widths: [360, 600, 1200, 1800],
mobileWidth: '100vw',
defaultWidth: '360px'
}
]
},
section5: {
header: "Telling the Story of the Brand in Many Different Ways",
body: [
"There were many opportunities to tell the story of our brand with the use of landing pages throughout the site. This was always a great opportunity to explore unique design options."
],
images: [
{
filename: "h20-plus-landing-page-0.jpg",
alt: "H2O Plus landing page featuring the skin care collections.",
widths: [180, 300, 600, 900],
mobileWidth: '50vw',
defaultWidth: '300px'
},
{
filename: "h20-plus-landing-page-1.jpg",
alt: "H2O Plus landing page showing the transition to the rebranded packaging.",
widths: [188, 312, 624, 936],
mobileWidth: '52vw',
defaultWidth: '312px'
},
{
filename: "h20-plus-landing-page-2.jpg",
alt: "H2O Plus landing page featuring the company's many philanthropic endeavors.",
widths: [184, 306, 612, 918],
mobileWidth: '51vw',
defaultWidth: '306px'
},
{
filename: "h20-plus-landing-page-3.jpg",
alt: "H2O Plus landing page selling the benefits of the customer loyalty program.",
widths: [238, 396, 792, 1188],
mobileWidth: '66vw',
defaultWidth: '396px'
}
]
},
section6: {
header: "Images Anchor Design & Are the Focal Point of Storytelling",
body: [
"The first big impact I was able to make on h2oplus.com was to create an implement a new stanadard for product photography. Consistent high quality product photography was primary in communicating that we were a prestige brand. I undertook rephotographing the entire collection to bring all products on the site up to this standard.",
"Over the years I was able to create colorful high impact story telling photos that anchored marketing promotions and brought the products to life in a new an fun way."
],
images: [
{
filename: "h2o-photography-product-silhouettes.jpg",
alt: "A collection of different product silhouette photos.",
widths: [360, 600, 1200, 1800],
mobileWidth: '100vw',
defaultWidth: '600px'
},
{
filename: "h2o-plus-photography-serum-splash.jpg",
alt: "A styled photo of serum in a rippling pool of water.",
widths: [159, 162, 324, 648],
mobileWidth: '44vw',
defaultWidth: '162px'
},
{
filename: "h2o-plus-photography-whitening.jpg",
alt: "A styled photo of whitening serum on a bright and bubbly background.",
widths: [202, 216, 432, 864],
mobileWidth: '56vw',
defaultWidth: '216px'
},
{
filename: "h2o-plus-photography-lip-candy.jpg",
alt: "A styled photo of lip balm on a background of candy hearts.",
widths: [195, 222, 444, 666],
mobileWidth: '54vw',
defaultWidth: '222px'
},
{
filename: "h2o-plus-photography-night-treatment.jpg",
alt: "A styled photo of a night treatment gel on a starry night background with rippling water.",
widths: [238, 260, 520, 780],
mobileWidth: '46vw',
defaultWidth: '260px'
},
{
filename: "h2o-plus-photography-holiday-sparkles.jpg",
alt: "A styled photo of a skin care collection on a background of festive red holiday sparkles.",
widths: [194, 209, 418, 627],
mobileWidth: '48vw',
defaultWidth: '209px'
},
{
filename: "h2o-plus-photography-bath-bubbles.jpg",
alt: "A styled photo of a pair of bath washes amidst floating bubbles.",
widths: [187, 201, 402, 804],
mobileWidth: '52vw',
defaultWidth: '201px'
}
]
},
section7: {
body: [
"Over the years at H2O Plus I was able to continually create dymanic imagery, relevant and stunning web sites that remained relevant elevating the brand to compete with larger prestige brands. The site was recognized as MarketLive <em>Best Site on the Rise</em> in 2011. The quality of work helped gain venture capital and foreign investment."
],
images: [
{
filename: "h2o-plus-website-award.jpg",
alt: "H2O Plus award from MarketLive for 'Best Site on the Rise.'",
widths: [324, 336, 672, 1008],
mobileWidth: '100vw',
defaultWidth: '336px'
}
]
}
}
}
}; |
// Copyright 2013 - UDS/CNRS
// The Aladin Lite program is distributed under the terms
// of the GNU General Public License version 3.
//
// This file is part of Aladin Lite.
//
// Aladin Lite is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Aladin Lite is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// The GNU General Public License is available in COPYING file
// along with Aladin Lite.
//
/******************************************************************************
* Aladin Lite project
*
* File Catalog
*
* Author: Thomas Boch[CDS]
*
*****************************************************************************/
var $ = require("jquery");
var cds = require("./cds").cds;
var Color = require("./Color");
// TODO : harmoniser parsing avec classe ProgressiveCat
cds.Catalog = (function() {
cds.Catalog = function(options) {
options = options || {};
this.type = "catalog";
this.name = options.name || "catalog";
this.color = options.color || Color.getNextColor();
this.sourceSize = options.sourceSize || 8;
this.markerSize = options.sourceSize || 12;
this.shape = options.shape || "square";
this.maxNbSources = options.limit || undefined;
this.onClick = options.onClick || undefined;
this.raField = options.raField || undefined; // ID or name of the field holding RA
this.decField = options.decField || undefined; // ID or name of the field holding dec
this.indexationNorder = 5; // à quel niveau indexe-t-on les sources
this.sources = [];
this.hpxIdx = new HealpixIndex(this.indexationNorder);
this.hpxIdx.init();
this.displayLabel = options.displayLabel || false;
this.labelColor = options.labelColor || this.color;
this.labelFont = options.labelFont || "10px sans-serif";
if (this.displayLabel) {
this.labelColumn = options.labelColumn;
if (!this.labelColumn) {
this.displayLabel = false;
}
}
if (
this.shape instanceof Image ||
this.shape instanceof HTMLCanvasElement
) {
this.sourceSize = this.shape.width;
}
this._shapeIsFunction = false; // if true, the shape is a function drawing on the canvas
if ($.isFunction(this.shape)) {
this._shapeIsFunction = true;
}
this.selectionColor = "#00ff00";
// create this.cacheCanvas
// cacheCanvas permet de ne créer le path de la source qu'une fois, et de le réutiliser (cf. http://simonsarris.com/blog/427-increasing-performance-by-caching-paths-on-canvas)
this.updateShape(options);
this.cacheMarkerCanvas = document.createElement("canvas");
this.cacheMarkerCanvas.width = this.markerSize;
this.cacheMarkerCanvas.height = this.markerSize;
var cacheMarkerCtx = this.cacheMarkerCanvas.getContext("2d");
cacheMarkerCtx.fillStyle = this.color;
cacheMarkerCtx.beginPath();
var half = this.markerSize / 2;
cacheMarkerCtx.arc(half, half, half - 2, 0, 2 * Math.PI, false);
cacheMarkerCtx.fill();
cacheMarkerCtx.lineWidth = 2;
cacheMarkerCtx.strokeStyle = "#ccc";
cacheMarkerCtx.stroke();
this.isShowing = true;
};
cds.Catalog.createShape = function(shapeName, color, sourceSize) {
if (shapeName instanceof Image || shapeName instanceof HTMLCanvasElement) {
// in this case, the shape is already created
return shapeName;
}
var c = document.createElement("canvas");
c.width = c.height = sourceSize;
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 2.0;
if (shapeName == "plus") {
ctx.moveTo(sourceSize / 2, 0);
ctx.lineTo(sourceSize / 2, sourceSize);
ctx.stroke();
ctx.moveTo(0, sourceSize / 2);
ctx.lineTo(sourceSize, sourceSize / 2);
ctx.stroke();
} else if (shapeName == "cross") {
ctx.moveTo(0, 0);
ctx.lineTo(sourceSize - 1, sourceSize - 1);
ctx.stroke();
ctx.moveTo(sourceSize - 1, 0);
ctx.lineTo(0, sourceSize - 1);
ctx.stroke();
} else if (shapeName == "rhomb") {
ctx.moveTo(sourceSize / 2, 0);
ctx.lineTo(0, sourceSize / 2);
ctx.lineTo(sourceSize / 2, sourceSize);
ctx.lineTo(sourceSize, sourceSize / 2);
ctx.lineTo(sourceSize / 2, 0);
ctx.stroke();
} else if (shapeName == "triangle") {
ctx.moveTo(sourceSize / 2, 0);
ctx.lineTo(0, sourceSize - 1);
ctx.lineTo(sourceSize - 1, sourceSize - 1);
ctx.lineTo(sourceSize / 2, 0);
ctx.stroke();
} else if (shapeName == "circle") {
ctx.arc(
sourceSize / 2,
sourceSize / 2,
sourceSize / 2 - 1,
0,
2 * Math.PI,
true
);
ctx.stroke();
} else {
// default shape: square
ctx.moveTo(1, 0);
ctx.lineTo(1, sourceSize - 1);
ctx.lineTo(sourceSize - 1, sourceSize - 1);
ctx.lineTo(sourceSize - 1, 1);
ctx.lineTo(1, 1);
ctx.stroke();
}
return c;
};
// find RA, Dec fields among the given fields
//
// @param fields: list of objects with ucd, unit, ID, name attributes
// @param raField: index or name of right ascension column (might be undefined)
// @param decField: index or name of declination column (might be undefined)
//
function findRADecFields(fields, raField, decField) {
var raFieldIdx, decFieldIdx;
raFieldIdx = decFieldIdx = null;
// first, look if RA/DEC fields have been already given
if (raField) {
// ID or name of RA field given at catalogue creation
for (var l = 0, len = fields.length; l < len; l++) {
var field = fields[l];
if (Utils.isInt(raField) && raField < fields.length) {
// raField can be given as an index
raFieldIdx = raField;
break;
}
if (
(field.ID && field.ID === raField) ||
(field.name && field.name === raField)
) {
raFieldIdx = l;
break;
}
}
}
if (decField) {
// ID or name of dec field given at catalogue creation
for (var l = 0, len = fields.length; l < len; l++) {
var field = fields[l];
if (Utils.isInt(decField) && decField < fields.length) {
// decField can be given as an index
decFieldIdx = decField;
break;
}
if (
(field.ID && field.ID === decField) ||
(field.name && field.name === decField)
) {
decFieldIdx = l;
break;
}
}
}
// if not already given, let's guess position columns on the basis of UCDs
for (var l = 0, len = fields.length; l < len; l++) {
if (raFieldIdx != null && decFieldIdx != null) {
break;
}
var field = fields[l];
if (!raFieldIdx) {
if (field.ucd) {
var ucd = $.trim(field.ucd.toLowerCase());
if (ucd.indexOf("pos.eq.ra") == 0 || ucd.indexOf("pos_eq_ra") == 0) {
raFieldIdx = l;
continue;
}
}
}
if (!decFieldIdx) {
if (field.ucd) {
var ucd = $.trim(field.ucd.toLowerCase());
if (
ucd.indexOf("pos.eq.dec") == 0 ||
ucd.indexOf("pos_eq_dec") == 0
) {
decFieldIdx = l;
continue;
}
}
}
}
// still not found ? try some common names for RA and Dec columns
if (raFieldIdx == null && decFieldIdx == null) {
for (var l = 0, len = fields.length; l < len; l++) {
var field = fields[l];
var name = field.name || field.ID || "";
name = name.toLowerCase();
if (!raFieldIdx) {
if (
name.indexOf("ra") == 0 ||
name.indexOf("_ra") == 0 ||
name.indexOf("ra(icrs)") == 0 ||
name.indexOf("_ra") == 0 ||
name.indexOf("alpha") == 0
) {
raFieldIdx = l;
continue;
}
}
if (!decFieldIdx) {
if (
name.indexOf("dej2000") == 0 ||
name.indexOf("_dej2000") == 0 ||
name.indexOf("de") == 0 ||
name.indexOf("de(icrs)") == 0 ||
name.indexOf("_de") == 0 ||
name.indexOf("delta") == 0
) {
decFieldIdx = l;
continue;
}
}
}
}
// last resort: take two first fieds
if (raFieldIdx == null || decFieldIdx == null) {
raFieldIdx = 0;
decFieldIdx = 1;
}
return [raFieldIdx, decFieldIdx];
}
// return an array of Source(s) from a VOTable url
// callback function is called each time a TABLE element has been parsed
cds.Catalog.parseVOTable = function(
url,
callback,
maxNbSources,
useProxy,
raField,
decField
) {
// adapted from votable.js
function getPrefix($xml) {
var prefix;
// If Webkit chrome/safari/... (no need prefix)
if ($xml.find("RESOURCE").length > 0) {
prefix = "";
} else {
// Select all data in the document
prefix = $xml.find("*").first();
if (prefix.length == 0) {
return "";
}
// get name of the first tag
prefix = prefix.prop("tagName");
var idx = prefix.indexOf(":");
prefix = prefix.substring(0, idx) + "\\:";
}
return prefix;
}
function doParseVOTable(xml, callback) {
xml = xml.replace(/^\s+/g, ""); // we need to trim whitespaces at start of document
var attributes = [
"name",
"ID",
"ucd",
"utype",
"unit",
"datatype",
"arraysize",
"width",
"precision"
];
var fields = [];
var k = 0;
var $xml = $($.parseXML(xml));
var prefix = getPrefix($xml);
$xml.find(prefix + "FIELD").each(function() {
var f = {};
for (var i = 0; i < attributes.length; i++) {
var attribute = attributes[i];
if ($(this).attr(attribute)) {
f[attribute] = $(this).attr(attribute);
}
}
if (!f.ID) {
f.ID = "col_" + k;
}
fields.push(f);
k++;
});
var raDecFieldIdxes = findRADecFields(fields, raField, decField);
var raFieldIdx, decFieldIdx;
raFieldIdx = raDecFieldIdxes[0];
decFieldIdx = raDecFieldIdxes[1];
var sources = [];
var coo = new Coo();
var ra, dec;
$xml.find(prefix + "TR").each(function() {
var mesures = {};
var k = 0;
$(this)
.find(prefix + "TD")
.each(function() {
var key = fields[k].name ? fields[k].name : fields[k].id;
mesures[key] = $(this).text();
k++;
});
var keyRa = fields[raFieldIdx].name
? fields[raFieldIdx].name
: fields[raFieldIdx].id;
var keyDec = fields[decFieldIdx].name
? fields[decFieldIdx].name
: fields[decFieldIdx].id;
if (Utils.isNumber(mesures[keyRa]) && Utils.isNumber(mesures[keyDec])) {
ra = parseFloat(mesures[keyRa]);
dec = parseFloat(mesures[keyDec]);
} else {
coo.parse(mesures[keyRa] + " " + mesures[keyDec]);
ra = coo.lon;
dec = coo.lat;
}
sources.push(new cds.Source(ra, dec, mesures));
if (maxNbSources && sources.length == maxNbSources) {
return false; // break the .each loop
}
});
if (callback) {
callback(sources);
}
}
var ajax = Utils.getAjaxObject(url, "GET", "text", useProxy);
ajax.done(function(xml) {
doParseVOTable(xml, callback);
});
};
// API
cds.Catalog.prototype.updateShape = function(options) {
options = options || {};
this.color = options.color || this.color || Color.getNextColor();
this.sourceSize = options.sourceSize || this.sourceSize || 6;
this.shape = options.shape || this.shape || "square";
this.selectSize = this.sourceSize + 2;
this.cacheCanvas = cds.Catalog.createShape(
this.shape,
this.color,
this.sourceSize
);
this.cacheSelectCanvas = cds.Catalog.createShape(
"square",
this.selectionColor,
this.selectSize
);
this.reportChange();
};
// API
cds.Catalog.prototype.addSources = function(sourcesToAdd) {
sourcesToAdd = [].concat(sourcesToAdd); // make sure we have an array and not an individual source
this.sources = this.sources.concat(sourcesToAdd);
for (var k = 0, len = sourcesToAdd.length; k < len; k++) {
sourcesToAdd[k].setCatalog(this);
}
this.reportChange();
};
// API
//
// create sources from a 2d array and add them to the catalog
//
// @param columnNames: array with names of the columns
// @array: 2D-array, each item being a 1d-array with the same number of items as columnNames
cds.Catalog.prototype.addSourcesAsArray = function(columnNames, array) {
var fields = [];
for (var colIdx = 0; colIdx < columnNames.length; colIdx++) {
fields.push({ name: columnNames[colIdx] });
}
var raDecFieldIdxes = findRADecFields(fields, this.raField, this.decField);
var raFieldIdx, decFieldIdx;
raFieldIdx = raDecFieldIdxes[0];
decFieldIdx = raDecFieldIdxes[1];
var newSources = [];
var coo = new Coo();
var ra, dec, row, dataDict;
for (var rowIdx = 0; rowIdx < array.length; rowIdx++) {
row = array[rowIdx];
if (Utils.isNumber(row[raFieldIdx]) && Utils.isNumber(row[decFieldIdx])) {
ra = parseFloat(row[raFieldIdx]);
dec = parseFloat(row[decFieldIdx]);
} else {
coo.parse(row[raFieldIdx] + " " + row[decFieldIdx]);
ra = coo.lon;
dec = coo.lat;
}
dataDict = {};
for (var colIdx = 0; colIdx < columnNames.length; colIdx++) {
dataDict[columnNames[colIdx]] = row[colIdx];
}
newSources.push(A.source(ra, dec, dataDict));
}
this.addSources(newSources);
};
// return the current list of Source objects
cds.Catalog.prototype.getSources = function() {
return this.sources;
};
// TODO : fonction générique traversant la liste des sources
cds.Catalog.prototype.selectAll = function() {
if (!this.sources) {
return;
}
for (var k = 0; k < this.sources.length; k++) {
this.sources[k].select();
}
};
cds.Catalog.prototype.deselectAll = function() {
if (!this.sources) {
return;
}
for (var k = 0; k < this.sources.length; k++) {
this.sources[k].deselect();
}
};
// return a source by index
cds.Catalog.prototype.getSource = function(idx) {
if (idx < this.sources.length) {
return this.sources[idx];
} else {
return null;
}
};
cds.Catalog.prototype.setView = function(view) {
this.view = view;
this.reportChange();
};
cds.Catalog.prototype.removeAll = cds.Catalog.prototype.clear = function() {
// TODO : RAZ de l'index
this.sources = [];
};
cds.Catalog.prototype.draw = function(
ctx,
projection,
frame,
width,
height,
largestDim,
zoomFactor
) {
if (!this.isShowing) {
return;
}
// tracé simple
//ctx.strokeStyle= this.color;
//ctx.lineWidth = 1;
//ctx.beginPath();
if (this._shapeIsFunction) {
ctx.save();
}
var sourcesInView = [];
for (var k = 0, len = this.sources.length; k < len; k++) {
var inView = cds.Catalog.drawSource(
this,
this.sources[k],
ctx,
projection,
frame,
width,
height,
largestDim,
zoomFactor
);
if (inView) {
sourcesInView.push(this.sources[k]);
}
}
if (this._shapeIsFunction) {
ctx.restore();
}
//ctx.stroke();
// tracé sélection
ctx.strokeStyle = this.selectionColor;
//ctx.beginPath();
var source;
for (var k = 0, len = sourcesInView.length; k < len; k++) {
source = sourcesInView[k];
if (!source.isSelected) {
continue;
}
cds.Catalog.drawSourceSelection(this, source, ctx);
}
// NEEDED ?
//ctx.stroke();
// tracé label
if (this.displayLabel) {
ctx.fillStyle = this.labelColor;
ctx.font = this.labelFont;
for (var k = 0, len = sourcesInView.length; k < len; k++) {
cds.Catalog.drawSourceLabel(this, sourcesInView[k], ctx);
}
}
};
cds.Catalog.drawSource = function(
catalogInstance,
s,
ctx,
projection,
frame,
width,
height,
largestDim,
zoomFactor
) {
if (!s.isShowing) {
return false;
}
var sourceSize = catalogInstance.sourceSize;
// TODO : we could factorize this code with Aladin.world2pix
var xy;
if (frame.system != CooFrameEnum.SYSTEMS.J2000) {
var lonlat = CooConversion.J2000ToGalactic([s.ra, s.dec]);
xy = projection.project(lonlat[0], lonlat[1]);
} else {
xy = projection.project(s.ra, s.dec);
}
if (xy) {
var xyview = AladinUtils.xyToView(
xy.X,
xy.Y,
width,
height,
largestDim,
zoomFactor,
true
);
var max = s.popup ? 100 : s.sourceSize;
if (xyview) {
// TODO : index sources by HEALPix cells at level 3, 4 ?
// check if source is visible in view
if (
xyview.vx > width + max ||
xyview.vx < 0 - max ||
xyview.vy > height + max ||
xyview.vy < 0 - max
) {
s.x = s.y = undefined;
return false;
}
s.x = xyview.vx;
s.y = xyview.vy;
if (catalogInstance._shapeIsFunction) {
catalogInstance.shape(s, ctx, catalogInstance.view.getViewParams());
} else if (s.marker && s.useMarkerDefaultIcon) {
ctx.drawImage(
catalogInstance.cacheMarkerCanvas,
s.x - sourceSize / 2,
s.y - sourceSize / 2
);
} else {
ctx.drawImage(
catalogInstance.cacheCanvas,
s.x - catalogInstance.cacheCanvas.width / 2,
s.y - catalogInstance.cacheCanvas.height / 2
);
}
// has associated popup ?
if (s.popup) {
s.popup.setPosition(s.x, s.y);
}
}
return true;
} else {
return false;
}
};
cds.Catalog.drawSourceSelection = function(catalogInstance, s, ctx) {
if (!s || !s.isShowing || !s.x || !s.y) {
return;
}
var sourceSize = catalogInstance.selectSize;
ctx.drawImage(
catalogInstance.cacheSelectCanvas,
s.x - sourceSize / 2,
s.y - sourceSize / 2
);
};
cds.Catalog.drawSourceLabel = function(catalogInstance, s, ctx) {
if (!s || !s.isShowing || !s.x || !s.y) {
return;
}
var label = s.data[catalogInstance.labelColumn];
if (!label) {
return;
}
ctx.fillText(label, s.x, s.y);
};
// callback function to be called when the status of one of the sources has changed
cds.Catalog.prototype.reportChange = function() {
this.view && this.view.requestRedraw();
};
cds.Catalog.prototype.show = function() {
if (this.isShowing) {
return;
}
this.isShowing = true;
this.reportChange();
};
cds.Catalog.prototype.hide = function() {
if (!this.isShowing) {
return;
}
this.isShowing = false;
if (
this.view &&
this.view.popup &&
this.view.popup.source &&
this.view.popup.source.catalog == this
) {
this.view.popup.hide();
}
this.reportChange();
};
return cds.Catalog;
})();
module.exports = {};
|
const onError = require('../../error');
const respond = require('../../respond');
const { utils: { strings } } = require('@iondv/core');
module.exports = (req, res) => respond(['auth'], (scope) => {
try {
const user = scope.auth.getUser(req);
let base = strings.getBase('frontend');
res
.set('Content-type', 'application/javascript')
.send(Buffer.from(`
'use strict';
function I18nHandler() {
this.base = {};
this.s = function(id, params) {
if (id) {
if (this.base.hasOwnProperty(id)) {
var str = this.base[id];
if (params) {
for (var p in params) {
str = str.replace('%' + p, params[p]);
}
}
return str;
}
return id;
}
return '';
};
}
window.i18n = new I18nHandler();
window.s = window.__ = function (id, params) {return window.i18n.s(id, params);};
window.i18n.base = ${JSON.stringify(base(user.language()))};
`));
} catch (err) {
if (scope.logRecorder) {
scope.logRecorder.stop();
}
onError(scope, err, res, true);
}
},
res);
|
import { app, query } from 'mu';
app.get('/book-reports', async function( req, res ) {
let reportsData = await getReports();
let jsonData = reportsDataToJsonApiObject(reportsData);
res.send( jsonData );
});
async function getReports(){
const results = await query(`
PREFIX ext: <http://mu.semte.ch/vocabularies/ext/>
PREFIX mu: <http://mu.semte.ch/vocabularies/core/>
PREFIX dct: <http://purl.org/dc/terms/>
SELECT ?uri ?uuid ?created ?booksTotal WHERE {
GRAPH <http://mu.semte.ch/application> {
?uri a ext:BookReport;
mu:uuid ?uuid;
dct:created ?created;
ext:booksTotal ?booksTotal.
}
}
ORDER BY DESC(?created)
`);
return results.results.bindings;
}
function reportsDataToJsonApiObject(reportsData){
const entries = reportsData.map( reportData => {
return {
attributes: {
created: reportData.created.value,
uri: reportData.uri.value,
'books-total': parseInt(reportData.booksTotal.value)
},
id: reportData.uuid.value,
type: "book-report",
relationships: {}
};
});
return {
data: entries,
links: {
"first": "/book-reports",
"last": "/book-reports"
}
};
}
|
/**
* @fileOverview contains queries used on the database.
* @author Gustavo Amaral
*/
'user strict';
/**
* The SQL query to create the session's table. The table is created
* only if it not exists.
* @constant
* @type {string}
*/
const createSessionTableSQL =
`CREATE TABLE IF NOT EXISTS Session (
UUID text NOT NULL,
UserID integer NOT NULL references Users(ID),
Expiration timestamp(6) NOT NULL
)`;
/** The SQL query used to delete the table session. It was originally created
* to reset the database when performing unity tests.
* @constant
* @type {string}
*/
const deleteSessionTableSQL = 'DROP TABLE Session';
/**
* Adds a new session within the database. This query was created to be used with 'pg' module
* because it contains three variables in this order: session's uuidv4 token, user's id and
* expiration date.
* @constant
* @type {string}
*/
const addSessionSQL = 'INSERT INTO Session (UUID, UserID, Expiration) VALUES ($1, $2, $3)';
/**
* Removes a session from the database using its UUID/Token.
* This query was created to be used with 'pg' module. So, it
* requires one variable that is the session's UUID/Token.
* @constant
* @type {string}
*/
const deleteSessionSQL = 'DELETE FROM Session WHERE UUID = $1';
/**
* Retrieves a session from the database based on its UUID token.
* It was created to be used with 'pg' module so it have a unique variable that corresponds
* to the session's token.
* @contant
* @type {string}
*/
const getSessionSQL = 'SELECT UUID, UserID, Expiration FROM Session WHERE UUID = $1';
module.exports = {
createSessionTableSQL,
deleteSessionTableSQL,
addSessionSQL,
getSessionSQL,
deleteSessionSQL,
};
|
/* global QUnit */
/**
* Before doing the test, import extended-css-iframejs-injection.txt to AdGuard
*/
window.addEventListener('DOMContentLoaded', () => {
QUnit.test('1. Test rules injection into iframe created by JS', (assert) => {
const frame = document.querySelector('#case1 > #frame1');
const innerDoc = frame.contentDocument || frame.contentWindow.document;
assert.ok(innerDoc.querySelector('#inframe1').style.display === 'none', 'Extended CSS rules should work inside of iframes created by JS');
});
});
|
import React from 'react';
import './SearchBar.css';
export const SearchBar = ({ filterProducts, isFilteringByCategory }) => {
if (isFilteringByCategory) {
if (document.getElementById('productSearch')) {
document.getElementById('productSearch').value = '';
}
}
return (
<input
id="productSearch"
className="search"
type="text"
placeholder="Search product..."
onChange={(event) => {
var text = event.target.value;
text.length < 3 || filterProducts({ filter: text, type: 'text' });
text.length || filterProducts({ filter: 0, type: 'category' });
}}
></input>
);
};
|
$(document).ready(function() {
//------------- jGrowl notification -------------//
setTimeout(function() {
$.jGrowl("<i class='icon16 i-checkmark-3'></i> Login is successfull", {
group: 'success',
position: 'center',
sticky: false,
closeTemplate: '<i class="icon16 i-close-2"></i>',
animateOpen: {
width: 'show',
height: 'show'
}
});
}, 250);
//define chart clolors ( you maybe add more colors if you want or flot will add it automatic )
var chartColours = ['#62aeef', '#d8605f', '#72c380', '#6f7a8a', '#f7cb38', '#5a8022', '#2c7282'];
//generate random number for charts
randNum = function(){
return (Math.floor( Math.random()* (1+40-20) ) ) + 20;
}
//check if element exist and draw chart
if($(".chart").length) {
$(function () {
var d1 = [];
var d2 = [];
//here we generate data for chart
for (var i = 0; i < 32; i++) {
d1.push([new Date(Date.today().add(i).days()).getTime(),randNum()+i+i]);
d2.push([new Date(Date.today().add(i).days()).getTime(),randNum()]);
}
var chartMinDate = d1[0][0]; //first day
var chartMaxDate = d1[31][0];//last day
var tickSize = [1, "day"];
var tformat = "%d/%m/%y";
//graph options
var options = {
grid: {
show: true,
aboveData: true,
color: "#3f3f3f" ,
labelMargin: 5,
axisMargin: 0,
borderWidth: 0,
borderColor:null,
minBorderMargin: 5 ,
clickable: true,
hoverable: true,
autoHighlight: true,
mouseActiveRadius: 100
},
series: {
lines: {
show: true,
fill: true,
lineWidth: 2,
steps: false
},
points: {
show:true,
radius: 2.8,
symbol: "circle",
lineWidth: 2.5
}
},
legend: {
position: "ne",
margin: [0,-25],
noColumns: 0,
labelBoxBorderColor: null,
labelFormatter: function(label, series) {
// just add some space to labes
return label+' ';
},
width: 40,
height: 1
},
colors: chartColours,
shadowSize:0,
tooltip: true, //activate tooltip
tooltipOpts: {
content: "%s: %y.0",
xDateFormat: "%d/%m",
shifts: {
x: -30,
y: -50
},
defaultTheme: false
},
yaxis: { min: 0 },
xaxis: {
mode: "time",
minTickSize: tickSize,
timeformat: tformat,
min: chartMinDate,
max: chartMaxDate
}
};
var plot = $.plot($(".chart"),
[{
label: "Email Send",
data: d1,
lines: {fillColor: "#f3faff"},
points: {fillColor: "#fff"}
},
{
label: "Email Open",
data: d2,
lines: {fillColor: "#fff8f7"},
points: {fillColor: "#fff"}
}], options);
});
}//End .chart if
//check if element exist and draw chat pie
if($(".chart-pie-social").length) {
$(function () {
var options = {
series: {
pie: {
show: true,
highlight: {
opacity: 0.1
},
radius: 1,
stroke: {
width: 2
},
startAngle: 2,
border: 30, //darken the main color with 30
label: {
show: true,
radius: 2/3,
formatter: function(label, series){
return '<div class="pie-chart-label">'+label+' '+Math.round(series.percent)+'%</div>';
}
}
}
},
legend:{
show:false
},
grid: {
hoverable: true,
clickable: true
},
tooltip: true, //activate tooltip
tooltipOpts: {
content: "%s : %y.1"+"%",
shifts: {
x: -30,
y: -50
},
defaultTheme: false
}
};
var data = [
{ label: "Facebook", data: 64, color: chartColours[0]},
{ label: "Twitter", data: 25, color: chartColours[1]},
{ label: "Google", data: 11, color: chartColours[2]}
];
$.plot($(".chart-pie-social"), data, options);
});
}//End of .cart-pie-social
//Init campaign stats
initPieChart();
//------------- ToDo -------------//
//toDo
function toDo () {
var todos = $('.toDo');
var items = todos.find('.task-item');
var chboxes = items.find('input[type="checkbox"]');
var close = items.find('.act');
chboxes.change(function() {
if ($(this).is(':checked')) {
$(this).closest('.task-item').addClass('done');
} else {
$(this).closest('.task-item').removeClass('done');
}
});
items.hover(
function () {
$(this).addClass('show');
},
function () {
$(this).removeClass('show');
}
);
close.click(function() {
$(this).closest('.task-item').fadeOut('500');
//Do other stuff here..
});
}
toDo();
//sortable
$(function() {
$( "#today, #tomorrow" ).sortable({
connectWith: ".todo-list"
}).disableSelection();
});
//------------- Full calendar -------------//
$(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
//calendar example
$('#dashboard-calendar').fullCalendar({
//isRTL: true,
//theme: true,
header: {
left: '',
center: 'title,today,prev,next,month,agendaWeek,agendaDay',
right: ''
},
firstDay: 1,
dayNamesShort: ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday'],
buttonText: {
prev: '<i class="icon24 i-arrow-left-7"></i>',
next: '<i class="icon24 i-arrow-right-8"></i>',
today:'<i class="icon24 i-home-6"></i>'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.allDay = allDay;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
$(this).remove();
},
events: [
{
title: 'All Day Event',
start: new Date(y, m, 1)
},
{
title: 'Long Event',
start: new Date(y, m, d-5),
end: new Date(y, m, d-2)
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d-3, 16, 0),
allDay: false
},
{
id: 999,
title: 'Repeating Event',
start: new Date(y, m, d+4, 16, 0),
allDay: false
},
{
title: 'Meeting',
start: new Date(y, m, d, 10, 30),
allDay: false
},
{
title: 'Lunch',
start: new Date(y, m, d, 12, 0),
end: new Date(y, m, d, 14, 0),
allDay: false,
color: '#25a7e8',
borderColor: '#0d7fb8'
},
{
title: 'Birthday Party',
start: new Date(y, m, d+1, 19, 0),
end: new Date(y, m, d+1, 22, 30),
allDay: false,
color: '#d8605f',
borderColor: '#b72827'
},
{
title: 'Click for Google',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
url: 'http://google.com/'
}
],
eventColor: '#72c380',
eventBorderColor: '#379e49'
});
});
//------------- Spark stats -------------//
$('.spark>.positive').sparkline('html', { type:'bar', barColor:'#42b449'});
$('.spark>.negative').sparkline('html', { type:'bar', barColor:'#db4a37'});
//------------- Gauge -------------//
var g = new JustGage({
id: "gauge",
value: getRandomInt(0, 100),
min: 0,
max: 100,
title: "server usage",
gaugeColor: '#6f7a8a',
labelFontColor: '#555',
titleFontColor: '#555',
valueFontColor: '#555',
showMinMax: false
});
var g1 = new JustGage({
id: "gauge1",
value: getRandomInt(100, 500),
min: 100,
max: 500,
title: "Visitors now",
gaugeColor: '#6f7a8a',
labelFontColor: '#555',
titleFontColor: '#555',
valueFontColor: '#555',
showMinMax: false
});
setInterval(function() {
g.refresh(getRandomInt(0, 100));
g1.refresh(getRandomInt(100, 500));
}, 2500);
});
//Setup campaign stats
var initPieChart = function() {
$(".percentage").easyPieChart({
barColor: '#62aeef',
borderColor: '#227dcb',
trackColor: '#d7e8f6',
scaleColor: false,
lineCap: 'butt',
lineWidth: 20,
size: 80,
animate: 1500
});
$(".percentage-red").easyPieChart({
barColor: '#d8605f',
trackColor: '#f6dbdb',
scaleColor: false,
lineCap: 'butt',
lineWidth: 20,
size: 80,
animate: 1500
});
} |
/*
* C.Extension.UI.UI //TODO description
*/
'use strict';
dust.helpers.include = function (chunk, context, bodies, params) {
return chunk.map(function (chunk) {
var extension_context = context.stack.head._context;
C.Extension.UI.Include.call(extension_context, params.src, function (err) {
if (err) {
console.log('[fail]', params.src, 'unable to load');
}
chunk.end();
});
});
};
dust.helpers.image = function (chunk, context, bodies, params) {
return chunk.map(function (chunk) {
var stack = context.stack;
while (stack.tail != undefined) {
stack = stack.tail;
}
var extension_context = stack.head._context;
var src = params.src;
if (typeof src == 'function') {
src(chunk, context);
src = chunk.data[0];
chunk.data.splice(0, 1);
}
extension_context._resources.file(src, function (err, handle) {
if (err) {
console.log('[fail]', params.src, 'unable to load');
chunk.end();
}
var bytes = handle.asUint8Array();
var binary = '';
for (var i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i])
}
var imageb64 = 'data:image/png;base64,' + window.btoa(binary);
chunk.write(imageb64);
chunk.end();
});
});
};
C.Extension.UI.UI = C.Utils.Inherit(C.Utils.Inherit(function (bridgeConstructor, eventEmitterConstructor, context) {
bridgeConstructor();
eventEmitterConstructor();
this._context = context;
this._current = undefined;
this._container = undefined;
this._contentContainer = undefined;
this._classList = [];
this._selector = undefined;
this._isLoaded = false;
this._isDestroyed = false;
this._isMinimized = false;
}, EventEmitter, 'C.Extension.UI.UI'), C.Extension.UI.Bridge, 'C.Extension.UI.UI');
C.Extension.UI.UI.prototype.addClass = function (classname) {
this._classList.push(classname);
if (this._container) {
this._container.classList.add(classname);
}
};
C.Extension.UI.UI.prototype.select = function (selector) {
if (this._selector) {
return this._selector.find(selector);
}
};
C.Extension.UI.UI.prototype._loaded = function () {
if (this._context._module.global.onLoaded !== undefined &&
typeof this._context._module.global.onLoaded === 'function') {
this._context._module.global.onLoaded(this._container);
}
};
C.Extension.UI.UI.prototype._destroy = function () {
if (this._context._module.global.onDestroyed !== undefined &&
typeof this._context._module.global.onDestroyed === 'function') {
this._context._module.global.onDestroyed(this._container);
}
};
C.Extension.UI.UI.prototype.destroy = function () {
this._isDestroyed = true;
this.emit('destroy', this._container);
this._destroy();
};
C.Extension.UI.UI.prototype.renderTemplate = function (content, callback) {
var name = this._context._package.name + (Math.floor(Math.random() * 10000));
var compiled = dust.compile(content, name);
dust.loadSource(compiled);
var context = C.Utils.Context.copy(this._context);
var citrongisCtx = {
_context: context
};
C.Utils.Object.merge(citrongisCtx, this._context._module.global);
dust.render(name, citrongisCtx, function (err, output) {
callback(err, output);
});
};
//TODO make this plateform independent
C.Extension.UI.UI.prototype.display = function (path, nowindow) {
var self = this;
C.Extension.Require.call(this._context, path, function (err, data) {
var name = self._context._package.name + path;
var compiled = dust.compile(data, name);
dust.loadSource(compiled);
//TODO bind context
var context = C.Utils.Context.copy(self._context);
context.currentPath = path;
var citrongisCtx = {
_context: context
};
C.Utils.Object.merge(citrongisCtx, self._context._module.global);
dust.render(name, citrongisCtx, function (err, output) {
if (err) {
console.error(err);
return;
}
if (!self._container) {
self._container = document.createElement('div');
var header = document.createElement('div');
header.classList.add('citrongisextension-header');
header.innerHTML = self._context._package.name;
// Close button
var close_btn = document.createElement('span');
close_btn.classList.add('citrongisextension-header-close');
close_btn.innerHTML = 'x';
header.appendChild(close_btn);
$(close_btn).mousedown(function (evt) {
evt.preventDefault();
evt.stopPropagation();
});
$(close_btn).click(function () {
self._context.destroy();
});
// Minimize button
var minimize_btn = document.createElement('span');
minimize_btn.classList.add('citrongisextension-header-minimize');
minimize_btn.innerHTML = '-';
header.appendChild(minimize_btn);
$(minimize_btn).mousedown(function (evt) {
evt.preventDefault();
evt.stopPropagation();
});
$(minimize_btn).click(function () {
if (!self._isMinimized) {
$(self._contentContainer).hide();
minimize_btn.innerHTML = '+';
} else {
$(self._contentContainer).show();
minimize_btn.innerHTML = '-';
}
self._isMinimized = !self._isMinimized;
});
self._container.classList.add('citrongisextension-handler');
for (var i = 0; i < self._classList.length; ++i) {
self._container.classList.add(self._classList[i]);
}
self._container.appendChild(header);
self._contentContainer = document.createElement('div');
self._container.appendChild(self._contentContainer);
self._selector = $(self._contentContainer);
}
if (nowindow) {
self._container = document.createElement('div');
var nodes = $.parseHTML(output, document, true);
for (var i = 0; nodes && i < nodes.length; ++i) {
$(self._container).append(nodes[i]);
}
for (var i = 0; i < self._classList.length; ++i) {
self._container.classList.add(self._classList[i]);
}
self._selector = $(self._container);
self.emit('display', self._container, nowindow);
} else {
var nodes = $.parseHTML(output, document, true);
for (var i = 0; nodes && i < nodes.length; ++i) {
$(self._contentContainer).append(nodes[i]);
}
self.emit('display', self._container);
}
self._isLoaded = true;
self._loaded();
});
});
};
|
import fs from 'fs'
import fs_promise from 'fs-promise'
import knex from 'knex'
import os from 'os'
import path from 'path'
import {isObject} from 'lodash'
const directories = [
'Application Data/Skype',
'AppData/Roaming/Skype',
'Library/Application Support/Skype',
'.Skype'
]
.map(dir => path.join.apply(null, [os.homedir()].concat(dir.split('/'))))
const SkypeStatus = {
DIR_NOT_FOUND: -1,
FILE_NOT_FOUND: -2,
}
// const ConversationType = {
// Contact: 1,
// Chat: 2
// }
let baseDir
export async function getBaseDirectory() {
if (!baseDir) {
for (const dir of directories) {
try {
fs.accessSync(dir)
baseDir = dir
break
}
catch (ex) {
}
}
}
return baseDir
}
export async function skype(username) {
await getBaseDirectory()
if (!baseDir) {
return SkypeStatus.DIR_NOT_FOUND
}
const sqliteFile = username + '/main.db'
let filename = path.join(baseDir, sqliteFile)
try {
fs.accessSync(filename)
}
catch (ex) {
return SkypeStatus.FILE_NOT_FOUND
}
try {
fs.accessSync(filename + '-journal')
const tmp = path.join(os.tmpdir(), sqliteFile)
try {
fs.accessSync(tmp)
}
catch (ex) {
await fs_promise.copy(filename, tmp)
}
filename = tmp
}
catch (ex) {
}
return knex({
client: 'sqlite3',
connection: {filename}
})
}
export async function readChatList(username) {
const db = await skype(username)
if (isObject(db)) {
const rows = await db.raw(`
SELECT
identity,
type,
displayname
FROM Conversations
WHERE type = 2 AND displayname IS NOT NULL AND identity LIKE '19:%@thread.skype'`)
const chats = {}
for(const row of rows) {
chats[/19:(\w+)@thread\.skype/.exec(row.identity)[1]] = row.displayname
}
return chats
}
}
|
var searchData=
[
['awake',['Awake',['../class_object_pool.html#ad94dc76a38c1ce6273fe9a25590e2e7aa9ca8bcac74fbf1f118cc3589aeca836f',1,'ObjectPool']]]
];
|
const TextReadController = require('./controller.readText')
module.exports = {TextReadController} |
/**
* CSS -webkit-user-drag property
* The non-standard `-webkit-user-drag` CSS property can be used to either make an element draggable or explicitly non-draggable (like links and images). See the standardized [draggable attribute/property](/mdn-api_htmlelement_draggable) for the recommended alternative method of accomplishing the same functionality.
* @see https://caniuse.com/webkit-user-drag
*/
/**
* @type {import('../features').Feature}
*/
export default {
'webkit-user-drag': true,
};
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
// Import Style
import styles from './App.css';
export class App extends Component {
constructor(props) {
super(props);
this.state = { isMounted: false };
}
componentDidMount() {
this.setState({isMounted: true}); // eslint-disable-line
}
render() {
return (
<div>
<Header />
<div className={styles.container}>
{this.props.children}
</div>
<Footer />
</div>
);
}
}
App.propTypes = {
children: PropTypes.object.isRequired,
};
export default App;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _actions = require('./../actions');
/**
* active when some people update
* @param {Object} client
* @param {Object} event
*/
function UpdateEvent(client) {
for (var _len = arguments.length, event = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
event[_key - 1] = arguments[_key];
}
client.on(event[0], function (message) {
var u = new _actions.UpdateAction(message.collection);
u.update(JSON.stringify(message.body)).then(function (doc) {
if (doc) {
// client.emit(event[1], JSON.stringify({ key: message.collection, doc, }));
// client.broadcast.emit(event[1], JSON.stringify({ key: message.collection, doc, }));
client.emit(event[1], JSON.stringify({ key: message.collection, doc: doc._id }));
client.broadcast.emit(event[1], JSON.stringify({ key: message.collection, doc: doc._id }));
}
}).catch(function (error) {
console.log(error);
});
u.quit();
});
}
exports.default = UpdateEvent; |
/**
* 事件
* @date :2014-12-01
* @author kotenei (kotenei@qq.com)
*/
define('km/event', [], function () {
var Event = function () {
this.topics = {};
this.subId = -1;
}
Event.prototype.on = function (topic, func) {
if (!this.topics[topic]) {
this.topics[topic] = [];
}
var token = (++this.subId).toString();
this.topics[topic].push({
token: token,
func: func
});
return this;
}
Event.prototype.off = function (topic) {
if (!topic) {
this.subId = -1;
this.topics = {};
return this;
}
if (/^\d+$/.test(topic)) {
for (var m in this.topics) {
if (this.topics[m]) {
for (var i = 0, j = this.topics[m].length; i < j; i++) {
if (this.topics[m][i].token === topic) {
this.topics[m].splice(i, 1);
return this;
}
}
}
}
} else {
if (this.topics[topic]) {
delete this.topics[topic];
}
}
return this;
}
Event.prototype.trigger = function (topic, args) {
if (!this.topics[topic]) {
return;
}
var arr = this.topics[topic],
len = arr ? arr.length : 0,
flag = 0;
while (flag < len && arr[flag]) {
arr[flag].func(args);
flag++;
}
};
return Event;
});
|
const { app } = require('electron');
const dialog = require('./dialog');
const parseAppURL = require('../lib/parse-app-url');
const requestGithubAccessToken = require('../lib/github-api');
const { ipcMain: ipc } = require('electron-better-ipc');
const APP_SCHEMA = 'ssh-git';
function registerAppSchema() {
app.setAsDefaultProtocolClient(APP_SCHEMA);
}
function showWindow(window) {
if (window.isMinimized()) window.restore();
if (window.isVisible()) window.focus();
window.show();
}
async function handleAppURL(callbackUrl, mainWindow) {
showWindow(mainWindow);
ipc.callFocusedRenderer('connecting-account');
const authState = parseAppURL(callbackUrl);
if (!authState) {
showError(
"Invalid redirect uri received. We couldn't verify the validity of the request. Please try again"
);
return;
}
const { code = null, state: client_state = null, token = null } = authState;
// Bitbucket and Gitlab will give back token directly
if (token) {
const result = await ipc.callFocusedRenderer('connect-account', {
state: client_state,
token,
});
if (!result) {
dialog.showErrorDialog(
"We couldn't verify the validity of the request. Please try again."
);
}
}
// Github Route : Using code to get back "access_token" in exchange from our serverless function.
else if (code) {
try {
const {
access_token: token = null,
state = null,
} = await requestGithubAccessToken(code, client_state);
if (!(token && state)) {
showError('We could verify the validity of request. Please try again');
return;
}
const result = await ipc.callFocusedRenderer('connect-account', {
state,
token,
});
if (!result) {
dialog.showErrorDialog(
"We couldn't verify the validity of the request. Please try again."
);
}
} catch (error) {
showError(error.message);
}
}
}
async function showError(error_message) {
dialog.showErrorDialog(error_message);
await ipc.callFocusedRenderer('connect-account', { state: null });
}
module.exports = { registerAppSchema, showWindow, handleAppURL };
|
import PropTypes from 'prop-types';
const Filter = ({ onChangeFilter }) => {
return (
<div>
<p>Find contacts by name</p>
<input type="text" onChange={onChangeFilter} />
</div>
);
};
Filter.propTypes = {
onChangeFilter: PropTypes.func.isRequired,
};
export default Filter;
|
const urlParams = new URLSearchParams(window.location.hash.substring(1));
const headers = {
'Authorization': `Bearer ${urlParams.get('access_token')}`,
'Content-Type': 'application/json'
};
var deviceId = "";
var player;
window.onSpotifyWebPlaybackSDKReady = () => {
const token = urlParams.get('access_token');
player = new Spotify.Player({
name: 'Song Start App',
getOAuthToken: cb => { cb(token); }
});
// Error handling
player.addListener('initialization_error', ({ message }) => { console.error(message); });
player.addListener('authentication_error', ({ message }) => { console.error(message); });
player.addListener('account_error', ({ message }) => { console.error(message); });
player.addListener('playback_error', ({ message }) => { console.error(message); });
// Playback status updates
player.addListener('player_state_changed', state => { console.log(state); });
// Ready
player.addListener('ready', ({ device_id }) => {
console.log('Ready with Device ID', device_id);
deviceId = device_id;
});
// Not Ready
player.addListener('not_ready', ({ device_id }) => {
console.log('Device ID has gone offline', device_id);
});
// Connect to the player!
player.connect();
};
var started = false;
var timeLeft = 30 * 1000;
var playing = false;
var done = false;
var chosen = false;
var submitted = false;
var songs;
var songIndex = 0;
var songsCorrect = 0;
var guesses = 0;
function play() {
if (!chosen) {
start();
return;
} else if (done) {
return;
} else if (started) {
const button = document.getElementById("button");
if (playing) {
const i = document.getElementById('song-name');
i.focus();
player.pause();
} else {
document.body.focus();
player.resume();
}
playing = !playing;
button.innerHTML = playing ? "Pause!" : "Play!";
} else {
songIndex++;
fetch(`https://api.spotify.com/v1/me/player/play?device_id=${deviceId}`, {
method: 'PUT',
body: JSON.stringify({ uris: [songs[songIndex].uri] }),
headers: headers
}).then(r => {
started = true;
playing = true;
submitted = false;
const button = document.getElementById("button");
button.innerHTML = "Pause!";
});
}
}
function start() {
getSongs().then(s => {
songs = s;
for (let i = songs.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = songs[i];
songs[i] = songs[j];
songs[j] = temp;
}
const song = songs[0];
console.log(song);
fetch(`https://api.spotify.com/v1/me/player/play?device_id=${deviceId}`, {
method: 'PUT',
body: JSON.stringify({ uris: [song.uri] }),
headers: headers
}).then(r => {
started = true;
playing = true;
chosen = true;
const button = document.getElementById("button");
button.innerHTML = "Pause!";
});
});
}
async function getSongs() {
const mode = document.getElementById("media-type").value;
let id = document.getElementById("search-results").value;
const res = await fetch(`https://api.spotify.com/v1/${mode}s/${id}/tracks`, {
method: 'GET',
headers: headers
});
let tempSongs = [];
let json = await res.json();
console.log(json);
for (const song of json.items) {
if (mode === 'playlist') {
tempSongs.push(song.track);
} else {
tempSongs.push(song);
}
}
return tempSongs;
}
async function getPlaylists() {
return (await fetch("https://api.spotify.com/v1/me/playlists", {
method: 'GET',
headers: headers
})).json();
}
function toOption(text, value) {
let option = document.createElement("option");
}
function mediaTypeChange() {
const type = document.getElementById("media-type");
let options = document.getElementById("search-results");
let topResult = document.getElementById("top-result");
if (type.value === "playlist") {
getPlaylists().then(playlists => {
topResult.text = playlists.items.length ? "Choose playlist" : "No playlists exist";
for (let i = options.length; i > 0; i--) {
options.remove(i);
}
for (const playlist of playlists.items) {
let option = document.createElement("option");
option.text = playlist.name;
option.value = playlist.id;
options.add(option);
}
});
} else if (type.value === "album") {
topResult.text = "Search for an album"
} else {
topResult.text = "Select collection type"
}
}
function submit() {
let song = songs[songIndex];
let button = document.getElementById("button");
if (playing) {
player.pause();
button.innerHTML = "Play!";
playing = false;
}
button.disabled = false;
started = false;
done = false;
submitted = true;
let input = document.getElementById("song-name");
console.log(input.value, song.name, correct(input.value, song.name));
input.value = "";
}
function cleanString(s) {
let n = "";
for (let c of s) {
let p = c.toLowerCase().charCodeAt(0);
if (97 <= p && p <= 122) {
n += c.toLowerCase();
}
}
return n;
}
function correct(guess, real) {
if (levenshtein(cleanString(real), cleanString(guess)) <= 2) {
songsCorrect++;
}
guesses++;
document.getElementById('progress').innerHTML = `Progress: ${guesses}/${songs.length}`;
document.getElementById('correct').innerHTML = `Correct: ${songsCorrect}/${guesses}`;
document.getElementById('last').innerHTML = `Last: ${real}`;
return levenshtein(cleanString(real), cleanString(guess)) <= 2;
}
async function search() {
let search = document.getElementById("search").value;
let topResult = document.getElementById("top-result");
let res = await fetch(`https://api.spotify.com/v1/search?q=${search}&type=album&limit=10`, {
method: 'GET',
headers: headers
})
console.log(res);
let reader = res.body.getReader();
const decoder = new TextDecoder();
let s = "";
while (1) {
const chunk = await reader.read();
console.log(chunk.done);
if (chunk.done) {
break;
} else {
s += decoder.decode(chunk.value);
}
}
const response = JSON.parse(s);
console.log(response);
let options = document.getElementById("search-results");
for (let i = options.length; i > 0; i--) {
options.remove(i);
}
for (const album of response.albums.items) {
let option = document.createElement("option");
option.text = `${album.name} by ${album.artists[0].name}`;
option.value = album.id;
options.add(option);
}
topResult.text = "Choose album"
}
function updateTimer() {
const clock = document.getElementById("time");
player.getCurrentState().then(state => {
if (!state) {
return;
}
const timeLeft = 30 * 1000 - state.position;
clock.innerHTML = Math.max(0, Math.floor(timeLeft / 1000));
if (timeLeft <= 0 && !done && !submitted) {
done = true;
player.pause();
let button = document.getElementById("button");
button.disabled = true;
button.innerHTML = "Pause!";
}
});
}
setInterval(updateTimer, 1000);
function levenshtein(a, b) {
if (!a || !b) {
return (a || b).length;
}
let m = [];
for (let i = 0; i <= b.length; i++) {
m[i] = [i];
if(i === 0) {
continue;
}
for (let j = 0; j <= a.length; j++) {
m[0][j] = j;
if(j === 0) {
continue;
}
m[i][j] = b.charAt(i - 1) == a.charAt(j - 1) ? m[i - 1][j - 1] : Math.min(
m[i-1][j-1] + 1,
m[i][j-1] + 1,
m[i-1][j] + 1
);
}
}
return m[b.length][a.length];
};
|
import Product from './Product';
import Profile from './Profile';
import Jaringan from './Jaringan';
import Splash from './Splash';
import Login from './Login';
import Register from './Register';
import Dashboard from './Dashboard';
import Menu from './Menu';
import Keranjang from './Keranjang';
import DetailProduct from './DetailProduct';
import Scan from './Scan';
import CheckOut from './CheckOut';
import TopUp from './TopUp';
import Transfer from './Transfer';
import History from './History';
import Agen from './Agen';
import Api from './Api';
import HistoryPoint from './HistoryPoint';
import HistoryOrder from './HistoryOrder';
import HistoryOrderDetail from './HistoryOrderDetail';
import OTP from './Otp';
import Bank from './Bank';
import WithDraw from './WithDraw';
import Downline from './Downline';
import HistoryOrderMasuk from './HistoryOrderMasuk'
import Notif from './Notif';
import Reset from './Reset';
import UploadImg from './UploadImg';
import LogNotif from './LogNotif';
import UpgradeType from './UpgradeType';
import Tree from './Tree'
import Courier from './Courier'
import Pay from './TopUp/pay';
import Geocoding from './Geocoding';
export {
Product,
Profile,
Jaringan,
Login,
Splash,
Register,
Dashboard,
Menu,
Keranjang,
DetailProduct,
Scan,
CheckOut,
TopUp,
Transfer,
History,
Agen,
Api,
HistoryPoint,
HistoryOrder,
HistoryOrderDetail,
OTP,
Bank,
WithDraw,
Downline,
HistoryOrderMasuk,
Notif,
Reset,
UploadImg,
LogNotif,
UpgradeType,
Tree,
Courier,
Pay,
Geocoding
};
|
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/core/styles';
import { Link } from 'react-router-dom';
import {
Typography,
IconButton,
Grid,
List,
ListItem,
} from '@material-ui/core';
import MailOutlineIcon from '@material-ui/icons/MailOutline';
import InstagramIcon from '@material-ui/icons/Instagram';
import WhatsAppIcon from '@material-ui/icons/WhatsApp';
import { Image } from 'components/atoms';
const useStyles = makeStyles(theme => ({
root: {
padding: theme.spacing(6, 0),
[theme.breakpoints.up('md')]: {
padding: theme.spacing(12, 0),
},
background: theme.palette.background.footer,
},
footerContainer: {
maxWidth: theme.layout.contentWidth,
width: '100%',
margin: '0 auto',
padding: theme.spacing(0, 2),
},
logoContainerItem: {
paddingTop: 0,
},
logoContainer: {
width: 240,
height: 64,
},
logoImage: {
width: '100%',
height: '100%',
},
socialIcon: {
padding: 0,
marginRight: theme.spacing(1),
color: 'rgba(255,255,255,.6)',
'&:hover': {
background: 'transparent',
},
'&:last-child': {
marginRight: 0,
},
},
icon: {
fontSize: 26,
},
copyright: {
color: 'white',
},
dataPrivacy: {
color: '#FFF',
'&:hover': {
color: '#f57c00',
},
},
}));
const Footer = props => {
const { pages, className, ...rest } = props;
const classes = useStyles();
return (
<div {...rest} className={clsx(classes.root, className)}>
<div className={classes.footerContainer}>
<Grid container spacing={4}>
<Grid item xs={12} md={2}>
<List disablePadding>
<ListItem disableGutters className={classes.logoContainerItem}>
<div className={classes.logoContainer}>
<a href="/home" title="Mullers">
<Image
className={classes.logoImage}
src="/assets/images/photos/muller/logo_footer.svg"
alt="thefront"
lazy={false}
/>
</a>
</div>
</ListItem>
<ListItem disableGutters>
<IconButton className={classes.socialIcon}>
<InstagramIcon className={classes.icon} />
</IconButton>
<IconButton className={classes.socialIcon}>
<MailOutlineIcon className={classes.icon} />
</IconButton>
<IconButton className={classes.socialIcon}>
<WhatsAppIcon className={classes.icon} />
</IconButton>
</ListItem>
</List>
</Grid>
<ListItem>
<Typography variant="subtitle1" className={classes.copyright}>
© 2021 Muller's, LTD. All rights reserved ||{' '}
<Link to="/dataPrivacy" className={classes.dataPrivacy}>
{' '}
Adatkezelési szabályzat{' '}
</Link>
</Typography>
</ListItem>
</Grid>
</div>
</div>
);
};
Footer.propTypes = {
className: PropTypes.string,
pages: PropTypes.object.isRequired,
};
export default Footer;
|
/**
* mallActions
* @params getState() 读取redux的store
*/
import * as actionTypes from "./actionTypes";
import * as requestApi from "../config/requestApi";
// 请求商品分类列表
export function fetchGoodsCategoryLists(data) {
return (dispatch, getState) => {
dispatch({ type: actionTypes.FETCH_GOODSCATEGORYLISTS, data });
};
}
// 更改商品分类列表的选中状态
export function changeGoodsCategoryList(params) {
return (dispatch, getState) => {
let data = getState().mallReducer.goodsCategoryLists;
for (let i = 0; i < data.length; i++) {
data[i].selected_status = false;
if (params.code === data[i].code) {
data[i].selected_status = true;
}
}
dispatch({ type: actionTypes.CHANGE_GOODSCATEGORYLIST, data });
};
}
// 私人分类列表修改
export function changePreCategoryList(data) {
return (dispatch, getState) => {
dispatch({ type: actionTypes.CHANGE_PRECATEGORYLIST, data });
};
}
/**
* 根据商品类目查询
* @param {*} params 参数
* @param {*} isFirst 是否第一次加载
* @param {*} isLoadingMore 是否加载更多
* @param {*} type 搜索结果还是商品一级列表或者二级列表
*/
export function fetchGoodsLists(
params,
isFirst = false,
isLoadingMore = false,
type = null
) {
return (dispatch, getState) => {
if (isFirst) {
type === "search"
? dispatch({ type: actionTypes.FETCH_RESULTLISTS_RESET })
: type === "children"
? dispatch({ type: actionTypes.FETCH_GOODSCLDLISTS_RESET })
: dispatch({ type: actionTypes.FETCH_GOODSLISTS_RESET });
} else {
if (isLoadingMore) {
type === "search"
? dispatch({
type: actionTypes.FETCH_RESULTLISTS_MORE_BEFORE
})
: type === "children"
? dispatch({
type: actionTypes.FETCH_GOODSCLDLISTS_MORE_BEFORE
})
: dispatch({
type: actionTypes.FETCH_GOODSLISTS_MORE_BEFORE
});
} else {
type === "search"
? dispatch({ type: actionTypes.FETCH_RESULTLISTS_BEFORE })
: type === "children"
? dispatch({ type: actionTypes.FETCH_GOODSCLDLISTS_BEFORE })
: dispatch({ type: actionTypes.FETCH_GOODSLISTS_BEFORE });
}
}
params = {
...params,
page:
type === "search"
? getState().mallReducer.resultListsPage
: type === "children"
? getState().mallReducer.goodsCldListsPage
: getState().mallReducer.goodsListsPage
};
requestApi.requestSearchGoodsList(params).then(data => {
console.log('datadata', data)
if (isLoadingMore) {
type === "search"
? dispatch({
type: actionTypes.FETCH_RESULTLISTS_MORE,
data
})
: type === "children"
? dispatch({
type: actionTypes.FETCH_GOODSCLDLISTS_MORE,
data
})
: dispatch({
type: actionTypes.FETCH_GOODSLISTS_MORE,
data
});
} else {
type === "search"
? dispatch({
type: actionTypes.FETCH_RESULTLISTS,
data
})
: type === "children"
? dispatch({
type: actionTypes.FETCH_GOODSCLDLISTS,
data
})
: dispatch({
type: actionTypes.FETCH_GOODSLISTS,
data
});
}
}).catch(error => {
if (isLoadingMore) {
type === "search"
? dispatch({
type: actionTypes.FETCH_RESULTLISTS_MORE_FAILED
})
: type === "children"
? dispatch({
type: actionTypes.FETCH_GOODSCLDLISTS_MORE_FAILED,
data
})
: dispatch({
type: actionTypes.FETCH_GOODSLISTS_MORE_FAILED
});
} else {
type === "search"
? dispatch({
type: actionTypes.FETCH_RESULTLISTS_FAILED
})
: type === "children"
? dispatch({
type: actionTypes.FETCH_GOODSCLDLISTS_FAILED
})
: dispatch({
type: actionTypes.FETCH_GOODSLISTS_FAILED
});
}
});
};
}
// 购物车列表
export function fetchMallCartList(params, callback = () => { }) {
return (dispatch, getState) => {
requestApi
.requestMallCartList(params)
.then(data => {
console.log(data)
if (data) {
data.data.forEach(item => {
// 添加是否选中状态
item.selected_status = false;
});
dispatch({
type: actionTypes.FETCH_MALLCARTLIST,
data: data.data
});
callback(data.data);
} else {
dispatch({
type: actionTypes.FETCH_MALLCARTLIST,
data: []
});
}
})
.catch(error => {
//
});
};
}
// 更改购物车列表商品
export function changeMallCartList(item) {
return (dispatch, getState) => {
let data = getState().mallReducer.cartLists;
for (let i = 0; i < data.length; i++) {
if (item.id === data[i].id) {
data[i] = item;
}
}
dispatch({ type: actionTypes.CHANGE_MALLCARTLIST, data });
};
}
//单纯修改一些状态
export function mallChangeState(params) {
return (dispatch, getState) => {
dispatch({ type: actionTypes.MALL_CHANGE_STATE, data: params });
};
}
// 支付订单信息储存
export function payOrderInfo(params) {
return (dispatch, getState) => {
dispatch({ type: actionTypes.SOM_PAY_PARAMS, data: params });
};
}
// 记录进入收银台的路由
export function recordPayRouter(params) {
return (dispatch, getState) => {
dispatch({ type: actionTypes.SOM_PAY_RECORDROUTER, data: params });
};
}
// 记录SOM和WM路由key
export function recordRouterKey(params) {
return (dispatch, getState) => {
dispatch({ type: actionTypes.RECORDROUTER, data: params });
};
}
// 获取批发商城 banner
export function getSOMBannerList(params={},callback=() => {},errorCallBack = () => { }) {
return (dispatch, getState) => {
console.log(getState())
requestApi.requestSOMBannerList({
regionCode: global.regionCode,
bannerModule: "MERCHANT_SELF_SHOP"
}).then(data => {
console.log('initBannerData',data)
dispatch({ type: actionTypes.WMBANNERLIST, data: bannerLists});
}).catch(err => {
errorCallBack(err)
Loading.hide();
});
};
}
// 推荐商品 列表
export function cacheSOMData(params={page: 1,limit: 10,jCondition: {districtCode: ''}},isLoadingMore,errorCallBack = () => { }) {
return (dispatch, getState) => {
console.log('getState()',getState())
// 获取已存的数据
let prevGoodsList = getState().mallReducer.recommendGoodsList.goodLists;
let prevBannerList = getState().mallReducer.bannerList_som;
if (prevBannerList.length === 0 || prevGoodsList.length === 0 && !isLoadingMore) {
Loading.show()
}
if (isLoadingMore) {
getGoodsRecommendGoods(params,getState,dispatch,prevBannerList,errorCallBack)
return
}
// 获取bannerList
requestApi.requestSOMBannerList({
regionCode: global.regionCode,
bannerModule: "MERCHANT_SELF_SHOP"
}).then(data => {
console.log('bannerlist',data)
return bannerList = data || [];
}).then((bannerList) => {
getGoodsRecommendGoods(params,getState,dispatch,bannerList,errorCallBack)
}).catch((err) => {
getGoodsRecommendGoods(params,getState,dispatch, [], errorCallBack)
});
};
}
const getGoodsRecommendGoods = (params = {page: 1,limit: 10,condition: {districtCode: ''}},getState = () => {},dispatch = () => {},bannerList = [],errorCallBack = () => {}) => {
let cacheData = {
bannerList: [],
recommendGoodsList: {
goodLists: [],
page: 1,
limit: 10,
refreshing: false,
hasMore: false,
total: 0,
}
}
let prevGoodsList = getState().mallReducer.recommendGoodsList.goodLists;
let total = getState().mallReducer.recommendGoodsList.total;
// 获取推荐数据
requestApi.requestMallGoodsRecommendSGoodsQPage(params).then(data => {
console.log('redxxx',data)
let _data;
if (params.page === 1) {
_data = data ? data.data : [];
} else {
_data = data ? [...prevGoodsList, ...data.data] : prevGoodsList;
}
let _total = params.page === 1
? (data)
? data.total
: 0
: total;
let hasMore = data ? _total !== _data.length : false;
cacheData.recommendGoodsList = {
goodLists: _data,
page:params.page,
limit: params.limit,
refreshing: false,
hasMore,
total:_total,
}
cacheData.bannerList = bannerList;
console.log("cacheData",cacheData)
dispatch({ type: actionTypes.SOMCACHEDATA, cacheData });
}).catch((err) => {
Toast.show(err.message)
// let prevGoodsList = getState().mallReducer.recommendGoodsList
// let prevBannerList = getState().mallReducer.bannerList_som;
// cacheData.bannerList = prevBannerList;
// cacheData.recommendGoodsList = prevGoodsList;
// dispatch({ type: actionTypes.SOMCACHEDATA, cacheData });
});
}
// 订单列表数据
export function fetchMallOrderList (params={ orderStatus: 'PRE_PAY',limit: 10,page:1,currentTab:0 }) {
return (dispatch, getState) => {
let currentTab = params.currentTab
let prevOrderList = getState().mallReducer.SOMOrderList
requestApi.fetchMallOrderList(params).then(data => {
console.log("%cDatadatadatadata", "color:red", data);
let _data;
if (params.page === 1) {
_data = data ? data.data : [];
} else {
_data = data ? [...prevOrderList[currentTab].data, ...data.data] : prevOrderList[currentTab].data;
}
let _total = params.page === 1 ? (data ? data.total : 0) : prevOrderList[currentTab].total;
let hasMore = data ? _total !== _data.length : false;
let obj = {
data: _data,
page: params.page,
limit: 10,
refreshing: false,
hasMore,
total: _total,
}
prevOrderList[currentTab] = obj
console.log('prevOrderList',prevOrderList)
dispatch({ type: actionTypes.SOMORDERLIST, orderList: JSON.parse(JSON.stringify(prevOrderList)) })
}).catch((err) => {
Toast.show(err.message)
// console.log('err',err)
// let prevOrderList = getState().mallReducer.SOMOrderList
// dispatch({ type: actionTypes.SOMORDERLIST, orderList: prevOrderList })
});
};
}
// 售后订单
export function fetchMallRefundOrderList (params={ limit: 10,page:1,currentTab: 5}) {
return (dispatch, getState) => {
let prevOrderList = getState().mallReducer.SOMOrderList
let currentTab = params.currentTab
requestApi.fetchMallRefundOrderList(params).then(data => {
let _data;
if (params.page === 1) {
_data = data ? data.data : [];
} else {
_data = data ? [...prevOrderList[currentTab].data, ...data.data] : prevOrderList[currentTab].data;
}
let _total = params.page === 1 ? (data ? data.total : 0) : prevOrderList[currentTab].total;
let hasMore = data ? _total !== _data.length : false;
let obj = {
data: _data,
page: params.page,
limit: 10,
refreshing: false,
hasMore,
total: _total,
}
prevOrderList[currentTab] = obj
dispatch({ type: actionTypes.SOMORDERLIST, orderList: prevOrderList })
}).catch((err) => {
Toast.show(err.message)
// console.log(err)
// let prevOrderList = getState().mallReducer.SOMOrderList
// dispatch({ type: actionTypes.SOMORDERLIST, orderList: prevOrderList })
});
}
}
// 售后退款金额
export function setRefundAmount (afterSaleGoods, orderInfo) {
return (dispatch, getState) => {
let temp = afterSaleGoods.map(item => {
return {
goodsId: item.goodsId,
goodsSkuCode: item.goodsSkuCode
}
})
let params = {
itemIds: temp,
orderId: orderInfo.orderId
}
requestApi.sOrderRefundApplyAmount(params).then(res => {
console.log('获取的售后金额',res)
if (res) {
dispatch({ type: actionTypes.SETREFUNDAMOUNT, refundAmount: res.amount })
}
}).catch(err => {
console.log(err)
})
}
}
|
import Container from "../components/Container";
import CarouselComp from "../components/Carousel";
import Items from "../components/Items";
import Footer from "../components/Footer";
import dataService from "../services/data";
const Index = () => {
const { newItems, topSelling, itemsCarousel } = dataService;
return (
<Container title="Home">
<CarouselComp items={itemsCarousel} />
<Items items={newItems} section="Nuevos productos" />
<div className="guarantee">
<div className="cardGuarantee">
<p>
<img
src="https://res.cloudinary.com/robcg1102/image/upload/v1604355701/maq_img/envios_q0wcb4.png"
alt="envios"
/>
</p>
<h4>Envíos y devoluciones</h4>
<p>Entrega garantizada en máximo de 48 horas.</p>
</div>
<div className="cardGuarantee">
<p>
<img
src="https://res.cloudinary.com/robcg1102/image/upload/v1604355701/maq_img/devolucion_m5gbfk.png"
alt="garantia"
/>
</p>
<h4>Garantía de devolución</h4>
<p>Clientes 100% satisfechos.</p>
</div>
<div className="cardGuarantee">
<p>
<img
src="https://res.cloudinary.com/robcg1102/image/upload/v1604355700/maq_img/clientes_vjedk8.png"
alt="satisfechos"
/>
</p>
<h4>Clientes satisfechos</h4>
<p>Ofrecemos la mejor variedad de productos.</p>
</div>
</div>
<Items items={topSelling} section="Más vendidos" />
<Footer />
</Container>
);
};
export default Index;
|
import * as Benchmark from 'benchmark';
import * as lfo from 'waves-lfo/common';
import * as Meyda from 'meyda';
export function getFftSuites(buffer, bufferLength, sampleRate, log) {
const suites = [256, 1024, 4096].map((frameSize) => {
return function(next) {
const numFrames = Math.floor(bufferLength / frameSize);
const suite = new Benchmark.Suite();
const fft = new lfo.operator.Fft({
window: 'hamming',
mode: 'magnitude',
size: frameSize,
});
fft.initStream({
frameSize: frameSize,
frameType: 'signal',
sourceSampleRate: sampleRate,
});
suite.add(`lfo:fft\t\tframeSize: ${frameSize}\t`, {
fn: function() {
for (let i = 0; i < numFrames; i++) {
const start = i * frameSize;
const end = start + frameSize;
const frame = buffer.subarray(start, end);
const res = fft.inputSignal(frame);
}
},
});
Meyda.bufferSize = frameSize;
Meyda.sampleRate = sampleRate;
suite.add(`meyda:fft\tframeSize: ${frameSize}\t`, {
fn: function() {
for (let i = 0; i < numFrames; i++) {
const start = i * frameSize;
const end = start + frameSize;
const frame = buffer.subarray(start, end);
const res = Meyda.extract('amplitudeSpectrum', frame);
}
},
});
suite.on('cycle', function(event) {
log.push(String(event.target));
});
suite.on('complete', function() {
log.push('==> Fastest is ' + this.filter('fastest').map('name') + '\n');
next();
});
suite.run({ async: false });
}
});
return suites;
}
|
import axios from 'axios';
import qs from 'qs';
let url = 'https://1e4e3372.ngrok.io';
export const api = {
login: '/login',
check: '/check',
points: '/points',
logout: '/logout',
register: '/register',
clear: '/clear',
recheck: '/recheck',
events: '/events',
};
export class Api {
static check(x, y, r) {
return axios({
url: url + api.check,
method: 'post',
withCredentials: true,
data: qs.stringify({ x, y, r }),
});
}
static setUrl(newUrl) {
url = newUrl;
console.log("changed url", newUrl);
}
static points() {
return axios.get(url + api.points, { withCredentials: true });
}
static login(username, password) {
return axios({
method: 'post',
url: url + api.login,
data: qs.stringify({ username, password }),
withCredentials: true
});
}
static logout() {
return axios.get(url + api.logout, { withCredentials: true });
}
static register(username, password) {
return axios({
url: url + api.register,
data: qs.stringify({
username,
password
}),
method: 'post',
});
}
static clear() {
return axios.get(url + api.clear, { withCredentials:true });
}
static recheck(points) {
return axios({
url: url + api.recheck,
method: 'post',
data: points,
withCredentials: true
})
}
static events() {
return axios.get(url + api.events, {withCredentials: true});
}
}
/*
Написать отдельный модуль-прослойку для общения с REST апи на промисаъ
Api.check(x, y, z);
Api.points();
Api.login(username, password);
Api.logout()
*/ |
import {Link} from 'react-router-dom'
import debounce from 'lodash/debounce'
import {connect} from 'react-redux'
import LabeledInput from '../common/LabeledInput'
import {getPatientList} from '../../actions/patients'
import React, {Component} from 'react'
class PatientList extends Component {
constructor(props, context) {
super(props, context)
this.state = { searchText: '' }
this.performSearchWithDelay = debounce(this.performSearch, 300)
}
componentDidMount() {
this.performSearch()
}
componentDidUpdate(prevProps, prevState) {
if (prevState.searchText !== this.state.searchText) this.performSearchWithDelay()
}
performSearch() {
this.props.dispatch(getPatientList({
search: this.state.searchText
}))
}
renderPatient = (patient) => {
return (
<Link className="Box PatientList-result" key={patient.id} to={`/patients/${patient.id}`}>
<div className="PatientList-resultTitle">{patient.last_name}, {patient.first_name}</div>
</Link>
)
}
render() {
const {
props: { searchResult, searchLoading },
state: { searchText }
} = this
return (
<div className="PatientList">
<div className="PatientList-wrap">
<div className="PatientList-sidebar">
<LabeledInput
label = "Search"
value = {searchText}
onChange = {(evt) => this.setState({ searchText: evt.target.value })}
placeholder = "ex: Jane Smith or 708-867-5309"
/>
</div>
<div className="PatientList-results">
{searchLoading &&
<div className="PatientList-resultsLoading">Loading...</div>
}
{searchResult && searchResult.map(this.renderPatient)}
</div>
</div>
</div>
)
}
}
export default connect(
(state) => ({
searchResult : state.patients.searchResult,
searchLoading : state.patients.searchLoading,
searchError : state.patients.searchError,
})
)(PatientList)
|
const express = require('express');
global.fetch = require('node-fetch');
const config = require('universal-config');
const Unsplash = require('unsplash-js').default;
const unsplashToJson = require('unsplash-js').toJson;
//---------------without universal config-------------------
// const api = require('./config/server');
// const unsplash = new Unsplash({
// applicationId: api.applicationId,
// secret: api.secret,
// callbackUrl: api.callbackUrl
// });
//------------------------config unsplash api using universal config-----------------------
// learn this way from brad
const unsplash = new Unsplash({
applicationId: config.get('applicationId'),
secret: config.get('secret'),
callbackUrl: config.get('callbackUrl')
});
//------------------start express--------------------
const app = express();
//@router Get api/images
//@desc Getting Photo From Api And Sending To Client Side
//access public
app.get('/api/images' , (req , res) => {
const {startImage , countImage} = req.query;
unsplash.photos.listPhotos(startImage , countImage )
.then(unsplashToJson)
.then(photos =>{
if(!photos) {res.status(400).json('fuck')}
res.json(photos);
});
});
//running server
const port = process.env.Port || 5000;
app.listen(port , () => {
console.log(`server in up in port : ${port}`)
}); |
import { each, mapValues, isObject, assign } from 'lodash'
var styleDefaultsFns = []
export function addStyleDefaults(fn) {
styleDefaultsFns.push(fn)
}
export function applyStyleDefaults(viewName, props) {
if (!styleDefaultsFns.length) {
return
}
if (typeof props.style == 'number') {
console.warn("TODO: setStyleDefaults does not yet work with tags.StyleSheet")
return
}
if (!props.style) {
props.style = {}
}
var defaultStyles = {}
each(styleDefaultsFns, (styleDefaultsFn) => {
var newDefaultStyles = styleDefaultsFn(viewName)
if (!newDefaultStyles) {
return
} else if (!isObject(newDefaultStyles)) {
throw new Error('function passed in to setStyleDefaults return non-object value: '+newDefaultStyles)
}
assign(defaultStyles, newDefaultStyles)
})
if (!Object.isExtensible(props.style)) {
props.style = mapValues(props.style, (val) => val) // copy
}
each(defaultStyles, (val, key) => {
if (props.style[key] == undefined) {
props.style[key] = val
}
})
} |
export default {
setUser (state, user) {
state.user = user
},
setUserPlaylist (state, playlist) {
state.userPlaylist = playlist
}
}
|
import React, { useState } from 'react'
import uuid from '../node_modules/uuid/dist/v4'
import './style.css'
function TodoApp() {
const [todo, setTodo] = useState('')
const handleChange = e => {
setTodo(e.target.value)
}
const [todoList, setTodoList] = useState([]);
const handleSubmit = e => {
e.preventDefault();
if (todo !== "") {
const newTodo = {
id: uuid(),
value: todo,
complated: false
}
setTodoList([...todoList, newTodo])
}
setTodo('')
}
const removeTodo = id => {
setTodoList(todoList.filter((t) => t.id !== id))
}
const IsComplated = (id) => {
const element = todoList.findIndex(item => item.id === id)
const newTodoList = [...todoList];
newTodoList[element] = {
...newTodoList[element], complated: true
}
setTodoList(newTodoList);
}
return (
<div className="container">
<form onSubmit={handleSubmit}>
<input
value={todo}
onChange={handleChange}
/>
<button>ADD</button>
</form>
<h1>Your todos:</h1>
{todoList !== [] ? (
<ul>
{todoList.map(item =>
<li className={item.complated ? 'complated' : 'not-complated'} key={item.id}>
{item.value}
<div className="buttons">
<button onClick={() => removeTodo(item.id)}>remove</button>
<button onClick={() => IsComplated(item.id)}><i className={item.complated ? 'fas fa-check' : 'far fa-circle'}></i></button>
</div>
</li>)}
</ul>
)
:null
}
</div>
)
}
export default TodoApp
|
const buttonSearch = document.querySelector('main .row_text a');
const modal = document.querySelector('#modal');
const close = document.querySelector('#modal .header a');
buttonSearch.addEventListener('click', () => {
modal.classList.remove('hide');
// abre opoção pesquisar
});
close.addEventListener('click', () => {
modal.classList.add('hide');
// fecha opção pesquisar
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.