text stringlengths 7 3.69M |
|---|
import request from '@/utils/request'
/**
* 版本
* @constant
* @type {string}
* @default
* */
/**
* 获取所有节点简单信息
* @param {*} params 节点参数
*/
export function GetList(params) {
return request({
url: `/hosts`,
method: 'get',
params
})
}
/**
* 根据uuid获取节点详细信息
* @param {*} uuid 节点uuid
*/
export function GetNodeInfo(uuid) {
return request({
url: `/hosts/${uuid}/info`,
method: 'get'
})
}
/**
* 添加节点
* @param {*} data 节点参数
*/
export function SaveNodeEntity(data) {
return request({
url: `/hosts`,
method: 'post',
data
})
}
/**
* 删除节点
* @param {*} uuid 节点UUID
*/
export function DeleteEntityOne(uuid) {
return request({
url: `/hosts/${uuid}`,
method: 'delete'
})
}
/**
* 修改节点信息
* @param {*} params 节点参数
*/
export function UpdateEntityOne(params) {
return request({
url: '/updateNodeEntityOne',
method: 'post',
params
})
}
/**
* 对单个主机绑定标签
* @param uuid 主机uuid
* @param data 标签uuid和资源类别 {{LabelUUID,ResourceType}}
*/
export function StickLabelToHost(uuid, data) {
return request({
url: `/hosts/${uuid}/labels`,
method: 'post',
data
})
}
/**
* 获取单个主机所有绑定标签信息
* @param uuid hostUUID
*/
export function GetTagOfHost(uuid) {
return request({
url: `/hosts/${uuid}/labels`,
method: 'get'
})
}
/**
* 取消单个主机下某个标签的绑定关系
* @param hostUUID 主机uuid
* @param labelUUID 标签uuid
*/
export function DeleteTagOfHost(hostUUID, labelUUID) {
return request({
url: `/hosts/${hostUUID}/labels/${labelUUID}`,
method: 'delete'
})
}
|
import * as THREE from 'three';
import CANNON from 'cannon';
import objectGenerator from '../utils/objectGenerator';
export default class Cube {
constructor({ size, position, color, texture, mass }) {
this.mesh = objectGenerator({
geometry: new THREE.BoxGeometry(...size),
material: new THREE.MeshLambertMaterial({ color }),
texture: texture,
position: position,
params: {
castShadow: true,
}
});
const cubeShape = new CANNON.Box(new CANNON.Vec3(size[0] / 2, size[1] / 2, size[2] / 2));
const cubeMaterial = new CANNON.Material();
cubeMaterial.friction = 0;
this.body = new CANNON.Body({
mass: mass,
shape: cubeShape,
material: cubeMaterial,
});
this.body.position.set(...position);
}
updatePosition = () => {
this.mesh.position.copy(this.body.position);
}
}
|
(function() {
angular.module( 'Together' )
.controller( 'MainController', MainController );
function MainController( $scope ) {
}
})();
|
import React,{ Component } from 'react';
import { Panel } from '@bumaga/tabs';
import InputForm from './InputForm';
export default class ContactPanel extends Component{
render() {
return (
<Panel>
<InputForm />
</Panel>
);
}
} |
angular.module('factController', [])
// inject the Fact service factory into our controller
.controller('mainController', ['$scope', '$http', 'Facts', function ($scope, $http, Facts) {
$scope.formData = {};
// GET =====================================================================
// when landing on the page, get all facts and show them
// use the service to get all the facts
Facts.get()
.success(function (data) {
$scope.facts = data;
});
// CREATE ==================================================================
// when submitting the add form, send the text to the node API
$scope.createFact = function () {
$scope.processing = true;
if ($scope.formData.text != undefined) {
// call the create function from our service (returns a promise object)
Facts.create($scope.formData)
// if successful creation, call our get function to get all the new facts
.success(function (data) {
$scope.facts = data; // assign our new list of facts
$scope.processing = false;
});
$scope.formData = {}; // clear the form so our user is ready to enter another
}
if ($scope.formData.text == undefined)
$scope.processing = false;
};
// DELETE ==================================================================
// delete a fact after checking it
$scope.deleteFact = function (id) {
Facts.delete(id)
// if successful creation, call our get function to get all the new facts
.success(function (data) {
$scope.facts = data; // assign our new list of facts
});
};
}]); |
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const zoomPlayer = require('./lib/zoomplayer.js');
const vlc = require('./lib/vlc.js');
const m3u = require('./lib/m3u.js');
const util = require('./lib/util.js');
const conf = JSON.parse(fs.readFileSync(__dirname+'/../conf.json', 'utf-8'));
function parseDate(str) {
let match = str.match(/([0-9]{4}) ([0-9]{2}) ([0-9]{2})/);
let date = new Date();
date.setFullYear(match[1]);
date.setMonth(match[2] - 1);
date.setDate(match[3]);
return date;
}
function copyFile(shortFileName, originFile, destinationFile) {
let destDir = path.dirname(destinationFile);
fs.mkdir(destDir, { recursive: true }, (err) => {
if (err) {
console.log(`Error creating folder ${destDir}`, err);
} else {
fs.stat(originFile, (err, originStats) => {
fs.stat(destinationFile, (err, destinationStats) => {
if (err || originStats.size != destinationStats.size) {
console.log(`Copying ${shortFileName}`);
fs.copyFile(originFile, destinationFile, (err) => {
if (err) {
console.log(`Error copying ${originFile} to ${destinationFile}`, err);
}
});
}
});
});
}
});
}
// find playlists to back up
fs.readdir(path.normalize(conf.sourceFolder), { encoding: 'utf-8', withFileTypes: true }, (err, files) => {
if (err) {
console.log("ERROR", err);
return;
}
let now = new Date(Date.now());
files.forEach(playlistFile => {
if (playlistFile.isDirectory() || !playlistFile.isFile()) {
return;
}
let playlistFilename = path.normalize(conf.sourceFolder+'/'+playlistFile.name);
if (playlistFile.name.match(/\.zpl$/)) {
let playlistName = playlistFile.name.replace(/\.zpl$/, '');
let playlistDate = parseDate(playlistName);
if (playlistDate < now) {
return;
}
zoomPlayer.readPlaylist(playlistFilename, (items) => {
console.log("\n\nPLAYLIST:", playlistName);
let destinationFolder = conf.destinationFolder+'/'+playlistName;
let ndigits = util.countDigits(items.length);
console.log(`${items.length} items: ${ndigits} digits`);
let n = 1;
items = items.map(item => {
let destinationFile = util.transformPath(item.filename, conf.baseFolders, destinationFolder, conf.unspace, conf.flattenFolders, n++, ndigits);
let shortName = destinationFile.replace(destinationFolder, '').replace(/^\//, '');
let destinationItem = {
filename: destinationFile,
name: item.name,
duration: item.duration,
};
copyFile(shortName, item.filename, destinationFile);
return destinationItem;
});
// let destinationPlaylist = conf.destinationFolder+'/'+playlistName+'.xspf';
// console.log(`Writing playlist: ${destinationPlaylist}`);
// vlc.writePlaylist(items, destinationPlaylist, destinationFolder);
// destinationPlaylist = conf.destinationFolder+'/'+playlistName+'.m3u8';
// console.log(`Writing playlist: ${destinationPlaylist}`);
// m3u.writePlaylist(items, destinationPlaylist, destinationFolder);
});
}
});
});
|
import React from 'react';
import FacebookIcon from '@material-ui/icons/Facebook';
import {Link, Grid , makeStyles,Box}from '@material-ui/core/';
const useStyles = makeStyles ({
icono: {
color: 'blue',
fontSize: '18px',
position: 'relative',
float: 'right',
top:-22,
right:30,
},
});
const FaceIcon=(props)=>{
const classes = useStyles();
return(
<FacebookIcon className={classes.icono}/>
)
}
export default FaceIcon; |
var target;
var syllableTemp;
var syllableContainer;
var completeWord;
var part;
function readyOk(){
target=$('#target');
syllableTemp=$('#syllableBlock');
completeWord1 = $('#completeWord1');
completeWord2 = $('#completeWord2');
syllableContainer=$('#syllableContainer');
completeWord=$('#completeWord');
}
function functionInit() {
return new Promise(function(resolve, reject) {
getConfig(14).then(function() {
return getConfigByElement("act14","act",1,null);
}).then(function(c) {
return functionCallback(c);
}).then(function() {
rotateEfect();
removeLoading();
playTutorial(actNum);
resolve();
})
readyOk();
});
}
function rotateEfect(){
// var labels = syllableTemp.find("label");
waitInterval(1000).then( function () {
$("label.star:last-child").addClass("animated flipInY");
});
}
function functionCallback(conf){
return new Promise(function(resolve, reject) {
conf = conf[0];
syllableResult = conf["target"];
resultFirstWord = conf["values"][0];
resultsecondWord = conf["values"][1];
fillTemplateWord(completeWord1,resultFirstWord);
fillTemplateWord(completeWord2,resultsecondWord);
getConfigByElementWithOne("distractors","syllables",
2,functionCallback2,syllableResult).then(function() {
resolve();
})
});
}
function moveToTarget(elem) {
$(target).append(elem);
functionsDD(null,elem);
}
function functionCallback2(conf) {
fillTemplateImages(conf);
images=syllableContainer.children().find("div#syllableTemp");
dragAndDrop(images,target,functionsDD,moveToTarget);
}
function fillTemplateWord(word, part){
$(word).attr('name',part);
addSound(part);
$(word).css({backgroundImage : 'url(images/activities/' + part + '.jpg)'});
$(word).hover(function(){
var elem = this;
$.data(this, "timer", setTimeout($.proxy(function() {
playSound($(elem).attr("name"));
$(this).css('background-image', 'none');
$(this).html("<b>"+part.toString().toUpperCase()+"</b>");
window.setTimeout(function(){
$(word).css({backgroundImage : 'url(images/activities/' + part + '.jpg)'});
$(word).html(" ");
}, 1000);
}, this), 300));
}, function() { clearTimeout($.data(this, "timer")); }
);
}
function fillTemplateImages(syllables){
var syllablesArray=[];
$(syllables).each(function(index,e){
t=$(syllableTemp).clone();
var content= $(t).find("#syllableTemp");
name=e;
addSound(name);
$(t).attr('name',name);
$(t).attr('alt', name);
content.attr('name',name);
content.attr('num',index);
/*Change to make effect*/
name = name.toUpperCase();
content.html(name);
content.hover(function(){
var elem = this;
$.data(this, "timer", setTimeout($.proxy(function() {
playSound($(elem).html());
}, this), 300));
}, function() { clearTimeout($.data(this, "timer")); }
);
$(t).removeClass('hidden');
$(t).hover(function(){
var labels = $(this).find("label");
$(labels).addClass("partialRot");
},
function(){
var labels = $(this).find("label");
$(labels).removeClass("partialRot");
});
syllablesArray.push(t);
});
disorder(syllablesArray);
$(syllableContainer).append(syllablesArray);
}
function setRotEfect(syllableCont){
var labels = syllableCont.find("label");
$(labels).addClass("partialRot");
console.log("over");
}
function removeRotEfect(syllableCont){
var labels = syllableCont.find("label");
$(labels).removeClass("partialRot");
console.log("out");
}
function functionsDD(context,currElem){
isCorrect=checkCorrect(currElem);
if (isCorrect==true){sessionCounter();}
}
function checkCorrect(syllable) {
var name = $(syllable).attr("name");
if(name == syllableResult){
$(syllable).animate({
// width: "20%",
// height: "20%",
// opacity: 1.4,
// marginLeft: "0.6in",
fontSize: "3em",
// borderWidth: "10px",
// borderColor: "green"
color: "green"
}, 500 );
return true;
}
else{
$(syllable).find("label").removeClass('rot');
var origin = $("#syllableBlock[name='"+$(syllable).attr("name")+"']");
wrong(syllable,origin.find("label").last())
window.setTimeout(function(){
$(syllable).find("label").addClass('rot');
}, 1000);
return false;
}
}
|
import { Link } from "react-router-dom";
const Navigator = () => {
return (
<div className="navigator">
<Link to="/">Home</Link>
|
<Link to="courses">Courses</Link>
|
<Link to="students">Students</Link>
</div>
);
};
export default Navigator;
|
exports.run = (client, message, args) => {
const Guild = client.sequelize.import(`../models/Guild`);
const role = message.guild.roles.find(r => r.name === args.join(' '));
if (role) {
message.guild.config.modRole = role.id;
Guild.update({modRole: role.id}, {where: {id: message.guild.id}}).then(message.reply(role.name + " is now the Moderator role."));
}
else {
message.guild.config.modRole = null;
Guild.update({modRole: null}, {where: {id: message.guild.id}}).then(message.reply("The Moderator role has been set to null."));
}
} |
// IMPORTS
// react
import React from "react";
// styled components
import styled from "styled-components";
// components
import Counter from "./Counter";
// COMPONENT
const MissionInput = props => {
// props
const { handleDrawer, status, missions, selectedMission } = props; // eslint-disable-line no-unused-vars
//render
return (
<>
<InputDrawer className={status}>
<DrawerAccent onClick={handleDrawer} />
<CloseButton onClick={handleDrawer}>X</CloseButton>
<InputMessage>
<i className={selectedMission && selectedMission.icon}></i>{" "}
<p key={selectedMission && selectedMission.mission_id}>
{selectedMission && selectedMission.question}
</p>
</InputMessage>
<Counter
missionTracker={props.missionTracker}
setMissionTracker={props.setMissionTracker}
selectedMission={selectedMission}
drawerStatus={props.drawerStatus}
/>
</InputDrawer>
</>
);
};
// STYLED COMPONENTS
const InputDrawer = styled.div`
&.open {
width: 100vw;
height: 35vh;
margin: 0 auto;
border-radius: 5px;
position: fixed;
bottom: 0;
background-color: #6762e3;
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
transition: 0.5s;
}
&.closed {
width: 100vw;
height: 40vh;
margin: 0 auto;
border-radius: 5px;
position: fixed;
bottom: -50vh;
background-color: #6762e3;
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
transition: 0.5s;
}
button {
align-self: flex-end;
margin-bottom: auto;
}
`;
const DrawerAccent = styled.div`
width: 40px;
height: 3px;
border-radius: 50px;
background-color: #fff;
opacity: 0.5;
margin: 0.2rem;
`;
const CloseButton = styled.button`
width: 25px;
height: 25px;
border-radius: 150px;
border: none;
margin: 1rem;
opacity: 0.5;
`;
const InputMessage = styled.div`
margin-bottom: auto;
color: #fff;
font-size: 1.5rem;
letter-spacing: 0.025rem;
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
i {
font-size: 3rem;
margin: 1rem;
}
`;
// const TestComponent = styled.button`
// width: 20rem;
// height: 5rem;
// border-radius: 5px;
// background-color: #fff;
// border: none;
// margin: 0 auto;
// `;
// EXPORT
export default MissionInput;
|
import escape from 'lodash.escape';
import {locations} from '../core/data';
import {capfirst} from '../utils/strings';
import {makeAbsoluteURL} from '../utils/urls';
export default class Place {
constructor(data) {
this.data = data;
}
isStub() {
return this.data.is_stub;
}
isReference() {
return typeof this.data == 'number';
}
getHighlightedName() {
if (!this.data.highlight) return this.getName();
return (
capfirst(this.data.highlight.full_name) ||
this.data.highlight.name ||
escape(this.getName())
);
}
getName() {
return capfirst(this.data.full_name);
}
getPresentFields(...fields) {
return fields.filter(f => this.hasValue(f));
}
hasValue(field) {
const value = this.data[field];
const isDefined = value != null;
const hasLength = isDefined && value.hasOwnProperty('length');
return hasLength ? value.length > 0 : isDefined;
}
getLocation() {
return locations.get(this.data.location);
}
toJSONLD(app) {
const url = app.url('place', {id: this.data.id});
if (this.isReference()) {
return {
'@id': url,
}
}
const result = {
'@context': 'http://schema.org',
'@type': 'Place',
'@id': url,
name: this.getName(),
address: this.data.address,
}
if (!this.isStub()) {
result.url = makeAbsoluteURL(url);
}
if (this.data.url) {
result.sameAs = this.data.url;
}
return result;
}
}
|
import React from 'react';
import CreditCardType from '../../components/CreditCardType/CreditCardType';
import './CreditCardsList.css';
import { dateToExpireCard } from '../../utils/timeUtils';
import { normalizeCardNumber } from '../../utils/creditCardUtil';
import {
List, Spin
} from 'antd';
import { Link } from 'react-router-dom';
export default ({ loading, list, match }) => (
<List>
{
loading ?
<Spin spinning={loading} /> :
list.map((item) => (
<List.Item key={item.id}>
<List.Item.Meta
title={
<Link to={`/cab/${match.params.role}/credit-card/${item.id}`}>
<div className="credit-card-item">
<CreditCardType
className="credit-card-item-type"
creditCard={item} />
<div>
<div>
{normalizeCardNumber(item.cardNumber)}
</div>
<small>
{dateToExpireCard(item.expired)}
</small>
</div>
</div>
</Link>
} />
</List.Item>
))
}
</List>
); |
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Images = new Schema({
url: {
type: String,
required: true
},
tag: [String]
});
var AlbumSchema = new Schema({
id: Number,
title: String,
desc: String,
featureUrl: String,
created: {
type: Date,
default: Date.now()
},
pics: [Images]
});
mongoose.model('Album', AlbumSchema);
|
function parseTypereference(obj) {
if (typeof obj !== 'object' || obj === null || !('kind' in obj) || obj.kind !== 'typereference') {
return obj;
}
return obj.name;
}
module.exports = parseTypereference; |
import React from 'react';
import '../styles/Title.scss';
export const Title = ({ title }) => {
return (
<div className="title">
<h2>{title}</h2>
</div>
);
};
|
/* eslint no-restricted-syntax:0, prefer-template: 0, prefer-arrow-callback: 0, func-names: 0, no-var: 0, vars-on-top: 0 */
/* global $ */
// Elements
var errorMessage = document.querySelector('.errorMessage');
var weatherContainer = document.querySelector('.weatherContainer');
var weatherHourly = document.querySelector('.weatherHourly');
var loadingSpinner = document.querySelector('.loadingSpinner');
var submitBtn = document.querySelector('#submitBtn');
var showMoreBtn = document.querySelector('#showMoreBtn');
// Get initial weather data
loadingSpinner.classList.toggle('show-me');
axios
.get('/weather')
.then(function (response) {
processResults(response);
})
.catch(function (e) {
handleErrors(e);
});
submitBtn.addEventListener('click', formSubmit);
showMoreBtn.addEventListener('click', showMore);
// Render Functions
function renderHourly(hourly) {
var rows = [];
for (var i = 0; i < hourly.length; i++) {
var rowDiv;
var isHidden = i > 25;
if (isHidden) rowDiv = '<div class="row hide-me">';
else rowDiv = '<div class="row">';
var hourlyRow = '<div class="hourly-row">';
rows.push(
hourlyRow+
rowDiv +
'<div class="col-xs-2 weather-col hourly-time">' +
hourly[i].timeByHour +
'</div>' +
'<div class="col-xs-1 weather-col first-row hourly-svg__col"><img class="hourly-svg" src="/img/svg/' +
hourly[i].icon +
'" alt="' +
hourly[i].icon +
'"' +
'"/></div>' +
'<div class="col-xs-1 weather-col">' +
hourly[i].temp +
'°C</div>' +
'<div class="col-xs-2 weather-col">' +
hourly[i].precipProbability +
'% '+ '<span class="small light">'+
hourly[i].precipIntensity
+
'mm</span></div>' +
'<div class="col-xs-1 weather-col">' +
hourly[i].cloudCover +
'%</div>' +
'<div class="col-xs-1 weather-col">' +
hourly[i].wind +
'm/s</div>' +
'</div>' +
rowDiv+
'<div class=" col-xs-12 weather-col hourly-summary">' +
'<span class="small">'+hourly[i].summary+'</span> ' +
'</div>'
+ '</div>'
+'</div>',
);
weatherHourly.innerHTML = ''; // remove old hourly data before rerendering
weatherHourly.insertAdjacentHTML('beforeend', rows.join(' '));
}
}
function formSubmit(e) {
e.preventDefault();
var addressInput = document.querySelector('.addressInput').value;
loadingSpinner.classList.toggle('show-me');
errorMessage.classList.remove('show-me');
errorMessage.classList.add('hide-me');
weatherContainer.classList.add('hide-me');
weatherContainer.classList.remove('show-me');
axios
.get(`/weather/${addressInput}`)
.then(function (response) {
processResults(response);
})
.catch(function (e) {
handleErrors(e);
});
}
function showMore() {
var hiddenRows = document.querySelectorAll('.row.hourly-row.hide-me');
hiddenRows.forEach((item) => {
item.classList.remove('hide-me');
});
showMoreBtn.classList.add('hide-me');
}
function processResults(res) {
loadingSpinner.classList.toggle('show-me');
if (!res.data.error) {
renderWeather(res.data);
renderHourly(res.data.hourlyWeather);
} else if (res.data.error) {
errorMessage.classList.add('show-me');
errorMessage.classList.remove('hide-me');
errorMessage.innerHTML = res.data.error;
} else {
errorMessage.classList.add('show-me');
errorMessage.classList.remove('hide-me');
}
}
function renderWeather(data) {
weatherContainer.classList.add('show-me');
weatherContainer.classList.remove('hide-me');
showMoreBtn.classList.remove('hide-me');
var currentIcon = document.querySelector('.currentIcon');
for (prop in data) {
if (data.hasOwnProperty(prop)) {
var tagName = document.querySelector('.' + prop);
if (tagName) {
tagName.innerHTML = data[prop];
if (tagName === currentIcon) {
tagName.setAttribute('src', '/img/svg/' + data[prop]);
tagName.setAttribute('alt', data.hourlyWeather[0].summary);
}
}
}
}
}
function handleErrors(e) {
loadingSpinner.classList.toggle('show-me');
console.log('errer', e);
// Returns 404 if could not get user's IP from some reason.
// We don't need to show error messages when user comes to the site.
if (e.response.status !== 404) {
errorMessage.classList.add('show-me');
errorMessage.classList.remove('hide-me');
errorMessage.innerHTML = 'Are you sure that is a valid address?';
console.error(e);
}
}
|
// DO NOT change the content of this file except for implementing the computeNormals() function
// to load a mesh you need to call: var myMesh = readOBJ('./data/mesh.obj');
function readOBJ(path) {
console.log("Reading OBJ file: " + path);
var obj = new Mesh();
var req = new XMLHttpRequest();
req.open('GET', path, false);
req.send(null);
obj.load(req.response);
obj.computeNormals();
console.log("OBJ file successfully loaded (nbV: " + obj.nbV() + ", nbF: " + obj.nbF() + ")");
return obj;
}
var Mesh = function() {
this.V = new Array(); // array of vertices
this.F = new Array(); // array of triangles
this.N = new Array(); // array of normals
};
Mesh.prototype.computeNormals = function() {
/* this function should be empty for the template */
for(var i = 0 ; i < this.nbV() ; ++i) {
this.N[i] = $V(0,0,0);
}
// ... to be completed by student to compute the normals per vertex
}
Mesh.prototype.nbV = function() { // number of vertices
return this.V.length;
};
Mesh.prototype.nbF = function() { // number of triangles
return this.F.length;
};
Mesh.prototype.load = function (data) {
// v float float float
var vertex_pattern = /v( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)( +[\d|\.|\+|\-|e]+)/;
// f vertex vertex vertex
var face_pattern1 = /f( +\d+)( +\d+)( +\d+)/
// f vertex/uv vertex/uv vertex/uv
var face_pattern2 = /f( +(\d+)\/(\d+))( +(\d+)\/(\d+))( +(\d+)\/(\d+))/;
// f vertex/uv/normal vertex/uv/normal vertex/uv/normal
var face_pattern3 = /f( +(\d+)\/(\d+)\/(\d+))( +(\d+)\/(\d+)\/(\d+))( +(\d+)\/(\d+)\/(\d+))/;
// f vertex//normal vertex//normal vertex//normal
var face_pattern4 = /f( +(\d+)\/\/(\d+))( +(\d+)\/\/(\d+))( +(\d+)\/\/(\d+))/;
var lines = data.split( "\n" );
for ( var i = 0; i < lines.length; i ++ ) {
var line = lines[ i ];
line = line.trim();
var result;
if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
continue;
}
else if ( ( result = vertex_pattern.exec( line ) ) !== null ) {
// ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
this.V.push( $V(
parseFloat( result[ 1 ] ),
parseFloat( result[ 2 ] ),
parseFloat( result[ 3 ] )
) );
}
else if ( ( result = face_pattern1.exec( line ) ) !== null ) {
// ["f 1 2 3", "1", "2", "3"]
this.F.push( $V(
parseInt( result[ 1 ] ) - 1 ,
parseInt( result[ 2 ] ) - 1 ,
parseInt( result[ 3 ] ) - 1
) );
} else if ( ( result = face_pattern2.exec( line ) ) !== null ) {
// ["f 1/1 2/2 3/3", " 1/1", "1", "1", " 2/2", "2", "2", " 3/3", "3", "3"]
this.F.push( $V(
parseInt( result[ 2 ] ) - 1 ,
parseInt( result[ 5 ] ) - 1 ,
parseInt( result[ 8 ] ) - 1
) );
} else if ( ( result = face_pattern3.exec( line ) ) !== null ) {
// ["f 1/1/1 2/2/2 3/3/3", " 1/1/1", "1", "1", "1", " 2/2/2", "2", "2", "2", " 3/3/3", "3", "3", "3"]
this.F.push( $V(
parseInt( result[ 2 ] ) - 1 ,
parseInt( result[ 6 ] ) - 1 ,
parseInt( result[ 10 ] ) - 1
) );
} else if ( ( result = face_pattern4.exec( line ) ) !== null ) {
// ["f 1//1 2//2 3//3", " 1//1", "1", "1", " 2//2", "2", "2", " 3//3", "3", "3"]
this.F.push( $V(
parseInt( result[ 2 ] ) - 1,
parseInt( result[ 5 ] ) - 1,
parseInt( result[ 8 ] ) - 1
) );
}
}
};
|
import React, {Component} from 'react'
export default class Countdown extends Component {
constructor(props) {
super(props)
this.state = {
returnStr: ''
}
this.countdown = this.countdown.bind(this)
}
componentDidMount() {
this.timer = setInterval(() => this.countdown(), 1000)
}
componentWillUnmount() {
clearInterval(this.timer)
}
countdown() {
let deadline = new Date(this.props.expiration).getTime()
let current = new Date().getTime()
let expires = deadline - current
if (expires > 0) {
let days = Math.floor(expires / (1000 * 60 * 60 * 24))
let hours = Math.floor(
(expires % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
)
let minutes = Math.floor((expires % (1000 * 60 * 60)) / (1000 * 60))
let seconds = Math.floor((expires % (1000 * 60)) / 1000)
this.setState({
returnStr: days +' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds left!'
}) }
else {
this.setState({returnStr: "Expired!"})
}
}
render() {
return <div>{this.state.returnStr}</div>
}
}
|
import { SEARCH_INPUT, SELECT_VIDEO, SET_VIDEOS } from '../constants'
import YSearch from 'youtube-api-search'
const API_KEY = 'AIzaSyDlwbMmvLbImh4GaK8yYlaD-ozvTy4X00U'
export const onInputChange = input => ({
type: SEARCH_INPUT,
payload: input
})
export const searchVideos = input => dispatch => {
YSearch({ key: API_KEY, term: input }, videos => {
dispatch({ type: SET_VIDEOS, payload: videos })
dispatch({ type: SELECT_VIDEO, payload: videos[0] })
})
}
export const selectVideo = video => ({
type: SELECT_VIDEO,
payload: video
})
|
var express = require('express');
var router = express.Router();
// home page
function checkSession(req, res) {
if (!req.session.Sign || !req.session.SuperUser) {
res.redirect('/');
return false;
} else {
res.locals.Account = req.session.Account;
res.locals.Name = req.session.Name;
res.locals.SuperUser = req.session.SuperUser;
}
return true;
}
router.get('/', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var mysqlQuery = req.mysqlQuery;
var SearchAllow = "";
var SearchAllowGroup = "";
if (req.session.SuperUser == 1) {
mysqlQuery('SELECT * FROM TempTbl ', function (err, serials) {
if (err) {
console.log(err);
}
var data = serials;
mysqlQuery('SELECT * FROM AllowTbl ', function (err, allows) {
if (err) {
console.log(err);
}
// use serial.ejs
var allow = allows;
res.render('serial', { title: 'Serial Information', data: data, allow: allow, SearchAllow: SearchAllow, SearchAllowGroup: SearchAllowGroup });
});
});
} else {
res.redirect('/serial');
}
});
// add page
router.get('/add', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
res.render('serialAdd', { title: 'Add Serial', msg: '' });
});
// add post
router.post('/serialAdd', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var DevNo = req.body.DevNo;
var GroupNo = req.body.GroupNo;
var DevNoArr = DevNo.toString().split(',');
var dateStr = req.body.ExpireDate;
var year = dateStr.substring(0, 4);
var month = dateStr.substring(4, 6);
var day = dateStr.substring(6, 8);
var date = new Date(year, month - 1, day, 0, 0, 0);
var ExpireDate = date.getTime() / 1000;
var mysqlQuery = req.mysqlQuery;
if (DevNoArr.length == 0) {
res.redirect('/serial');
return;
}
DevNoArr.forEach(devNo => {
if (devNo.trim().length == 12) {
var sql = {
DevNo: devNo.trim(),
ExpireDate: ExpireDate,
};
if (GroupNo) {
sql.GroupNo = GroupNo;
}
mysqlQuery('REPLACE INTO TempTbl SET ?', sql, function (err, rows) {
if (err) {
console.log(err);
}
if (DevNoArr[DevNoArr.length - 1].toString() == devNo.toString()) {
res.redirect('/serial');
return;
}
});
} else {
if (DevNoArr[DevNoArr.length - 1] == devNo) {
res.redirect('/serial');
return;
}
}
});
});
router.get('/search', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var SearchAllow = req.query.SearchAllow;
var SearchAllowGroup = "";
var mysqlQuery = req.mysqlQuery;
if (req.session.SuperUser == 1 || req.session.SuperUser == 2) {
mysqlQuery('SELECT * FROM AllowTbl WHERE DevNo LIKE ?', `%${SearchAllow}%`, function (err, allows) {
if (err) {
console.log(err);
}
var allow = allows;
mysqlQuery('SELECT * FROM TempTbl ', function (err, serials) {
if (err) {
console.log(err);
}
var data = serials;
// use serial.ejs
res.render('serial', { title: 'Serial Information', data: data, allow: allow, SearchAllow: SearchAllow, SearchAllowGroup: SearchAllowGroup });
});
});
} else {
return;
}
});
router.get('/searchGroup', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var SearchAllow = "";
var SearchAllowGroup = req.query.SearchAllowGroup;
var mysqlQuery = req.mysqlQuery;
if (req.session.SuperUser == 1 || req.session.SuperUser == 2) {
mysqlQuery('SELECT * FROM AllowTbl WHERE GroupNo = ?', `${SearchAllowGroup}`, function (err, allows) {
if (err) {
console.log(err);
}
var allow = allows;
mysqlQuery('SELECT * FROM TempTbl ', function (err, serials) {
if (err) {
console.log(err);
}
var data = serials;
// use serial.ejs
res.render('serial', { title: 'Serial Information', data: data, allow: allow, SearchAllow: SearchAllow, SearchAllowGroup: SearchAllowGroup });
});
});
} else {
return;
}
});
// edit page
router.get('/serialEdit', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var DevNo = req.query.DevNo;
var mysqlQuery = req.mysqlQuery;
mysqlQuery('SELECT * FROM AllowTbl WHERE DevNo = ?', DevNo, function (err, allows) {
if (err) {
console.log(err);
}
var data = allows;
if (data.length != 0) {
var date = new Date(data[0].ExpireDate * 1000);
var year = date.getFullYear();
var month = date.getMonth() + 1;
if (month < 10) {
month = "0" + month;
}
var day = date.getDate();
if (day < 10) {
day = "0" + day;
}
data[0].ExpireStr = `${year}${month}${day}`;
}
res.render('serialEdit', { title: 'Edit serial', data: data });
});
});
router.post('/serialEdit', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var mysqlQuery = req.mysqlQuery;
var DevNo = req.body.DevNo;
var GroupNo = req.body.GroupNo;
var sql = {};
var dateStr = req.body.ExpireDate;
var year = dateStr.substring(0, 4);
var month = dateStr.substring(4, 6);
var day = dateStr.substring(6, 8);
var date = new Date(year, month - 1, day, 0, 0, 0);
var ExpireDate = date.getTime() / 1000;
if (ExpireDate) {
sql.ExpireDate = ExpireDate;
}
if (GroupNo) {
sql.GroupNo = GroupNo;
} else {
sql.GroupNo = null;
}
mysqlQuery('UPDATE AllowTbl SET ? WHERE DevNo = ?', [sql, DevNo], function (err, allows) {
if (err) {
console.log(err);
}
var sql2 = { GroupNo: sql.GroupNo };
if (ExpireDate) {
sql2.ExpireDate = ExpireDate;
}
mysqlQuery('UPDATE DeviceTbl SET ? WHERE DevNo = ?', [sql2, DevNo], function (err, res) { });
res.locals.Account = req.session.Account;
res.locals.Name = req.session.Name;
res.setHeader('Content-Type', 'application/json');
res.redirect('/serial');
});
});
router.get('/move', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var mysqlQuery = req.mysqlQuery;
mysqlQuery('REPLACE INTO AllowTbl(DevNo,ExpireDate,GroupNo) SELECT DevNo,ExpireDate,GroupNo FROM TempTbl', function (err, rows) {
if (err) {
console.log(err);
}
mysqlQuery('TRUNCATE TABLE TempTbl', function (err, rows) {
if (err) {
console.log(err);
}
res.redirect('/serial');
});
});
});
router.get('/remove', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var mysqlQuery = req.mysqlQuery;
mysqlQuery('TRUNCATE TABLE TempTbl', function (err, rows) {
if (err) {
console.log(err);
}
res.redirect('/serial');
});
});
router.get('/serialDelete', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var DevNo = req.query.DevNo;
var mysqlQuery = req.mysqlQuery;
mysqlQuery('DELETE FROM TempTbl WHERE DevNo = ?', DevNo, function (err, rows) {
if (err) {
console.log(err);
}
res.redirect('/serial');
});
});
router.get('/allowDelete', function (req, res, next) {
if (!checkSession(req, res)) {
return;
}
var DevNo = req.query.DevNo;
var mysqlQuery = req.mysqlQuery;
mysqlQuery('DELETE FROM AllowTbl WHERE DevNo = ?', DevNo, function (err, rows) {
if (err) {
console.log(err);
}
res.redirect('/serial');
});
});
module.exports = router;
|
import React from 'react'
import PropTypes from 'prop-types'
import { graphql } from 'gatsby'
import { Helmet } from 'react-helmet'
import dayjs from 'dayjs'
import { Tags } from '@tryghost/helpers-gatsby'
import { readingTime as readingTimeHelper } from '@tryghost/helpers'
import { Layout } from '../components/common'
import { MetaData } from '../components/common/meta'
import RelatedPostsBlock from '../components/RelatedPostsBlock'
import NewsletterForm from '../components/NewsletterForm'
import TipButton from '../components/TipButton'
/**
* Single post view (/:slug)
*
* This file renders a single post and loads all the content.
*
*/
const Post = ({ data, location }) => {
const post = data.ghostPost
const readingTime = readingTimeHelper(post)
const publishedAt = dayjs(post.published_at).format(`MMM D, YYYY`)
const updatedAt = dayjs(post.updated_at).format(`MMM D, YYYY`)
return (
<Layout>
<MetaData data={data} location={location} type="article" />
<Helmet>
<style type="text/css">{`${post.codeinjection_styles}`}</style>
</Helmet>
<div className="pb-5">
<article className="content">
<header className="gh-header gh-canvas mb-8">
{post.feature_image ? <img className="gh-feature-image" src={post.feature_image} alt={post.title} /> : null}
{post.primary_tag && <span className="post-card-tags subtitle">{post.primary_tag.name}</span>}
<h1 className="text-6xl text-wide font-black mb-2">{post.title}</h1>
<div className="grid grid-cols-2 mb-8">
<div className="col-span-2 md:col-span-1 md:text-right lg:order-2">
<time className="post-byline-item block text-muted" dateTime={post.published_at}>
<span className="sr-only">Published on </span>
Written {publishedAt}
</time>
<time className="post-byline-item block text-muted" dateTime={post.updated_at}>
Last Updated {updatedAt}
</time>
</div>
<div className="col-span-2 md:col-span-1 lg:order-1">
<span className="uppercase inline-block mb-1 pe-4 font-bold">{readingTime}</span>
</div>
</div>
</header>
{/* The main post content */}
<section className="gh-content gh-canvas load-external-scripts content-body pb-12" dangerouslySetInnerHTML={{ __html: post.html }} />
<footer className="post-footer gh-canvas">
<div className="pb-8">
<div className="pb-3">
<TipButton text="Show your support!" />
</div>
<p>If you come across something that has helped or inspired you, consider showing your support!</p>
</div>
{post.tags && (
<div className="related-tags py-6">
<p className="text-lg uppercase mb-2 text-wide">Related Tags</p>
<div className="block">
<Tags post={post} permalink={`/tag/:slug`} visibility="public" autolink={true} classes="tag-item" separatorClasses="hidden" />
</div>
</div>
)}
</footer>
</article>
<div className="gh-canvas">
<RelatedPostsBlock tags={post.tags} currentArticleSlug={post.slug} />
<div className="about-author pb-12">
<h6 className="text-lg uppercase mb-2 text-wide">About the Author</h6>
<div className="post-card-author">
<h6 className="post-byline-item font-bold uppercase block mb-1">{post.primary_author.name}</h6>
<p className="font-light">{post.primary_author.bio}</p>
</div>
</div>
<div>
<hr />
<div className="pt-12">
<NewsletterForm />
</div>
</div>
</div>
</div>
</Layout>
)
}
Post.propTypes = {
data: PropTypes.shape({
ghostPost: PropTypes.shape({
codeinjection_styles: PropTypes.object,
title: PropTypes.string.isRequired,
slug: PropTypes.string.isRequired,
primary_tag: PropTypes.PropTypes.object,
html: PropTypes.string.isRequired,
feature_image: PropTypes.string,
custom_excerpt: PropTypes.string,
published_at: PropTypes.string,
updated_at: PropTypes.string,
primary_author: PropTypes.object,
tags: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string,
})
),
}).isRequired,
}).isRequired,
location: PropTypes.object.isRequired,
}
export default Post
export const postQuery = graphql`
query ($slug: String!) {
ghostPost(slug: { eq: $slug }) {
...GhostPostFields
}
}
`
|
import React from 'react';
const ChocolateCard = ({ chocolate }) => (
<div key={chocolate.id} className="chocolate-card">
<img src={chocolate.img_url} alt={chocolate.chocolate_type}/>
<h3>Type:{chocolate.chocolate_type}</h3>
</div>
)
export default ChocolateCard;
|
// previousValue, currentValue, index, array
_.reduceRight = function(array,callback){
var result ;//= array[0];
for(var len = array.length,i=len-1;i>=0;i--){
if(!result){
result = array[i];
}else{
result = callback(result,array[i],i,array);
}
}
return result;
}
_.foldR = _.reduceRight; |
// Create a menu app as seen in this week’s video. What you create is up to you as long as it meets the following requirements.
// Use at least one array.
// Use at least two classes.
// Your menu should have the options to create, view, and delete elements.
class Film {
constructor(name, year, genre) {
this.name = name;
this.year = year;
this.genre = genre;
}
describe() {
return `${this.name} is a ${this.genre} film that came out in ${this.year}.`
}
}
class Director {
constructor(name, country) {
this.name = name;
this.country = country;
this.films = [];
}
addFilm(film) {
if (film instanceof Film) {
this.film.push(film);
} else {
throw new Error(`You can only add an instance of Film. Argument is not a film: ${film}`);
}
}
describe() {
return `${this.name}, is a ${this.country} director who has ${this.films.length} films!`;
}
}
class Menu {
constructor() {
this.directors = [];
this.selectedDirector = null;
}
start() {
let selection = this.showMainMenuOptions();
while (selection != 0) {
switch (selection) {
case '1':
this.createDirector();
break;
case '2':
this.viewDirector();
break;
case '3':
this.deleteDirector();
break;
case '4':
this.displayDirectors();
break;
default:
selection = 0;
}
selection = this.showMainMenuOptions();
}
alert('Goodbye!');
}
showMainMenuOptions() {
return prompt(`
0) Exit
1) Create New Director
2) View Director
3) Delete Director
4) Display All Directors
`);
}
showDirectorMenuOptions(directorInfo) {
return prompt(`
0) Back
1) Create Film
2) Delete Film
---------------------------------------------------
${directorInfo}
`);
}
displayDirectors() {
let directorString = '';
for (let i = 0; i < this.directors.length; i++) {
directorString += i + ') ' + this.directors[i].name + '\n';
}
alert(directorString);
}
createDirector() {
let name = prompt('Enter the name of new director:');
let country = prompt('Enter the country of new director:');
this.directors.push(new Director(name,country));
}
viewDirector(){
let index = prompt('Enter the index of the director you wish to view: ');
if(index > -1 && index < this.directors.length) {
this.selectedDirector = this.directors[index];
let description = 'Director Name: ' + this.selectedDirector.name +
'\nDirectors Country: ' + this.selectedDirector.country + '\n';
for (let i = 0; i < this.selectedDirector.films.length; i++) {
description += i + ') ' + this.selectedDirector.films[i].name + ' - ' + this.selectedDirector.films[i].year +
' - ' + this.selectedDirector.films[i].genre + '\n';
}
let selection = this.showDirectorMenuOptions(description);
switch (selection) {
case '1':
this.createFilm();
break;
case '2':
this.deleteFilm();
break;
case '3':
this.viewFilm();
}
}
}
deleteDirector() {
let index = prompt('Enter the index of the director you wish to delete: ');
if (index > -1 && index < this.selectedDirector.films.length) {
this.directors.splice(index,1);
}
}
createFilm() {
let name = prompt('Enter name of film: ');
let year = prompt('Enter the year of release of the film: ');
let genre = prompt('Enter the genre of the film: ');
this.selectedDirector.films.push(new Film(name, year, genre));
}
deleteFilm() {
let index = prompt('Enter the index of the film you wish to delete: ');
if (index > -1 && index < this.selectedDirector.films.length) {
this.selectedDirector.films.splice(index, 1);
}
}
viewFilm(){
let index = prompt('Enter the index of the film you wish to view: ');
if(index > -1 && index < this.selectedDirector.films.length) {
this.selectedDirector.films = this.directors.films[index];
let description = `Film Name: ${this.selectedDirector.films.name}
Film's Release Year: ${this.selectedDirector.films.year}
Film's Genre: ${this.selectedDirector.films.genre}`;
}
}
}
let menu = new Menu();
menu.start(); |
/*
** TailwindCSS Configuration File
**
** Docs: https://tailwindcss.com/docs/configuration
** Default: https://github.com/tailwindcss/tailwindcss/blob/master/stubs/defaultConfig.stub.js
*/
module.exports = {
theme: {
colors: {
primary: {
default: '#F0F0F3',
},
dark : '#000000',
separator: '#DBDBE9',
},
boxShadow: {
flat: '-10px 10px 20px rgba(216, 216, 219, 0.2), 10px -10px 20px rgba(216, 216, 219, 0.2), -10px -10px 20px rgba(255, 255, 255, 0.9), 10px 10px 25px rgba(216, 216, 219, 0.9), inset 1px 1px 2px rgba(255, 255, 255, 0.3), inset -1px -1px 2px rgba(216, 216, 219, 0.5)',
pressed: '2px 2px 3px rgba(255, 255, 255, 0.3), -2px -2px 3px rgba(204, 204, 207, 0.5), inset -56px 56px 112px rgba(204, 204, 207, 0.2), inset 56px -56px 112px rgba(204, 204, 207, 0.2), inset -56px -56px 112px rgba(255, 255, 255, 0.9), inset 56px 56px 140px rgba(204, 204, 207, 0.9)',
convex: '-10px 10px 20px rgba(204, 204, 207, 0.2), 10px -10px 20px rgba(204, 204, 207, 0.2), -10px -10px 20px rgba(255, 255, 255, 0.9), 10px 10px 25px rgba(204, 204, 207, 0.9), inset 1px 1px 2px rgba(255, 255, 255, 0.3), inset -1px -1px 2px rgba(204, 204, 207, 0.5)',
concave: '-10px 10px 20px rgba(204, 204, 207, 0.2), 10px -10px 20px rgba(204, 204, 207, 0.2), -10px -10px 20px rgba(255, 255, 255, 0.9), 10px 10px 25px rgba(204, 204, 207, 0.9), inset 1px 1px 2px rgba(255, 255, 255, 0.3), inset -1px -1px 2px rgba(204, 204, 207, 0.5)'
},
fontFamily: {
'sans': ['Avenir', 'sans-serif'],
},
backgroundImage: theme => ({
account: "url('https://i.pravatar.cc/400')",
}),
extend: {
lineHeight: {
'12': '3rem'
},
height: {
'fit': 'fit-content'
}
}
},
variants: {},
plugins: []
}
|
import express from 'express';
import {postOption, fetchJsonByNode} from '../../../common/common';
import {host} from '../../globalConfig';
const service = `${host}/report-service`;
const service1 = `${host}/report-service`;
let api = express.Router();
const URL_LIST = `${service}/often_output_template/list/search`;
const URL_SAVE = `${service}/often_output_template/batch/`;
const URL_REPORT = `${service1}/report/drop_list`;
// 获取界面信息
api.get('/config', async (req, res) => {
const module = await require('./config');
res.send({returnCode: 0, result: module.default});
});
// 获取主列表数据
api.post('/list', async (req, res) => {
const {filter, ...others} = req.body;
let body = {...filter, ...others};
res.send(await fetchJsonByNode(req, URL_LIST, postOption(body)));
});
// 新增
api.post('/add',async (req, res)=>{
res.send(await fetchJsonByNode(req, URL_SAVE, postOption(req.body)));
});
// 删除
api.delete('/del/:id',async (req, res)=>{
const url= `${service}/often_output_template/batch/?ids=${req.params.id}`;
res.send(await fetchJsonByNode(req, url, postOption(null, 'delete')));
});
// 获取模板名称
api.get('/reportName/:guid', async (req, res) => {
const url = `${URL_REPORT}/${req.params.guid}`;
res.send(await fetchJsonByNode(req, url));
});
export default api;
|
const mongoose = require("mongoose")
const Route = mongoose.model("Route")
const sha256 = require('js-sha256')
const jwt = require('jsonwebtoken')
exports.getRoutesById = async(req,res)=>{
// console.log(req.body)
// console.log(req)
const {userid}=req.headers;
try{
const rutas = await Route.find({idVendedor:userid}).sort({"createdAt": -1})
console.log(rutas)
if(!rutas) throw "EmptyRoutes"
else{
let respuesta = {
rutas,
message:'success'
}
res.json(respuesta)
}
}catch(e){
console.log(e)
}
}
|
if (typeof window === "undefined") {
module.exports = require("abort-controller");
}
else {
module.exports = window.AbortController;
}
|
#!/usr/bin/env node
import {fileURLToPath} from 'url';
import {join, dirname} from 'path';
import {cliBasics} from 'command-line-basics';
import {makeBadgeFromJSONFile} from '../src/makeBadge.cjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const optionDefinitions = await cliBasics(
join(__dirname, './optionDefinitions.js')
);
if (!optionDefinitions) { // cliBasics handled
process.exit(0);
}
const {output} = await makeBadgeFromJSONFile(optionDefinitions);
console.log('Saved to ' + output);
|
import React from 'react'
import './Loading.css'
const Loading = props => {
const loadingClass = props.loadingFinished ? 'Loading finished' : 'Loading'
return (
<div className={loadingClass}>
<div className='floater1' />
<div className='waveContainer'>
{
Array.from(Array(20).keys()).map(() => (
<svg viewBox='0 0 200 100'>
<path d='M 0 0 C 40 30, 60 30, 100 0' stroke='none' fill='#90DAB9' />
<path d='M 99 1 C 140 -30, 160 -30, 201 1' stroke='none' fill='#619192' />
</svg>
))
}
</div>
<div className='floater2' />
<div className='waveContainer2'>
{
Array.from(Array(20).keys()).map(() => (
<svg viewBox='0 0 200 100'>
<path d='M -1 -1 C 40 30, 60 30, 101 -1' stroke='none' fill='#619192' />
<path d='M 100 0 C 140 -30, 160 -30, 200 0' stroke='none' fill='#31476A' />
</svg>
))
}
</div>
</div>
)
}
export default Loading
|
import React, {useState, useEffect} from 'react';
import PropTypes from 'prop-types';
const applications = [];
const CalculatorQuestionnaireHoc = (Component) => {
const CalculatorQuestionnaireState = (props) => {
const [successActive, setSuccessActive] = useState(false);
const [applicationItems, setApplicationItems] = useState(JSON.parse(localStorage.getItem(`applications`)) || `[]`);
const [fullName, setFullName] = useState(``);
const [phone, setPhone] = useState(``);
const [email, setEmail] = useState(``);
const [fullNameError, setFullNameError] = useState(false);
const [emailError, setEmailError] = useState(false);
const [emailValid, setEmailValid] = useState(false);
const [phoneError, setPhoneError] = useState(false);
useEffect(() => {
setApplicationItems(applications);
}, []);
useEffect(() => {
const body = document.querySelector(`body`);
body.style.overflow = successActive ? `hidden` : `auto`;
}, [successActive]);
useEffect(() => {
localStorage.setItem(`applications`, JSON.stringify(applicationItems));
}, [applicationItems]);
return (
<Component
successActive={successActive} onSuccessActive={setSuccessActive}
counter={props.counter} onCounter={props.onCounter}
questionnaireActive={props.questionnaireActive} onQuestionnaireActive={props.onQuestionnaireActive}
time={props.time}
target={props.target}
price={props.price}
deposit={props.deposit}
applicationItems={applicationItems} onApplicationItems={setApplicationItems}
fullName={fullName} onFullName={setFullName}
phone={phone} onPhone={setPhone}
email={email} onEmail={setEmail}
fullNameError={fullNameError} onFullNameError={setFullNameError}
emailError={emailError} onEmailError={setEmailError}
emailValid={emailValid} onEmailValid={setEmailValid}
phoneError={phoneError} onPhoneError={setPhoneError}
/>
);
};
CalculatorQuestionnaireState.propTypes = {
time: PropTypes.number.isRequired,
target: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
deposit: PropTypes.number.isRequired,
counter: PropTypes.number.isRequired,
onCounter: PropTypes.func.isRequired,
questionnaireActive: PropTypes.bool.isRequired,
onQuestionnaireActive: PropTypes.func.isRequired,
};
return CalculatorQuestionnaireState;
};
export default CalculatorQuestionnaireHoc;
|
module.exports = {
deepEncode(value) {
return value.replace(/[\~\:\s\@\/\(\)]/g, '_');
}
}
|
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/personal_package/material/main" ], {
"266c": function(e, t, n) {},
3234: function(e, t, n) {
n.r(t);
var o = n("b3a2"), r = n.n(o);
for (var a in o) [ "default" ].indexOf(a) < 0 && function(e) {
n.d(t, e, function() {
return o[e];
});
}(a);
t.default = r.a;
},
"3dbf": function(e, t, n) {
(function(e) {
function t(e) {
return e && e.__esModule ? e : {
default: e
};
}
n("6cdc"), t(n("66fd")), e(t(n("c6db")).default);
}).call(this, n("543d").createPage);
},
"6dcb": function(e, t, n) {
var o = n("266c");
n.n(o).a;
},
b3a2: function(e, t, n) {
function o(e, t) {
var n = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
t && (o = o.filter(function(t) {
return Object.getOwnPropertyDescriptor(e, t).enumerable;
})), n.push.apply(n, o);
}
return n;
}
function r(e) {
for (var t = 1; t < arguments.length; t++) {
var n = null != arguments[t] ? arguments[t] : {};
t % 2 ? o(Object(n), !0).forEach(function(t) {
a(e, t, n[t]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : o(Object(n)).forEach(function(t) {
Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
});
}
return e;
}
function a(e, t, n) {
return t in e ? Object.defineProperty(e, t, {
value: n,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[t] = n, e;
}
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var c = n("2f62"), i = n("371c"), u = {
onShareAppMessage: function() {
var e = encodeURIComponent("/pages/personal_package/material/main"), t = {
title: "杭州购房资格查询,必备模板都在这里了,快来看看~",
path: "/pages/index/main?sub_page=".concat(e),
imageUrl: "https://cdn.vip-wifi.com/hzfangchan/config/share-img/share-gfzn.png"
};
return this.getShareInfo(t);
},
components: {
TopRightShare: function() {
n.e("components/views/top_right_share").then(function() {
return resolve(n("73b4"));
}.bind(null, n)).catch(n.oe);
}
},
data: function() {
return {};
},
computed: r(r({}, (0, c.mapState)([ "materialTools", "footerCardType", "consultant_today_rankings" ])), {}, {
tool_tabs_bg: function() {
var e = this.materialTools.bg, t = e.path, n = e.w, o = e.h;
return {
url: "https://cdn.vip-wifi.com/hzfangchan/".concat("", "config/").concat(t),
size: {
width: "".concat(n, "rpx"),
height: "".concat(o, "rpx")
}
};
}
}),
onLoad: function(e) {},
methods: {
sendLog: function(e) {
var t = e.currentTarget.dataset.name;
console.error(t), (0, i.sendCtmEvtLog)("购房指南-".concat(t));
}
}
};
t.default = u;
},
c6db: function(e, t, n) {
n.r(t);
var o = n("d60a"), r = n("3234");
for (var a in r) [ "default" ].indexOf(a) < 0 && function(e) {
n.d(t, e, function() {
return r[e];
});
}(a);
n("6dcb");
var c = n("f0c5"), i = Object(c.a)(r.default, o.b, o.c, !1, null, "7741e35f", null, !1, o.a, void 0);
t.default = i.exports;
},
d60a: function(e, t, n) {
n.d(t, "b", function() {
return o;
}), n.d(t, "c", function() {
return r;
}), n.d(t, "a", function() {});
var o = function() {
var e = this, t = (e.$createElement, e._self._c, e.materialTools && e.materialTools.tabs.length ? e.__get_style([ e.tool_tabs_bg.size ]) : null);
e.$mp.data = Object.assign({}, {
$root: {
s0: t
}
});
}, r = [];
}
}, [ [ "3dbf", "common/runtime", "common/vendor" ] ] ]); |
const _ = require('lodash');
const should = require('should');
const supertest = require('supertest');
const config = require('../../../../../core/shared/config');
const testUtils = require('../../../../utils');
const localUtils = require('./utils');
const ghost = testUtils.startGhost;
// NOTE: in future iterations these fields should be fetched from a central module.
// Have put a list as is here for the lack of better place for it.
const defaultSettingsKeys = [
'title',
'description',
'logo',
'cover_image',
'icon',
'lang',
'timezone',
'codeinjection_head',
'codeinjection_foot',
'facebook',
'twitter',
'navigation',
'secondary_navigation',
'meta_title',
'meta_description',
'og_image',
'og_title',
'og_description',
'twitter_image',
'twitter_title',
'twitter_description',
'active_theme',
'is_private',
'password',
'public_hash',
'default_content_visibility',
'members_allow_free_signup',
'members_from_address',
'stripe_product_name',
'stripe_plans',
'stripe_secret_key',
'stripe_publishable_key',
'stripe_connect_secret_key',
'stripe_connect_publishable_key',
'stripe_connect_account_id',
'stripe_connect_display_name',
'stripe_connect_livemode',
'portal_name',
'portal_button',
'portal_plans',
'mailgun_api_key',
'mailgun_domain',
'mailgun_base_url',
'amp',
'labs',
'slack',
'unsplash',
'shared_views',
'active_timezone',
'default_locale'
];
describe('Settings API (v3)', function () {
let ghostServer;
let request;
describe('As Owner', function () {
before(function () {
return ghost()
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('url'));
})
.then(function () {
return localUtils.doAuth(request);
});
});
it('Can request all settings', function () {
return request.get(localUtils.API.getApiQuery(`settings/`))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.then((res) => {
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse.settings);
should.exist(jsonResponse.meta);
jsonResponse.settings.should.be.an.Object();
const settings = jsonResponse.settings;
settings.map(s => s.key).sort().should.deepEqual(defaultSettingsKeys.sort());
localUtils.API.checkResponse(jsonResponse, 'settings');
});
});
it('Can request settings by type', function () {
return request.get(localUtils.API.getApiQuery(`settings/?type=theme`))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.then((res) => {
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse.settings);
should.exist(jsonResponse.meta);
jsonResponse.settings.should.be.an.Object();
const settings = jsonResponse.settings;
Object.keys(settings).length.should.equal(1);
settings[0].key.should.equal('active_theme');
settings[0].value.should.equal('casper');
settings[0].type.should.equal('theme');
localUtils.API.checkResponse(jsonResponse, 'settings');
});
});
it('Can\'t read core setting', function () {
return request
.get(localUtils.API.getApiQuery('settings/db_hash/'))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(403);
});
it('Can\'t read permalinks', function (done) {
request.get(localUtils.API.getApiQuery('settings/permalinks/'))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
it('Can read deprecated default_locale', function (done) {
request.get(localUtils.API.getApiQuery('settings/default_locale/'))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
jsonResponse.settings.length.should.eql(1);
testUtils.API.checkResponseValue(jsonResponse.settings[0], ['id', 'group', 'key', 'value', 'type', 'flags', 'created_at', 'updated_at']);
jsonResponse.settings[0].key.should.eql('default_locale');
done();
});
});
it('can edit deprecated default_locale setting', function () {
return request.get(localUtils.API.getApiQuery('settings/default_locale/'))
.set('Origin', config.get('url'))
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.then(function (res) {
let jsonResponse = res.body;
const newValue = 'new value';
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
jsonResponse.settings = [{key: 'default_locale', value: 'ua'}];
return jsonResponse;
})
.then((editedSetting) => {
return request.put(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.send(editedSetting)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.then(function (res) {
should.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
jsonResponse.settings.length.should.eql(1);
testUtils.API.checkResponseValue(jsonResponse.settings[0], ['id', 'group', 'key', 'value', 'type', 'flags', 'created_at', 'updated_at']);
jsonResponse.settings[0].key.should.eql('default_locale');
jsonResponse.settings[0].value.should.eql('ua');
});
});
});
it('Can read timezone', function (done) {
request.get(localUtils.API.getApiQuery('settings/timezone/'))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
jsonResponse.settings.length.should.eql(1);
testUtils.API.checkResponseValue(jsonResponse.settings[0], ['id', 'group', 'key', 'value', 'type', 'flags', 'created_at', 'updated_at']);
jsonResponse.settings[0].key.should.eql('timezone');
done();
});
});
it('Can read active_timezone', function (done) {
request.get(localUtils.API.getApiQuery('settings/active_timezone/'))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
jsonResponse.settings.length.should.eql(1);
testUtils.API.checkResponseValue(jsonResponse.settings[0], ['id', 'group', 'key', 'value', 'type', 'flags', 'created_at', 'updated_at']);
jsonResponse.settings[0].key.should.eql('active_timezone');
done();
});
});
it('Can read deprecated active_timezone', function (done) {
request.get(localUtils.API.getApiQuery('settings/active_timezone/'))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
jsonResponse.settings.length.should.eql(1);
testUtils.API.checkResponseValue(jsonResponse.settings[0], ['id', 'group', 'key', 'value', 'type', 'flags', 'created_at', 'updated_at']);
jsonResponse.settings[0].key.should.eql('active_timezone');
done();
});
});
it('can\'t read non existent setting', function (done) {
request.get(localUtils.API.getApiQuery('settings/testsetting/'))
.set('Origin', config.get('url'))
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse);
should.exist(jsonResponse.errors);
testUtils.API.checkResponseValue(jsonResponse.errors[0], [
'message',
'context',
'type',
'details',
'property',
'help',
'code',
'id'
]);
done();
});
});
it('can toggle member setting', function (done) {
request.get(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.end(function (err, res) {
if (err) {
return done(err);
}
const jsonResponse = res.body;
const changedValue = [];
const settingToChange = {
settings: [
{
key: 'labs',
value: '{"subscribers":false,"members":false}'
}
]
};
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
request.put(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.send(settingToChange)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
const putBody = res.body;
res.headers['x-cache-invalidate'].should.eql('/*');
should.exist(putBody);
putBody.settings[0].key.should.eql('labs');
putBody.settings[0].value.should.eql(JSON.stringify({subscribers: false, members: false}));
done();
});
});
});
it('can\'t edit permalinks', function (done) {
const settingToChange = {
settings: [{key: 'permalinks', value: '/:primary_author/:slug/'}]
};
request.put(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.send(settingToChange)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
it('can\'t edit non existent setting', function (done) {
request.get(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.end(function (err, res) {
if (err) {
return done(err);
}
let jsonResponse = res.body;
const newValue = 'new value';
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
jsonResponse.settings = [{key: 'testvalue', value: newValue}];
request.put(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.send(jsonResponse)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.end(function (err, res) {
if (err) {
return done(err);
}
jsonResponse = res.body;
should.not.exist(res.headers['x-cache-invalidate']);
should.exist(jsonResponse.errors);
testUtils.API.checkResponseValue(jsonResponse.errors[0], [
'message',
'context',
'type',
'details',
'property',
'help',
'code',
'id'
]);
done();
});
});
});
it('Will transform "1"', function (done) {
request.get(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.end(function (err, res) {
if (err) {
return done(err);
}
const jsonResponse = res.body;
const settingToChange = {
settings: [
{
key: 'is_private',
value: '1'
}
]
};
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
request.put(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.send(settingToChange)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
const putBody = res.body;
res.headers['x-cache-invalidate'].should.eql('/*');
should.exist(putBody);
putBody.settings[0].key.should.eql('is_private');
putBody.settings[0].value.should.eql(true);
localUtils.API.checkResponse(putBody, 'settings');
done();
});
});
});
});
describe('As Admin', function () {
before(function () {
return ghost()
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('url'));
})
.then(function () {
// create admin
return testUtils.createUser({
user: testUtils.DataGenerator.forKnex.createUser({email: 'admin+1@ghost.org'}),
role: testUtils.DataGenerator.Content.roles[0].name
});
})
.then(function (admin) {
request.user = admin;
// by default we login with the owner
return localUtils.doAuth(request);
});
});
it('cannot toggle member setting', function (done) {
const settingToChange = {
settings: [
{
key: 'labs',
value: '{"subscribers":false,"members":true}'
}
]
};
request.put(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.send(settingToChange)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(403)
.end(function (err, res) {
if (err) {
return done(err);
}
done();
});
});
});
describe('As Editor', function () {
let editor;
before(function () {
return ghost()
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('url'));
})
.then(function () {
// create editor
return testUtils.createUser({
user: testUtils.DataGenerator.forKnex.createUser({email: 'test+1@ghost.org'}),
role: testUtils.DataGenerator.Content.roles[1].name
});
})
.then(function (_user1) {
editor = _user1;
request.user = editor;
// by default we login with the owner
return localUtils.doAuth(request);
});
});
it('should not be able to edit settings', function (done) {
request.get(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.end(function (err, res) {
if (err) {
return done(err);
}
let jsonResponse = res.body;
const newValue = 'new value';
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
jsonResponse.settings = [{key: 'visibility', value: 'public'}];
request.put(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.send(jsonResponse)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(403)
.end(function (err, res) {
if (err) {
return done(err);
}
jsonResponse = res.body;
should.not.exist(res.headers['x-cache-invalidate']);
should.exist(jsonResponse.errors);
testUtils.API.checkResponseValue(jsonResponse.errors[0], [
'message',
'context',
'type',
'details',
'property',
'help',
'code',
'id'
]);
done();
});
});
});
});
describe('As Author', function () {
before(function () {
return ghost()
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('url'));
})
.then(function () {
// create author
return testUtils.createUser({
user: testUtils.DataGenerator.forKnex.createUser({email: 'test+2@ghost.org'}),
role: testUtils.DataGenerator.Content.roles[2].name
});
})
.then(function (author) {
request.user = author;
// by default we login with the owner
return localUtils.doAuth(request);
});
});
it('should not be able to edit settings', function (done) {
request.get(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.end(function (err, res) {
if (err) {
return done(err);
}
let jsonResponse = res.body;
const newValue = 'new value';
should.exist(jsonResponse);
should.exist(jsonResponse.settings);
jsonResponse.settings = [{key: 'visibility', value: 'public'}];
request.put(localUtils.API.getApiQuery('settings/'))
.set('Origin', config.get('url'))
.send(jsonResponse)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(403)
.end(function (err, res) {
if (err) {
return done(err);
}
jsonResponse = res.body;
should.not.exist(res.headers['x-cache-invalidate']);
should.exist(jsonResponse.errors);
testUtils.API.checkResponseValue(jsonResponse.errors[0], [
'message',
'context',
'type',
'details',
'property',
'help',
'code',
'id'
]);
done();
});
});
});
});
});
|
import withModnikkyService from "./with-modnikky-service";
export { withModnikkyService };
|
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://120.25.75.23:27017/data';
t = [
{"名称":"蜜蜡珠链","货号":"L1712-212001M","重量(g)":"19.8","规格(mm)":"7","粒数":"110","克价(元)":"120/g","售价":"2876",},
{"名称":"蜜蜡珠链","货号":"L1712-312002M","重量(g)":"16.9","规格(mm)":"6","粒数":"123","克价(元)":"120/g","售价":"2628",},
{"名称":"蜜蜡珠链","货号":"L1712-312003M","重量(g)":"15.9","规格(mm)":"6","粒数":"127","克价(元)":"120/g","售价":"2400",},
{"名称":"蜜蜡珠链","货号":"L1712-215004M","重量(g)":"20.5","规格(mm)":"13.5","粒数":"15","克价(元)":"180/g","售价":"3890",},
{"名称":"蜜蜡珠链","货号":"L1712-215005M","重量(g)":"20.5","规格(mm)":"13.5","粒数":"15","克价(元)":"180/g","售价":"3890",},
{"名称":"蜜蜡珠链","货号":"L1712-222006M","重量(g)":"37.1","规格(mm)":"8","粒数":"118","克价(元)":"150/g","售价":"5565",},
{"名称":"蜜蜡珠链","货号":"L1712-222007M","重量(g)":"37.4","规格(mm)":"8","粒数":"118","克价(元)":"150/g","售价":"5610","备注":"改编“游鱼”余34粒"},
{},
];
MongoClient.connect(url, function (err, d) {
if (err) throw err;
console.log('数据库已创建!');
db = d.db('data');
for (item of t) {
if(item.扫描码){
item.条码号= item.扫描码
item._id= item.扫描码
delete item.扫描码}
else {
item.条码号= item.证书号
item._id= item.证书号
}
if (item.证书号&&item.条码号&&item.名称)
db.collection('sp').insertOne( {
...item,
状态: '在库',
'材质':'蜜蜡',
'类别':'珠链'
});
else{
console.log(item)
}
}
});
|
Ext.define('NU.Network', {
extend: 'Ext.util.Observable',
config: {
robotIPs: []
},
singleton: true,
constructor: function () {
var self;
self = this;
this.addEvents(
'robot_ips',
'sensor_data',
'vision',
'localisation'
);
self.setupSocket();
self.callParent(arguments);
return self;
},
setupSocket: function () {
var self, socket;
self = this;
socket = io.connect(document.location.origin);
socket.on('robot_ips', function (robotIPs) {
self.setRobotIPs(robotIPs);
setTimeout(function () {
self.fireEvent('robot_ips', self.robotIPs);
}, 1000); // hack since display isn't rendered yet :(
});
socket.on('message', function (robotIP, message) {
var api_message, array, stream, eventName;
api_message = new API.Message;
array = Base64Binary.decodeArrayBuffer(message);
stream = new PROTO.ArrayBufferStream(array, array.byteLength);
api_message.ParseFromStream(stream);
eventName = API.Message.Type[api_message.type].toLowerCase();
//console.log(eventName);
self.fireEvent(eventName, robotIP, api_message);
});
},
listeners: {
vision: function () {
//console.log('yes')
}
}
}); |
import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, Text, WebView, StyleSheet, Linking } from "react-native";
import showdown from "showdown";
class MarkdownRenderer extends Component {
static defaultShowdownOptions = {
simplifiedAutoLink: true,
strikethrough: true,
tables: true,
};
state = { html: null, contentHeight: 1 };
converter = null;
componentWillMount() {
this._instantiateShowdownConverter(this.props.options);
this._convertMarkdown(this.props.body);
}
componentWillReceiveProps(nextProps) {
this.props.options !== nextProps.options &&
this._instantiateShowdownConverter(nextProps.options);
this.props.body !== nextProps.body && this._convertMarkdown(nextProps.body);
}
_instantiateShowdownConverter(options) {
this.converter = new showdown.Converter({
...this.constructor.defaultShowdownOptions,
...options,
});
}
_convertMarkdown(markdownString) {
this.setState({ html: this.converter.makeHtml(markdownString) });
}
render() {
const { pureCSS, automaticallyAdjustContentInsets, style } = this.props;
return (
<WebView
ref={"WebView"}
source={{
html: defaultHTML
.replace("$title", "")
.replace("$body", this.state.html)
.replace("$pureCSS", pureCSS),
baseUrl: "about:blank",
}}
injectedJavaScript={
"setTimeout(function() { window.postMessage(document.body.scrollHeight, '*'); }, 1000);"
}
onMessage={event => {
console.log("height", parseInt(event.nativeEvent.data));
this.setState({ contentHeight: parseInt(event.nativeEvent.data) });
}}
automaticallyAdjustContentInsets={automaticallyAdjustContentInsets}
onNavigationStateChange={this.onNavigationStateChange.bind(this)}
style={{ flex: 1, height: this.state.contentHeight }}
/>
);
}
onNavigationStateChange(navState) {
if (navState.url !== "about:blank") {
this.refs.WebView.stopLoading();
Linking.openURL(navState.url);
}
}
}
export default MarkdownRenderer;
// const stylesheetProp = PropTypes.oneOfType([
// PropTypes.number,
// PropTypes.object,
// ]);
// MarkdownRenderer.propTypes = {
// title: PropTypes.string,
// body: PropTypes.string.isRequired,
// pureCSS: PropTypes.string,
// options: PropTypes.object,
// automaticallyAdjustContentInsets: PropTypes.bool,
// style: stylesheetProp,
// };
MarkdownRenderer.defaultProps = {
title: "",
pureCSS: "",
options: {},
style: {
flex: 1,
},
};
const defaultHTML = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<meta name="format-detection" content="telephone=no">
<meta name="format-detection" content="date=no">
<meta name="format-detection" content="address=no">
<meta name="format-detection" content="email=no">
<title>$title</title>
<style type="text/css">
body {
font-family: Roboto, '-apple-system', Helvetica Neue, Arial;
}
b, strong {
font-family: Roboto, '-apple-system', Helvetica Neue, Arial;
font-weight: bold;
}
h1, h2, h3, h4, h5, h6 {
font-family: Roboto, '-apple-system', Helvetica Neue, Arial;
font-weight: bold;
}
$pureCSS
</style>
</head>
<body>
$body
</body>
</html>`;
|
import { handleActions } from 'redux-actions'
import {
fetchBtcRequest,
fetchEthRequest,
fetchBtcSuccess,
fetchEthSuccess,
fetchBtcFailure,
fetchEthFailure,
selectCurrency,
selectOffset
} from '../actions/currency'
export default handleActions(
{
[fetchBtcRequest]: state => ({ ...state, isBtcLoading: true }),
[fetchEthRequest]: state => ({ ...state, isEthLoading: true }),
[fetchBtcSuccess]: (state, { payload }) => ({
...state,
isBtcLoading: false,
btc: payload
}),
[fetchEthSuccess]: (state, { payload }) => ({
...state,
isEthLoading: false,
eth: payload
}),
[fetchBtcFailure]: (state, { payload }) => ({
...state,
isBtcLoading: false
}),
[fetchEthFailure]: (state, { payload }) => ({
...state,
isEthLoading: false
}),
[selectCurrency]: (state, { payload }) => ({
...state,
selected: payload,
error: null
}),
[selectOffset]: (state, { payload }) => ({ ...state, offset: payload })
},
{
selected: 'btc',
offset: '2h',
btc: [],
eth: [],
isBtcLoading: false,
isEthLoading: false
}
)
export const getSelectedCurrency = state => state.currency.selected
export const getOffset = state => state.currency.offset
export const getBtc = state => state.currency.btc
export const getEth = state => state.currency.eth
export const getIsloading = state =>
state.currency.isBtcLoading || state.currency.isEthLoading
export const getBtcSellCourse = state =>
state.currency.btc[0] ? state.currency.btc[0].sell : 0
export const getEthSellCourse = state =>
state.currency.eth[0] ? state.currency.eth[0].sell : 0
export const getBtcPurchaseCourse = state =>
state.currency.btc[0] ? state.currency.btc[0].purchase : 0
export const getEthPurchaseCourse = state =>
state.currency.eth[0] ? state.currency.eth[0].purchase : 0
|
function foodTrailMarker(x, y){
let newMarker = createSprite(x, y)
newMarker.type = 'food'
newMarker.draw = function(){
stroke(240)
ellipse(0, 0, 1)
}
newMarker.debug = false
newMarker.life = 250
newMarker.setCollider('circle', 0, 0, 20)
return newMarker
}
function foodIsGoneMarker(x, y){
let newMarker = createSprite(x, y)
newMarker.type = 'foodGone'
newMarker.draw = function(){
stroke(70)
ellipse(0, 0, 1)
}
newMarker.debug = false
newMarker.life = 1000
newMarker.setCollider('circle', 0, 0, 50)
return newMarker
}
function fightTrailMarker(x, y){
let newMarker = createSprite(x, y)
newMarker.type = 'fight'
newMarker.life = 500
newMarker.setCollider('circle', 0, 0, 100)
newMarker.draw = function(){
noFill()
stroke(255, 0, 0)
ellipse(0, 0, 150)
}
newMarker.debug = false
return newMarker
}
function wanderTrailMarker(x, y){
let newMarker = createSprite(x, y)
newMarker.type = 'wander'
newMarker.life = 199
newMarker.setCollider('circle', 0, 0, 25)
newMarker.draw = function(){
noFill()
stroke(150, 150, 255)
ellipse(0, 0, 25)
}
newMarker.debug = false
return newMarker
}
|
import tape from 'tape';
import milestones from '../src/main';
import * as d3 from 'd3-selection';
import { startTransaction } from './apm';
import { delay } from './delay';
const TEST_NAME =
'should render a minimal milestones chart with attached events';
tape(TEST_NAME, (t) => {
document.body.insertAdjacentHTML(
'afterbegin',
'<div id="wrapper_event"></div>'
);
const data = [
{ timestamp: '2012-09-09T00:00', detail: 'v1.0.0' },
{ timestamp: '2012-09-10T00:00', detail: 'v1.0.1' },
{ timestamp: '2012-09-12T00:00', detail: 'v1.1.0' },
];
const { endTransaction } = startTransaction(TEST_NAME);
const timeline = milestones('#wrapper_event')
.onEventClick((d) => {
t.equal(d.text, 'v1.0.0', 'click event text should match label text');
})
.onEventMouseOver((d) => {
t.equal(d.text, 'v1.0.0', 'mouseover event text should match label text');
})
.onEventMouseLeave((d) => {
t.equal(d.text, 'v1.0.0', 'mouseover event text should match label text');
})
.mapping({
timestamp: 'timestamp',
text: 'detail',
});
timeline
.parseTime('%Y-%m-%dT%H:%M')
.aggregateBy('second')
.optimize(true)
.render(data);
endTransaction();
t.plan(3);
return delay(1000).then(function () {
d3.select('#wrapper_event .milestones-text-label').each(function (d, i) {
var onClickFunc = d3.select(this).on('click');
onClickFunc.apply(this, [d, i]);
});
d3.select('#wrapper_event .milestones-text-label').each(function (d, i) {
var onClickFunc = d3.select(this).on('mouseover');
onClickFunc.apply(this, [d, i]);
});
d3.select('#wrapper_event .milestones-text-label').each(function (d, i) {
var onClickFunc = d3.select(this).on('mouseleave');
onClickFunc.apply(this, [d, i]);
});
t.end();
});
});
|
'use strict'
/** @typedef {import('@adonisjs/framework/src/Request')} Request */
/** @typedef {import('@adonisjs/framework/src/Response')} Response */
/** @typedef {import('@adonisjs/framework/src/View')} View */
const Campeonato = use('App/Models/Campeonato')
/**
* Resourceful controller for interacting with campeonatoes
*/
class CampeonatoController {
/**
* Show a list of all campeonatoes.
* GET campeonatoes
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async index ({ request, response, view }) {
const campeonatos = await Campeonato.all();
return campeonatos;
}
/**
* Create/save a new campeonato.
* POST campeonatoes
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async store ({ request, response }) {
const data = request.only(['Nome','Inicio','Fim']);
data.Inicio = new Date()
data.Fim = new Date()
const createdCamp = await Campeonato.create({...data});
return createdCamp;
}
/**
* Display a single campeonato.
* GET campeonatoes/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
* @param {View} ctx.view
*/
async show ({ params, request, response, view }) {
const { id } = params
const campeonatos = await Campeonato.find(id);
return campeonatos;
}
/**
* Update campeonato details.
* PUT or PATCH campeonatoes/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async update ({ params, request, response }) {
const { id } = params
const data = request.only(['Nome','Inicio','Fim']);
data.Inicio = undefined
data.Fim = undefined
const campeonato = Campeonato.query().where('id',id).update(data)
return campeonato
}
/**
* Delete a campeonato with id.
* DELETE campeonatoes/:id
*
* @param {object} ctx
* @param {Request} ctx.request
* @param {Response} ctx.response
*/
async destroy ({ params, request, response }) {
const { id } = params
const campeonato = Campeonato.query().where('id', id).delete()
return campeonato
}
}
module.exports = CampeonatoController
|
import { shallowMount } from "@vue/test-utils";
import About from "@/components/About.vue";
describe("About", () => {
describe("astronaut image", () => {
it("renders the image", () => {
const wrapper = shallowMount(About);
expect(wrapper.find(".about__img img").exists()).toBe(true);
});
it("includes alt text", () => {
const wrapper = shallowMount(About);
expect(wrapper.find(".about__img img").element.alt).toEqual(
"A floating astronaut in space on a laptop programming"
);
});
it("includes title", () => {
const wrapper = shallowMount(About);
expect(wrapper.find(".about__img img").element.title).toEqual(
"I prefer Spaces over Tabs"
);
});
});
describe("content", () => {
describe("header", () => {
it("has a text content stating 'HELLO'", () => {
const wrapper = shallowMount(About);
expect(
wrapper.find(".about__header").element.textContent.trim()
).toEqual("Hello");
});
});
describe("subheader", () => {
it("has a text content stating 'Passionate. Involved. Dedicated.'", () => {
const wrapper = shallowMount(About);
expect(
wrapper.find(".about__subheader").element.textContent.trim()
).toEqual("Passionate. Involved. Dedicated.");
});
});
describe("description", () => {
it("includes the proper content for the description", () => {
const wrapper = shallowMount(About);
expect(
wrapper.find(".about__description").element.textContent.trim()
).toEqual(
"I am an extremely motivated Chicago-based developer immersed in the potential of computers since the ripe age of seven. Always consumed by the latest hardware and software trends, I live and breathe to push the limits of what people think apps can do."
);
});
});
});
});
|
import { createGlobalStyle } from "styled-components";
export const GlobalStyles = createGlobalStyle`
body {
background-color: ${(props) => props.theme.body};
}
.col-header {
background-color: ${(props) => props.theme.header};
}
.App-header button {
background-color: ${(props) => props.theme.button};
color: ${(props) => props.theme.buttonColor};
}
input, form {
background: ${(props) => props.theme.input};
color: ${(props) => props.theme.inputText};
}
input[type="text"]::placeholder {
color: ${(props) => props.theme.inputText};
}
`; |
var Calc = require('./calc3');
//// Q-0. 객체는 무엇이며 인스턴스는 무엇인가?
//// A-0. 객체는 SW세계에 구현할 현실의 대상이고, 인스턴스는 SW세계에 구현된 실체이다.
var calc = new Calc(); // new연산자를 이용 인스턴스객체인 calc 생성
//// Q-1. 그냥 Calc를 쓰면 될 것을 왜 var calc에 할당한건가?
//// A-1. 이렇게 하지 않고 Calc.emit('stop')을 하면 오류발생한다.
//// A-1. TypeError: Calc.emit is not a function
//// Q-2. 그렇다면 왜 이런 에러가 발생하는건가?
//// Q-2. Calc만으로 emit 메소드를 호출할 수 없는 이유는??
//// Q-3. require을 통해 모듈을 할당받은 객체가 Calc인데? new연산자는 뭔가 다른건가?
//// A-3. new연산자를 통해 인스턴스 객체인 calc를 만들었고, 이 calc객체는 Calc객체에 상속된 것들을 사용할 수 있다.
calc.emit('stop');
// 할당받은 Calc에는 EventEmitter객체를 상속받았고 이 Emitter객체안에있는 emit메소드를 호출하여 stop이벤트를 전달한다.
console.log(Calc.title + '에 stop이벤트 전달함');
|
import React, {useState} from 'react';
import {Button, CircularProgress, Container} from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import {CustomTextField} from "../../Components/CustomTextField";
import {AccountPageTranslation} from "../../Translations/Pages/AccountPageTranslation";
import {WordTranslations} from "../../Translations/Standard/WordTranslations";
import {useStyles} from './styles';
import axios from "axios";
import {BACKEND_URL} from "../../secrets";
import {connect} from "react-redux";
import Dialog from "@material-ui/core/Dialog";
import Typography from "@material-ui/core/Typography";
import AddIcon from '@material-ui/icons/Add';
import CloseIcon from '@material-ui/icons/Close';
import {closeMessage, handleNewAccountData, openMessage} from "../../ReduxActions";
import IconButton from "@material-ui/core/IconButton";
import clsx from "clsx";
let cloneDeep = require('lodash.clonedeep');
export const PhoneFormComponent = (props) => {
const classes = useStyles();
const initialState = {
open: false,
popupStyle: 1,
fetchingCode: false,
fetchingNumber: false,
fetchingConfirmation: false,
code: "",
phone_number: "",
};
// popupStyle 0 = Dialog hidden
// popupStyle 1 = Show Code and intructions
// popupStyle 2 = Show Phone number to be confirmed and buttons "yes"/"no"
let [verifyPopup, setVerifyPopupState] = useState(initialState);
function setVerifyPopup(newState) {
let oldState = cloneDeep(verifyPopup);
Object.assign(oldState, newState);
setVerifyPopupState(oldState);
}
let [countdown, setCountdown] = useState({
interval: undefined,
minutes_left: 3,
seconds_left: 0,
});
function setState0() {
props.setActiveProcesses({verifying: false});
setVerifyPopup({open: false});
}
function setState1() {
clearInterval(countdown.interval);
setCountdown({
minutes_left: 3,
seconds_left: 0,
});
props.closeMessage();
if (!verifyPopup.open) {
props.setActiveProcesses({verifying: true});
}
setVerifyPopup({
fetchingCode: true,
});
setTimeout(() => {
triggerFetchingCode();
}, 500);
}
function setState2(code) {
let deadline = new Date().getTime();
setVerifyPopup({
open: true,
popupStyle: 1,
fetchingCode: false,
code: code,
});
// Update the count down every 1 second
let interval = setInterval(function() {
let now = new Date().getTime();
let distance = deadline - now + (3 * 60 * 1000);
if (distance > 0) {
setCountdown({
interval: interval,
minutes_left: Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
seconds_left: Math.floor((distance % (1000 * 60)) / 1000),
});
} else {
clearInterval(countdown.interval);
setCountdown({
interval: undefined,
minutes_left: 0,
seconds_left: 0,
});
}
}, 100);
}
function formatCountdown(minutes_left, seconds_left) {
let minutes_left_string = minutes_left.toString();
let seconds_left_string = seconds_left.toString();
switch (minutes_left_string.length) {
case 0:
minutes_left_string = "00" + minutes_left_string;
break;
case 1:
minutes_left_string = "0" + minutes_left_string;
break;
default:
break;
}
switch (seconds_left_string.length) {
case 0:
seconds_left_string = "00" + seconds_left_string;
break;
case 1:
seconds_left_string = "0" + seconds_left_string;
break;
default:
break;
}
return minutes_left_string + ":" + seconds_left_string;
}
function setState3() {
clearInterval(countdown.interval);
props.closeMessage();
setVerifyPopup({
fetchingNumber: true,
});
setTimeout(() => {
triggerFetchingPhoneNumber();
}, 500);
}
function setState4(phone_number) {
setVerifyPopup({
popupStyle: 2,
fetchingNumber: false,
phone_number: phone_number,
});
}
function setState5() {
props.closeMessage();
setVerifyPopup({
fetchingConfirmation: true,
});
setTimeout(() => {
triggerFetchingConfirmation();
}, 500);
}
function triggerFetchingCode() {
axios.post(BACKEND_URL + "phone/trigger", {
email: props.email,
api_key: props.api_key,
})
.then(response => {
if (response.data.status === "ok") {
props.setActiveProcesses({verifying: false});
setState2(response.data.token);
} else {
setState0();
props.openMessage(response.data.status);
}
}).catch(() => {
setState0();
props.openMessage("");
});
}
function triggerFetchingPhoneNumber() {
axios.put(BACKEND_URL + "database/helper", {
email: props.email,
api_key: props.api_key,
})
.then(response => {
if (response.data.status === "ok") {
let phone_number = response.data.account.phone_number;
if (phone_number !== "") {
setState4(phone_number);
} else {
setState2(verifyPopup.code);
props.openMessage("are you sure");
}
} else {
setState0();
props.openMessage(response.data.status);
}
}).catch(() => {
setState0();
props.openMessage("");
});
}
function triggerFetchingConfirmation() {
axios.post(BACKEND_URL + "phone/confirm", {
email: props.email,
api_key: props.api_key,
})
.then(response => {
if (response.data.status === "ok") {
setState0();
props.handleNewAccountData(response);
} else {
setState0();
props.openMessage(response.data.status);
}
}).catch(() => {
setState0();
props.openMessage("");
});
}
return (
<React.Fragment>
<Grid item xs={12} md={8}>
<CustomTextField
disabled className={classes.textField} variant="outlined"
value={(props.account.phone_number_verified
&& props.account.phone_number_confirmed) ? props.account.phone_number : ""}
label={WordTranslations.phoneNumber[props.language]} fullWidth/>
</Grid>
<Grid item xs={12} md={4} className={classes.flexButtonBox}>
<div className={classes.wrapper}>
{(props.account.phone_number_verified
&& props.account.phone_number_confirmed) && (
<Button disableElevation variant="contained" className={clsx(classes.button, classes.grayButton)}
disabled={props.activeProcesses.submitting || props.activeProcesses.resending || props.activeProcesses.verifying || props.formModified}
onClick={setState1} startIcon={<AddIcon className={classes.startIcon}/>}>
{WordTranslations.phoneNumber[props.language]}
</Button>
)}
{!(props.account.phone_number_verified
&& props.account.phone_number_confirmed) && (
<Button variant="contained" color="secondary" className={clsx(classes.button)}
disabled={props.activeProcesses.submitting || props.activeProcesses.resending || props.activeProcesses.verifying || props.formModified}
onClick={setState1} startIcon={<AddIcon className={classes.startIcon}/>}>
{WordTranslations.phoneNumber[props.language]}
</Button>
)}
{(props.activeProcesses.verifying && !verifyPopup.open) && (
<CircularProgress size={24} className={classes.buttonProgress} color="secondary"/>
)}
</div>
</Grid>
<Dialog onClose={setState0} maxWidth="sm" fullWidth open={verifyPopup.open}>
<IconButton aria-label="delete" className={classes.phoneDialogClose} onClick={setState0}>
<CloseIcon/>
</IconButton>
<Container maxWidth="sm" className={classes.phoneDialog}>
<Typography variant="h5" className={classes.phoneDialogTitle}>
<strong>{AccountPageTranslation.phonePopupTitle[props.language]}</strong>
</Typography>
{verifyPopup.popupStyle === 1 && (
<Typography variant="subtitle1" className={classes.phoneDialogText}>
{AccountPageTranslation.phonePopupText11[props.language]}
<a href="tel:+493025555301" className={classes.pinkLink}><strong>+49 30 2555 5301</strong></a>
{AccountPageTranslation.phonePopupText12[props.language]}
</Typography>
)}
{verifyPopup.popupStyle === 2 && (
<Typography variant="subtitle1" className={classes.phoneDialogText}>
{AccountPageTranslation.phonePopupText2[props.language]}
</Typography>
)}
{verifyPopup.popupStyle === 1 && (
<Typography variant="h5" className={classes.phoneDialogCode}>
{WordTranslations.code[props.language]}: <strong>{verifyPopup.code}</strong>
({formatCountdown(countdown.minutes_left, countdown.seconds_left)})
</Typography>
)}
{verifyPopup.popupStyle === 2 && (
<Typography variant="h5" className={classes.phoneDialogCode}>
{WordTranslations.phoneNumber[props.language]}: <strong>{verifyPopup.phone_number}</strong>
</Typography>
)}
<div className={classes.phoneDialogButton}>
{verifyPopup.popupStyle === 1 && (
<div className={classes.wrapper}>
<Button disableElevation
variant="contained" color="secondary" className={classes.button}
disabled={verifyPopup.fetchingNumber}
onClick={setState3}>
{AccountPageTranslation.verifyPhoneNumberButton1[props.language]}
</Button>
{verifyPopup.fetchingNumber && (
<CircularProgress size={24} className={classes.buttonProgress}
color="secondary"/>
)}
</div>
)}
{verifyPopup.popupStyle === 2 && (
<React.Fragment>
<div className={classes.wrapper}>
<Button disableElevation
variant="contained" className={clsx(classes.button, classes.grayButton)}
disabled={verifyPopup.fetchingCode || verifyPopup.fetchingConfirmation}
onClick={setState1}>
{WordTranslations.no[props.language]}
</Button>
{verifyPopup.fetchingCode && (
<CircularProgress size={24} className={classes.buttonProgress}
color="secondary"/>
)}
</div>
<div className={classes.wrapper}>
<Button disableElevation
variant="contained" color="secondary" className={classes.button}
disabled={verifyPopup.fetchingConfirmation}
onClick={setState5}>
{WordTranslations.yes[props.language]}
</Button>
{verifyPopup.fetchingConfirmation && (
<CircularProgress size={24} className={classes.buttonProgress}
color="secondary"/>
)}
</div>
</React.Fragment>
)}
</div>
</Container>
</Dialog>
</React.Fragment>
)
};
const mapStateToProps = state => ({
email: state.email,
api_key: state.api_key,
language: state.language,
account: state.account,
});
const mapDispatchToProps = dispatch => ({
handleNewAccountData: (response) => dispatch(handleNewAccountData(response)),
openMessage: (text) => dispatch(openMessage(text)),
closeMessage: () => dispatch(closeMessage()),
});
export const PhoneForm = connect(mapStateToProps, mapDispatchToProps)(PhoneFormComponent);
|
// Ver: 4.1
var nOP=0,nOP5=0,nIE=0,nIE4=0,nIE5=0,nNN=0,nNN4=0,nNN6=0,nMAC=0,nIEM=0,nIEW=0,nDM=0,nVER=0.0,st_delb=0,st_addb=0,st_reg=1;stnav();var st_ttb=nIE||nOP&&(nVER>=6&&nVER<7);
var stT2P=["static","absolute","absolute"],stHAL=["left","center","right"],stVAL=["top","middle","bottom"],stREP=["no-repeat","repeat-x","repeat-y","repeat"],stBDS=["none","solid","double","dotted","dashed","groove","ridge"];
var st_max=10,st_ht="",st_gc=0,st_rl=null,st_cl,st_ct,st_cw,st_ch,st_cm=0,st_cp,st_ci,st_ri=/Stm([0-9]*)p([0-9]*)i([0-9]*)e/,st_rp=/Stm([0-9]*)p([0-9]*)i/,st_ims=[],st_ms=[],st_load=0,st_scr=null;
var st_rsp=new RegExp(" +");
if(nNN4){stitovn=stevfn('stitov',1);stitoun=stevfn('stitou',1);stitckn=stevfn('stitck',1);stppovn=stevfn('stppov',0);stppoun=stevfn('stppou',0);}
if(nIE4||nNN4)window.onerror=function(m,u,l){return !confirm("Java Script Error\n"+"\nDescription:"+m+"\nSource:"+u+"\nLine:"+l+"\n\nSee more details?");}
if(nDM)window.onload=st_onload;
if(nIEM||nOP5)window.onunload=function(){if(st_rl){clearInterval(st_rl);st_rl=null;}return true;}
if(typeof(st_js)=='undefined'){
if(nDM&&!nNN4)
{
var s="<STYLE>\n.st_tbcss,.st_tdcss,.st_divcss,.st_ftcss{border:none;padding:0px;margin:0px;}\n</STYLE>";
for(var i=0;i<st_max;i++)
s+="<FONT ID=st_gl"+i+"></FONT>";
if(nIEW&&nVER>=5.0&&document.body)
document.body.insertAdjacentHTML("AfterBegin",s);
else
document.write(s);
}st_js=1;}
function stm_bm(a)
{
st_ms[st_cm]=
{
ps:[],
mei:st_cm,
ids:"Stm"+st_cm+"p",
hdid:null,
cked:0,
tfrm:window,
sfrm:window,
mcff:"",
mcfd:0,
mcfx:0,
mcfy:0,
mnam:a[0],
mver:a[1],
mweb:a[2],
mbnk:stbuf(a[2]+a[3]),
mtyp:a[4],
mcox:a[5],
mcoy:a[6],
maln:stHAL[a[7]],
mcks:a[8],
msdv:a[9],
msdh:a[10],
mhdd:nNN4?Math.max(100,a[11]):a[11],
mhds:a[12],
mhdo:a[13],
mhdi:a[14],
args:a.slice(0)
};
}
function stm_bp(l,a)
{
var op=st_cp;var oi=st_ci;st_cp=st_ms[st_cm].ps.length;st_ci=0;
var m=st_ms[st_cm];
m.ps[st_cp]=
{
is:[],
mei:st_cm,
ppi:st_cp,
ids:"Stm"+st_cm+"p"+st_cp+"i",
par:(st_cp?[st_cm,op,oi]:null),
tmid:null,
citi:-1,
issh:0,
isst:!st_cp&&m.mtyp==0,
isck:!st_cp&&m.mcks,
exed:0,
pver:a[0],
pdir:a[1],
poffx:a[2],
poffy:a[3],
pspc:a[4],
ppad:a[5],
plmw:a[6],
prmw:a[7],
popc:a[8],
pesh:a[9]?a[9]:"Normal",
pesi:a[10],
pehd:a[11]?a[11]:"Normal",
pehi:a[12],
pesp:a[13],
pstp:a[14],
psds:nIEW?a[15]:0,
pscl:a[16],
pbgc:a[17],
pbgi:stbuf(stgsrc(a[18],m,0)),
pbgr:stREP[a[19]],
pbds:stBDS[a[20]],
ipbw:a[21],
pbdc:(!nDM||nNN4)?a[22].split(st_rsp)[0]:a[22],
args:a.slice(0)
};
var p=m.ps[st_cp];
if(st_cp) stgpar(p).sub=[st_cm,st_cp];
p.zind=!st_cp?1000:stgpar(stgpar(p)).zind+10;
p.pbgd=stgbg(p.pbgc,p.pbgi,p.pbgr);
if(nIEW&&nVER>=5.5)
{
p.efsh=p.pesh=="Normal"?"stnm":"stft";
p.efhd=p.pehd=="Normal"?"stnm":"stft";
}
else if(nIEW&&(nVER>=5.0||nVER>=4.0&&!p.isst))
{
p.efsh=p.pesi>=0?"stft":"stnm";
p.efhd=p.pehi>=0?"stft":"stnm";
}
else
p.efsh=p.efhd="stnm";
eval(l+"=p;");
}
function stm_bpx(l,r,a)
{
var p=eval(r);
stm_bp(l,a.concat(p.args.slice(a.length)));
}
function stm_ai(l,a)
{
st_ci=st_ms[st_cm].ps[st_cp].is.length;
var m=st_ms[st_cm];
var p=m.ps[st_cp];
if(a[0]==6)
p.is[st_ci]=
{
ssiz:a[1],
ibgc:[a[2]],
simg:stbuf(stgsrc(a[3],m,1)),
simw:a[4],
simh:a[5],
simb:a[6],
args:a.slice(0)
};
else
p.is[st_ci]=
{
itex:a[0]?a[1]:a[1].replace(new RegExp(" ","g"),nMAC?" ":" "),
iimg:[stbuf(stgsrc(a[2],m,0)),stbuf(stgsrc(a[3],m,0))],
iimw:a[4],
iimh:a[5],
iimb:a[6],
iurl:a[7],
itgt:a[8],
istt:a[9],
itip:a[10],
iicn:[stbuf(stgsrc(a[11],m,1)),stbuf(stgsrc(a[12],m,1))],
iicw:a[13],
iich:a[14],
iicb:a[15],
iarr:[stbuf(stgsrc(a[16],m,1)),stbuf(stgsrc(a[17],m,1))],
iarw:a[18],
iarh:a[19],
iarb:a[20],
ihal:stHAL[a[21]],
ival:stVAL[a[22]],
ibgc:nOP5&&nVER<7.0&&a[24]&&a[26]?["transparent","transparent"]:[nOP5&&nVER<7.0||!a[24]?a[23]:"transparent",nOP5&&nVER<7.0||!a[26]?a[25]:"transparent"],
ibgi:[stbuf(stgsrc(a[27],m,0)),stbuf(stgsrc(a[28],m,0))],
ibgr:[stREP[a[29]],stREP[a[30]]],
ibds:stBDS[a[31]],
ipbw:a[32],
ibdc:(!nDM||nNN4)?[a[33].split(st_rsp)[0],a[34].split(st_rsp)[0]]:[a[33],a[34]],
itxc:[a[35],a[36]],
itxf:[a[37],a[38]],
itxd:[stgdec(a[39]),stgdec(a[40])],
args:a.slice(0)
};
var it=st_ms[st_cm].ps[st_cp].is[st_ci];
it.ityp=a[0];
it.mei=st_cm;
it.ppi=st_cp;
it.iti=st_ci;
it.ids=p.ids+st_ci+"e";
it.sub=null;
it.tmid=null;
if(it.ityp!=6)
it.ibgd=[stgbg(it.ibgc[0],it.ibgi[0],it.ibgr[0]),stgbg(it.ibgc[1],it.ibgi[1],it.ibgr[1])];
eval(l+"=it;");
}
function stm_aix(l,r,a)
{
var i=eval(r);
stm_ai(l,a.concat(i.args.slice(a.length)));
}
function stm_ep()
{
var m=st_ms[st_cm];
var p=m.ps[st_cp];
var i=stgpar(p);
if(i)
{
st_cm=i.mei;
st_cp=i.ppi;
st_ci=i.iti;
}
if(p.is.length==0)
{
m.ps.length--;
if(i)
i.sub=null;
}
}
function stm_em()
{
var m=st_ms[st_cm];
if(m.ps.length==0)
{
st_ms.length--;
return;
}
var mh="";
var mc="<STYLE TYPE='text/css'>\n";
var l=nDM?m.ps.length:1;
for(var ppi=0;ppi<l;ppi++)
{
var p=m.ps[ppi];
var ph=stpbtx(p);
if(p.isst&&m.maln!="left")
ph="<TABLE STYLE='border:none;padding:0px;' CELLPADDING=0 CELLSPACING=0 ALIGN="+m.maln+"><TD class=st_tdcss>"+ph;
for(var iti=0;iti<p.is.length;iti++)
{
var i=p.is[iti];
var ih="";
ih+=p.pver ? "<TR ID="+i.ids+"TR>" : "";
ih+=stittx(i);
ih+=(p.pver ? "</TR>" : "");
ph+=ih;
if(i.ityp!=6)
{
mc+="."+i.ids+"TX0{"+sttcss(i,0)+"}\n";
mc+="."+i.ids+"TX1{"+sttcss(i,1)+"}\n";
}
}
ph+=stpetx(p);
if(p.isst&&m.maln!="left")
ph+="</TD></TABLE>";
if(p.isst||nNN4||!nDM)
mh+=ph;
else
st_ht+=ph;
}
mc+="</STYLE>";
if(!nDM||nNN4)
document.write(mc);
if(mh)
document.write(mh);
if(nDM&&!(nIEM||(nIEW&&nVER<5.0)))
{
if(st_ht)
{
var o=stgobj('st_gl'+st_gc,'font');
if(nNN6)
o.innerHTML=st_ht;
else if(nIE&&nVER>=5.0)
o.insertAdjacentHTML("BeforeEnd",st_ht);
else
o.document.write(st_ht);
st_gc++;
st_ht='';
}
if(!nOP&&!nNN)
stpre(m);
}
st_cm++;st_cp=0;st_ci=0;
}
function stpbtx(p)
{
var s="";
if(nNN4||!nDM)
{
s+=p.isst?"<ILAYER":"<LAYER";
s+=" VISIBILITY=hide";
s+=" ID="+p.ids;
s+=" Z-INDEX="+p.zind;
s+="><LAYER>";
s+="<TABLE BORDER=0 CELLSPACING=0 CELLPADDING="+p.pspc;
s+=" BACKGROUND='"+p.pbgi+"'";
s+=" BGCOLOR="+(p.pbgi||p.pbgc=="transparent"?"''":p.pbgc);
s+=">";
}
else
{
var ds="position:"+stT2P[p.ppi?1:stgme(p).mtyp]+";";
ds+="z-index:"+p.zind+";";
ds+="visibility:hidden;";
s+=st_ttb ? "<TABLE class=st_tbcss CELLPADDING=0 CELLSPACING=0" : "<DIV class=st_divcss";
s+=stppev(p);
s+=" ID="+p.ids;
s+=" STYLE='";
if(nIEM)
s+="width:1px;";
else if(nIE)
s+="width:0px;";
s+=stfcss(p);
s+=ds;
s+="'>";
if(st_ttb)
s+="<TD class=st_tdcss ID="+p.ids+"TTD>";
s+="<TABLE class=st_tbcss CELLSPACING=0 CELLPADDING=0";
s+=" ID="+p.ids+"TB";
s+=" STYLE='";
s+=stpcss(p);
if(nIEW)
s+="margin:"+p.psds+"px;";
s+="'>";
}
return s;
}
function stpetx(p)
{
var s="</TABLE>";
if(nNN4||!nDM)
s+="</LAYER></LAYER>";
else if(st_ttb)
s+="</TD></TABLE>";
else
s+="</DIV>";
return s;
}
function stittx(i)
{
var s="";
var p=stgpar(i);
if(nNN4||!nDM)
{
s+="<TD WIDTH=1 NOWRAP>";
s+="<FONT STYLE='font-size:1pt;'>";
s+="<ILAYER ID="+i.ids+"><LAYER";
if(i.ipbw&&i.ityp!=6)
s+=" BGCOLOR="+i.ibdc[0];
s+=">";
for(var l=0;l<(nNN4?2:1);l++)
{
if(i.ityp==6&&l)
break;
s+="<LAYER Z-INDEX=10 VISIBILITY="+(l?"HIDE":"SHOW");
if(i.ityp!=6)
{
s+=" LEFT="+i.ipbw+" TOP="+i.ipbw;
}
s+=">";
s+="<TABLE ALIGN=LEFT WIDTH=100% BORDER=0 CELLSPACING=0 CELLPADDING="+(i.ityp==6 ? 0 : p.ppad);
s+=" BACKGROUND='"+(i.ityp!=6?i.ibgi[l]:"")+"'";
s+=" BGCOLOR="+(i.ityp!=6&&i.ibgi[l]||i.ibgc[l]=="transparent"?"''":i.ibgc[l])
s+=">";
if(i.ityp==6)
{
s+="<TD NOWRAP VALIGN=TOP"+
" HEIGHT="+(p.pver ? i.ssiz : "100%")+
" WIDTH="+(p.pver ? "100%" : i.ssiz)+
" STYLE='font-size:0pt;'"+
">";
s+=stgimg(i.simg,i.ids+"LINE",i.simw,i.simh,0);
s+="</TD>";
}
else
{
if(p.pver&&p.plmw||!p.pver&&i.iicw)
{
s+="<TD ALIGN=CENTER VALIGN=MIDDLE";
s+=stgiws(i);
s+=">";
s+=stgimg(i.iicn[l],"",i.iicw,i.iich,i.iicb);
s+="</TD>";
}
s+="<TD WIDTH=100% NOWRAP ALIGN="+i.ihal+" VALIGN="+i.ival+">";
s+="<A "+stgurl(i)+" CLASS='"+(i.ids+"TX"+l)+"'>";
if(i.ityp==2)
s+=stgimg(i.iimg[l],i.ids+"IMG",i.iimw,i.iimh,i.iimb);
else
{
s+="<IMG SRC=\""+stgme(i).mbnk+"\" WIDTH=1 HEIGHT=1 BORDER=0 ALIGN=ABSMIDDLE>";
s+=i.itex;
}
s+="</A>";
s+="</TD>";
if(p.pver&&p.prmw||!p.pver&&i.iarw)
{
s+="<TD ALIGN=CENTER VALIGN=MIDDLE";
s+=stgaws(i);
s+=">";
s+=stgimg(i.iarr[l],"",i.iarw,i.iarh,i.iarb);
s+="</TD>";
}
}
s+="</TABLE>";
if(i.ipbw&&i.ityp!=6)
s+="<BR CLEAR=ALL><SPACER HEIGHT=1 WIDTH="+i.ipbw+"></SPACER><SPACER WIDTH=1 HEIGHT="+i.ipbw+"></SPACER>";
s+="</LAYER>";
}
if(i.ityp!=6)
s+="<LAYER Z-INDEX=20></LAYER>";
s+="</LAYER></ILAYER>"
s+="</FONT>";
s+="</TD>";
}
else
{
s+="<TD class=st_tdcss NOWRAP VALIGN="+(nIE ? "MIDDLE" : "TOP");
s+=" STYLE='"
s+="padding:"+p.pspc+"px;";
s+="'";
s+=" ID="+p.ids+i.iti;
if(nIEW)
s+=" HEIGHT=100%";
s+=">";
if(!nOP&&!nIE)
{
s+="<DIV class=st_divcss ID="+i.ids;
s+=stitev(i);
s+=" STYLE=\""+sticss(i,0);
s+="\"";
s+=">";
}
s+="<TABLE class=st_tbcss CELLSPACING=0 CELLPADDING=0";
if(!nOP)
s+=" HEIGHT=100%";
s+=" STYLE=\"";
if(nOP||nIE)
s+=sticss(i,0);
s+="\"";
if(nOP||nIE)
s+=stitev(i);
if(p.pver||nIEM)
s+=" WIDTH=100%";
s+=" ID="+(nOP||nIE ? i.ids : (i.ids+"TB"));
if(!nOP)
s+=" TITLE="+stquo(i.ityp!=6 ? i.itip : "");
s+=">";
if(i.ityp==6)
{
s+="<TD class=st_tdcss NOWRAP VALIGN=TOP"+
" ID="+i.ids+"MTD"+
" HEIGHT="+(p.pver ? i.ssiz : "100%")+
" WIDTH="+(p.pver ? "100%" : i.ssiz)+
">";
s+=stgimg(i.simg,i.ids+"LINE",i.simw,i.simh,0);
s+="</TD>";
}
else
{
if(p.pver&&p.plmw||!p.pver&&i.iicw)
{
s+="<TD class=st_tdcss NOWRAP ALIGN=CENTER VALIGN=MIDDLE HEIGHT=100%";
s+=" STYLE=\"padding:"+p.ppad+"px\"";
s+=" ID="+i.ids+"LTD";
s+=stgiws(i);
s+=">";
s+=stgimg(i.iicn[0],i.ids+"ICON",i.iicw,i.iich,i.iicb);
s+="</TD>";
}
s+="<TD class=st_tdcss NOWRAP HEIGHT=100% STYLE=\"";
s+="color:"+i.itxc[0]+";";
s+="padding:"+p.ppad+"px;";
s+="\"";
s+=" ID="+i.ids+"MTD";
s+=" ALIGN="+i.ihal;
s+=" VALIGN="+i.ival+">";
s+="<FONT class=st_ftcss ID="+i.ids+"TX STYLE=\""+sttcss(i,0)+"\">";
if(i.ityp==2)
s+=stgimg(i.iimg[0],i.ids+"IMG",i.iimw,i.iimh,i.iimb);
else
s+=i.itex;
s+="</FONT>";
s+="</TD>";
if(p.pver&&p.prmw||!p.pver&&i.iarw)
{
s+="<TD class=st_tdcss NOWRAP ALIGN=CENTER VALIGN=MIDDLE HEIGHT=100%";
s+=" STYLE=\"padding:"+p.ppad+"px\"";
s+=" ID="+i.ids+"RTD";
s+=stgaws(i);
s+=">";
s+=stgimg(i.iarr[0],i.ids+"ARROW",i.iarw,i.iarh,i.iarb);
s+="</TD>";
}
}
s+="</TABLE>";
if(!nOP&&!nIE)
s+="</DIV>";
s+="</TD>";
}
return s;
}
function stpcss(p)
{
var s="";
s+="border-style:"+p.pbds+";";
s+="border-width:"+p.ipbw+"px;";
s+="border-color:"+p.pbdc+";";
if(nIE)
s+="background:"+p.pbgd+";";
else
{
s+="background-color:"+(p.pbgc)+";";
if(p.pbgi)
{
s+="background-image:url("+p.pbgi+");";
s+="background-repeat:"+p.pbgr+";";
}
}
return s;
}
function stfcss(p)
{
var s="";
if(nIEW&&(nVER>=5.0||!p.isst))
{
var dx=nVER>=5.5?"progid:DXImageTransform.Microsoft." : "";
s+="filter:";
if(nVER>=5.5)
{
if(p.pesh!="Normal")
s+=p.pesh+" ";
}
else
{
if(p.pesi<24&&p.pesi>=0)
s+="revealTrans(Transition="+p.pesi+",Duration="+((110-p.pesp)/100)+") ";
}
s+=dx+"Alpha(opacity="+p.popc+") ";
if(p.psds)
{
if(p.pstp==1)
s+=dx+"dropshadow(color="+p.pscl+",offx="+p.psds+",offy="+p.psds+",positive=1) ";
else
s+=dx+"Shadow(color="+p.pscl+",direction=135,strength="+p.psds+") ";
}
if(nVER>=5.5)
{
if(p.pehd!="Normal")
s+=p.pehd+" ";
}
else
{
if(p.pehi<24&&p.pehi>=0)
s+="revealTrans(Transition="+p.pehi+",Duration="+((110-p.pesp)/100)+") ";
}
s+=";";
}
return s;
}
function sticss(i,n)
{
var s="";
if(i.ityp!=6)
{
s+="border-style:"+i.ibds+";";
s+="border-width:"+i.ipbw+"px;";
s+="border-color:"+i.ibdc[n]+";";
if(!nIEM&&i.ibgi[n])
{
s+="background-image:url("+i.ibgi[n]+");";
s+="background-repeat:"+i.ibgr[n]+";";
}
}
if(nIEM&&i.ityp!=6)
s+="background:"+i.ibgd[n]+";";
else
s+="background-color:"+i.ibgc[n]+";";
s+="cursor:"+stgcur(i)+";";
return s;
}
function sttcss(i,n)
{
var s="";
s+="cursor:"+stgcur(i)+";";
s+="font:"+i.itxf[n]+";";
s+="text-decoration:"+i.itxd[n]+";";
if(!nDM||nNN4)
s+="background-color:transparent;color:"+i.itxc[n];
return s;
}
function stitov(e,o,i)
{
if(nIEW)
{
if(!i.layer)
i.layer=o;
if(!stgpar(i).issh||(e.fromElement&&o.contains(e.fromElement)))
return;
}
else
{
if(!stgpar(i).issh||(!nNN&&(e.fromElement&&e.fromElement.id&&e.fromElement.id.indexOf(i.ids)>=0)))
return;
}
if(nNN4)
stglay(i).document.layers[0].captureEvents(Event.CLICK);
var m=stgme(i);
if(!i.ppi&&m.mcff)
stfrm(m);
var w=m.sfrm;
if(w!=window)
m=w.stmenu(m.mnam);
if(m.hdid)
{
w.clearTimeout(m.hdid);
m.hdid=null;
}
var cii=stgpar(i).citi;
var ci=null;
if(cii>=0)
ci=stgpar(i).is[cii];
var p=stgpar(i);
if(!p.isck||stgme(i).cked)
{
if(p.citi!=i.iti)
{
if(p.citi>=0)
{
sthdit(p.is[p.citi]);
p.citi=-1;
}
stshit(i);
p.citi=i.iti;
}
else
{
var p=stgtsub(i);
if(p&&!p.issh)
stshit(i);
}
}
if(i.istt)
window.status=i.istt;
}
function stitou(e,o,i)
{
if(nIEW)
{
if(!stgpar(i).issh||e.toElement&&o.contains(e.toElement))
return;
}
else
{
if(!stgpar(i).issh||(!nNN&&(e.toElement&&e.toElement.id&&e.toElement.id.indexOf(i.ids)>=0)))
return;
}
if(nNN4)
stglay(i).document.layers[0].releaseEvents(Event.CLICK);
var p=stgtsub(i);
if(!p||!p.issh)
{
stshst(i,0);
stgpar(i).citi=-1;
}
else if(p&&p.issh&&!p.exed)
sthdit(i);
window.status="";
}
function stitck(e,o,i)
{
if(e.button&&e.button>=2)
return;
var m=stgme(i);
var p=stgpar(i);
if(p.isck)
{
m.cked=!m.cked;
if(m.cked)
{
stshit(i);
p.citi=i.iti;
}
else
{
sthdit(i);
p.citi=-1;
}
}
if(!nNN4&&!(p.isck&&stgsub(i))&&i.iurl)
{
if(i.iurl.toLowerCase().indexOf("javascript:")==0)
eval(i.iurl.substring(11,i.iurl.length));
else if(i.itgt=="_self")
window.location.href=i.iurl;
else if(i.itgt=="_parent")
window.parent.location.href=i.iurl;
else if(i.itgt=="_top")
window.top.location.href=i.iurl;
else
{
for(var co=window;co!=co.parent;co=co.parent)
{
if(typeof(co.parent.frames[i.itgt])!="undefined")
{
co.parent.frames[i.itgt].location.href=i.iurl;
return;
}
}
window.open(i.iurl,i.itgt);
}
}
}
function stppov(e,o,p)
{
if(nIEW)
{
if(!p.layer)
p.layer=o;
if(!p.issh||(e.fromElement&&o.contains(e.fromElement)))
return;
}
else
{
if(!p.issh||(!nNN&&(e.fromElement&&e.fromElement.id&&e.fromElement.id.indexOf(p.ids)>=0)))
return;
}
var m=stgme(p);
var w=m.sfrm;
if(w!=window)
m=w.stmenu(m.mnam);
if(m.hdid)
{
w.clearTimeout(m.hdid);
m.hdid=null;
}
}
function stppou(e,o,p)
{
if(nIEW)
{
if(!p.issh||(e.toElement&&o.contains(e.toElement)))
return;
}
else
{
if(!p.issh||(!nNN&&(e.toElement&&e.toElement.id&&e.toElement.id.indexOf(p.ids)>=0)))
return;
}
var m=stgme(p);
var w=m.sfrm;
if(w!=window)
m=w.stmenu(m.mnam);
if(m.hdid)
w.clearTimeout(m.hdid);
m.hdid=w.setTimeout("sthdall(st_ms['"+m.mei+"'],0);",m.mhdd);
}
function stshst(i,n)
{
if(nNN4)
{
var ls=stgstlay(i);
ls[n].parentLayer.bgColor=i.ibdc[n];
ls[n].visibility="show";
ls[1-n].visibility="hide";
}
else
{
var os=stglay(i).style;
if(nIEM)
{
if(i.ibgd[0]!=i.ibgd[1]) os.background=i.ibgd[n];
}
else
{
if(i.ibgc[0]!=i.ibgc[1])
{
if(nOP&&nVER<6)
os.background=i.ibgc[n];
else
os.backgroundColor=i.ibgc[n];
}
if(i.ibgi[0]!=i.ibgi[1]) os.backgroundImage="url("+(i.ibgi[n]?i.ibgi[n]:stgme(i).mbnk)+")";
if(i.ibgr[0]!=i.ibgr[1]) os.backgroundRepeat=i.ibgr[n];
}
if(i.ibdc[0]!=i.ibdc[1]) os.borderColor=i.ibdc[n];
var t;
if(i.iicn[0]!=i.iicn[1])
{
t=stgobj(i.ids+'ICON','IMG');
if(t) t.src=i.iicn[n];
}
if(i.iarr[0]!=i.iarr[1])
{
t=stgobj(i.ids+'ARROW','IMG');
if(t) t.src=i.iarr[n];
}
if(i.ityp==2&&i.iimg[0]!=i.iimg[1])
{
t=stgobj(i.ids+'IMG','IMG');
if(t) t.src=i.iimg[n];
}
if (!i.txstyle) i.txstyle=stgobj(i.ids+"TX",'FONT').style;
t=i.txstyle;
if(i.itxf[0]!=i.itxf[1])
t.font=i.itxf[n];
if(i.itxd[0]!=i.itxd[1])
t.textDecoration=i.itxd[n];
if(nOP) stgobj(i.ids+'MTD','td').style.color=i.itxc[n];
else t.color=i.itxc[n];
}
}
function stshpp(p)
{
stshow(p);
}
function sthdpp(p)
{
if(p.citi>=0)
{
var t=stgsub(p.is[p.citi]);
if(t&&t.issh)
sthdpp(t);
stshst(p.is[p.citi],0);
p.citi=-1;
}
sthide(p);
}
function stshit(i)
{
var w=stgme(i).tfrm;
var p=stgtsub(i);
if(p&&!p.issh)
w.stshpp(p);
stshst(i,1);
}
function sthdit(i)
{
var w=stgme(i).tfrm;
var p=stgtsub(i);
if(p&&p.issh)
w.sthdpp(p);
stshst(i,0);
}
function stshow(p)
{
var d=p.ppi&&stgpar(stgpar(p)).pver ? stgme(p).msdv : stgme(p).msdh;
p.exed=0;
if(!p.rc)
stgxy(p);
if(p.tmid)
{
clearTimeout(p.tmid);
p.tmid=null;
stwels(1,p)
}
if(d>0)
p.tmid=setTimeout(stsdstr(p,1),d);
p.issh=1;
if(d<=0)
eval(stsdstr(p,1));
}
function sthide(p)
{
if(p.tmid)
{
clearTimeout(p.tmid);
p.tmid=null;
}
if(p.issh&&!p.exed)
{
p.exed=0;
p.issh=0;
}
else
{
p.exed=0;
p.issh=0;
eval(stsdstr(p,0));
}
}
function stshx(p)
{
var ly=stglay(p);
if(nNN4)
{
ly.visibility='show';
if(!p.fixed)
{
ly.resizeBy(p.ipbw*2,p.ipbw*2);
ly=ly.document.layers[0];
ly.moveTo(p.ipbw,p.ipbw);
ly.onmouseover=stppovn;
ly.onmouseout=stppoun;
for(var l=p.is.length-1;l>=0;l--)
{
var i=p.is[l];
if(i.ityp!=6)
{
var ls=stgstlay(i);
ls[2].resizeTo(ls[0].parentLayer.clip.width,ls[0].parentLayer.clip.height);
if(stgcur(i)=="hand")
{
with(ls[2].document)
{
open();
write("<A "+stgurl(i)+"\"><IMG BORDER=0 SRC='"+stgme(i).mbnk+"' WIDTH="+ls[2].clip.width+" HEIGHT="+ls[2].clip.height+"></A>");
close();
}
}
ls[0].resizeBy(-i.ipbw,-i.ipbw);
ls[1].resizeBy(-i.ipbw,-i.ipbw);
ly=stglay(i).document.layers[0];
ly.onmouseover=stitovn;
ly.onmouseout=stitoun;
ly.onclick=stitckn;
}
}
if(p.ipbw)
setTimeout("var pp=st_ms["+p.mei+"].ps["+p.ppi+"];stglay(pp).bgColor=pp.pbdc;",1);
p.fixed=1;
}
}
else
{
ly.style.visibility='visible';
if(nIE5)
ly.filters['Alpha'].opacity=p.popc;
}
}
function sthdx(p)
{
var ly=stglay(p);
if(nNN4)
ly.visibility='hide';
else
{
if(nIE5)
ly.filters['Alpha'].opacity=0;
ly.style.visibility='hidden';
}
}
function sthdall(m,f)
{
var w=m.sfrm;
var s=w==window?m:w.stmenu(m.mnam);
s.cked=0;
var p=s.ps[0];
if(p.issh)
{
if(p.citi>=0)
{
w.sthdit(p.is[p.citi]);
p.citi=-1;
}
if(s.mtyp==2&&f)
w.sthide(p);
}
s.hdid=null;
}
function stnmsh(p)
{
stmvto(stgxy(p),p);
stwels(-1,p);
stshx(p);
}
function stnmhd(p)
{
sthdx(p);
stwels(1,p);
}
function stftsh(p)
{
if(nVER<5.5)
stshfx(p);
else if(st_reg)
eval("try{stshfx(p);} catch(er){st_reg=0;stnmsh(p);}");
else
stnmsh(p);
}
function stfthd(p)
{
if(nVER<5.5)
sthdfx(p);
else if(st_reg)
eval("try{sthdfx(p);}catch(er){st_reg=0;stnmhd(p);}");
else
stnmhd(p);
}
function stshfx(p)
{
var t=stglay(p).filters[0];
if(nVER>=5.5)
t.enabled=1;
if(t.Status!=0)
t.stop();
stmvto(stgxy(p),p);
stwels(-1,p);
t.apply();
stshx(p);
t.play();
}
function sthdfx(p)
{
var t=stglay(p).filters[stglay(p).filters.length-1];
if(nVER>=5.5)
t.enabled=1;
if(t.Status!=0)
t.stop();
t.apply();
sthdx(p);
stwels(1,p);
t.play();
}
function ststxy(m,xy)
{
m.mcox=xy[0];
m.mcoy=xy[1];
}
function stnav()
{
var v=navigator.appVersion;
var a=navigator.userAgent;
nMAC=v.indexOf("Mac")>=0;
nOP=a.indexOf("Opera")>=0;
if(nOP)
{
nVER=parseFloat(a.substring(a.indexOf("Opera ")+6,a.length));
nOP5=nVER>=5.12&&!nMAC&&a.indexOf("MSIE 5.0")>=0;
if(nVER>=7) nOP5=1;
}
else
{
nIE=document.all ? 1 : 0;
if(nIE)
{
nIE4=(eval(v.substring(0,1)>=4));
nVER=parseFloat(a.substring(a.indexOf("MSIE ")+5,a.length));
nIE5=nVER>=5.0&&nVER<5.5&&!nMAC;
nIEM=nIE4&&nMAC;
nIEW=nIE4&&!nMAC;
}
else
{
nNN4=navigator.appName.toLowerCase()=="netscape"&&v.substring(0,1)=="4" ? 1 : 0;
if(!nNN4)
{
nNN6=(document.getElementsByTagName("*") && a.indexOf("Gecko")!=-1);
if(nNN6)
{
nVER=parseInt(navigator.productSub);
if(a.indexOf("Netscape")>=0)
{
st_delb=nVER<20001108+1;
st_addb=nVER>20020512-1;
}
else
{
st_delb=nVER<20010628+1;
st_addb=nVER>20011221-1;
}
}
}
else
nVER=parseFloat(v);
nNN=nNN4||nNN6;
}
}
nDM=nOP5||nIE4||nNN;
}
function stckpg()
{
var w=st_cw;
var h=st_ch;
var l=st_cl;
var t=st_ct;
st_cw=stgcw();
st_ch=stgch();
st_cl=stgcl();
st_ct=stgct();
if(((nOP&&nVER<7.0)||nNN4)&&(st_cw-w||st_ch-h))
document.location.reload();
else if(st_cl-l||st_ct-t)
stscr();
}
function st_onload()
{
if(nIEM||nOP5||nNN||(nIEW&&nVER<5.0))
{
if(st_ht)
document.body.insertAdjacentHTML('BeforeEnd',st_ht);
for(i=0;i<st_ms.length;i++)
stpre(st_ms[i]);
}
st_load=1;
if(!nNN4)
{
for(var i=0;i<st_ms.length;i++)
{
var m=st_ms[i];
for(var j=0;j<m.ps.length;j++)
{
var p=m.ps[j];
if(p.issh&&p.exed)
stwels(-1,p);
}
}
}
}
function stpre(m)
{
var p=m.ps[m.ps.length-1];
var i=p.is[p.is.length-1];
while(1)
if(stglay(i)) break;
if(!nNN4)
stfix(m);
if(m.mtyp!=2)
stshow(m.ps[0]);
if(nIE||nNN6)
window.onscroll=new Function("if(st_scr)clearTimeout(st_scr);st_scr=setTimeout('stscr();',nIEM ?500:0);");
else if(!st_rl)
{
st_cw=stgcw();
st_ch=stgch();
st_cl=stgcl();
st_ct=stgct();
st_rl=setInterval("stckpg();",500);
}
m.ready=1;
}
function stfix(m)
{
for(var l=0;l<m.ps.length;l++)
{
var p=m.ps[l];
if(nOP&&nVER<6.0)
stglay(p).style.pixelWidth=parseInt(stgobj(p.ids+"TB",'table').style.pixelWidth);
if(nIE5)
stglay(p).style.width=stglay(p).offsetWidth;
else if(nIEM||!nIE)
{
if(!p.pver)
{
var ii=0;
var fi=stgobj(p.ids+ii);
var h=parseInt(nOP ? fi.style.pixelHeight : fi.offsetHeight);
if(h)
{
for(ii=0;ii<p.is.length;ii++)
{
var i=p.is[ii];
var lys=stglay(i).style;
var th=h-2*p.pspc;
if(nOP)
lys.pixelHeight=th;
else if(i.ityp==6||nIE)
lys.height=th+'px';
else
lys.height=th-2*i.ipbw+'px';
if(nIEM)
{
var fh=h-2*p.pspc;
var lt=stgobj(i.ids+"LTD");
var rt=stgobj(i.ids+"RTD");
if(lt)
lt.style.height=fh+'px';
stgobj(i.ids+"MTD").style.height=fh+'px';
if(rt)
rt.style.height=fh+'px';
}
}
}
}
else if(nOP)
{
for(var ii=0;ii<p.is.length;ii++)
{
var i=p.is[ii];
if(i.ityp!=6)
{
var fi=stgobj(p.ids+ii);
var it=stglay(i);
var w=parseInt(fi.style.pixelWidth);
var h=parseInt(it.style.pixelHeight);
if(w)
it.style.pixelWidth=w-2*p.pspc;
if(h)
it.style.pixelHeight=h;
}
}
}
}
}
}
function stscr()
{
for(var l=0;l<st_ms.length;l++)
{
var m=st_ms[l];
if(m)
{
sthdall(m,0);
if(m.mtyp==1)
{
var p=m.ps[0];
stwels(1,p);
stmvto(stgxy(m.ps[0]),p);
stwels(-1,p);
}
}
}
}
function stwels(c,p)
{
var m=stgme(p);
if(!st_load||nNN4||nOP||p.isst) return;
if(m.mhds&&!nNN6) stwtag("SELECT",c,p);
if(m.mhdo) stwtag("OBJECT",c,p);
if(m.mhdi&&!nNN6&&!(nIEW&&nVER>=5.5)) stwtag("IFRAME",c,p);
}
function stwtag(tg,c,o)
{
var es=nNN6 ? document.getElementsByTagName(tg) : document.all.tags(tg);
var l;
for(l=0;l<es.length;l++)
{
var e=es.item(l);
var f=0;
for(var t=e.offsetParent;t;t=t.offsetParent)
if(t.id&&t.id.indexOf("Stm")>=0)
f=1;
if(f)
continue;
else if(stwover(e,o))
{
if(e.visLevel)
e.visLevel+=c;
else
e.visLevel=c;
if(e.visLevel==-1)
{
if(typeof(e.visSave)=='undefined')
e.visSave=e.style.visibility;
e.style.visibility="hidden";
}
else if(e.visLevel==0)
e.style.visibility=e.visSave;
}
}
}
function stmvto(xy,p)
{
if(xy&&(p.ppi||stgme(p).mtyp!=0))
{
var l=stglay(p);
if(nNN4)
l.moveToAbsolute(xy[0],xy[1]);
else if(nOP)
{
var ls=l.style;
ls.pixelLeft=xy[0];
ls.pixelTop=xy[1];
}
else
{
var ls=l.style;
ls.left=xy[0]+'px';
ls.top=xy[1]+'px';
}
p.rc=[xy[0],xy[1],p.rc[2],p.rc[3]];
}
}
function stsdstr(p,iss)
{
return "var pp=st_ms["+p.mei+"].ps["+p.ppi+"];pp.tmid=null;"+(iss? p.efsh+"sh(" : p.efhd+"hd(")+"pp);pp.exed=1;"
}
function stwover(e,o)
{
var l=0;
var t=0;
var w=e.offsetWidth;
var h=e.offsetHeight;
if(w)
e._wd=w;
else
w=e._wd;
if(h)
e._ht=h;
else
h=e._ht;
while(e)
{
l+=e.offsetLeft;
t+=e.offsetTop;
e=e.offsetParent;
}
return ((l<o.rc[2]+o.rc[0]) && (l+w>o.rc[0]) && (t<o.rc[3]+o.rc[1]) && (t+h>o.rc[1]));
}
function stevfn(pr,isi)
{
var s=isi ? 'st_ri' : 'st_rp';
s+='.exec(this.parentLayer.id);mei=RegExp.$1;ppi=parseInt(RegExp.$2);';
if(isi) s+='iti=parseInt(RegExp.$3);return '+pr+'(e,this,st_ms[mei].ps[ppi].is[iti]);';
else s+='return '+pr+'(e,this,st_ms[mei].ps[ppi]);';
return new Function('e',s);
}
function stppev(p)
{
var s=" onMouseOver='stppov(event,this,st_ms["+p.mei+"].ps["+p.ppi+"]);'";
s+=" onMouseOut='stppou(event,this,st_ms["+p.mei+"].ps["+p.ppi+"]);'";
return s;
}
function stitev(i)
{
if(i.ityp==6) return '';
var s=" onMouseOver='stitov(event,this,st_ms["+i.mei+"].ps["+i.ppi+"].is["+i.iti+"]);'";
s+=" onMouseOut='stitou(event,this,st_ms["+i.mei+"].ps["+i.ppi+"].is["+i.iti+"]);'";
s+=" onClick='stitck(event,this,st_ms["+i.mei+"].ps["+i.ppi+"].is["+i.iti+"]);'";
return s;
}
function stquo(n)
{
return "\""+n+"\"";
}
function stgurl(i)
{
return " HREF=" + stquo(i.iurl=="" ? "#" : i.iurl.replace(new RegExp("\"","g"),""")) + " TARGET=" + stquo(i.iurl==""||i.iurl.toLowerCase().indexOf('javascript:')==0 ? "_self" : i.itgt);
}
function stgdec(v)
{
if(v)
{
var s='';
if(v&1)
s+='underline ';
if(v&2)
s+='line-through ';
if(v&4)
s+='overline';
return s;
}
else
return 'none';
}
function stgimg(src,id,w,h,b)
{
var s='<IMG SRC=';
s+=stquo(src);
if(id)
s+=' ID='+id;
if(w>0)
s+=' WIDTH='+w;
else if(nNN)
s+=' WIDTH=0';
if(h>0)
s+=' HEIGHT='+h;
else if(nNN)
s+=' HEIGHT=0';
s+=' BORDER='+b+'>';
return s;
}
function stgbg(c,im,r)
{
var s=c;
if(im)
s+=" url("+im+") "+r;
return s;
}
function stgcur(i)
{
if(nNN6)
return "default";
return i.ityp!=6&&((i.ppi==0&&stgme(i).mcks&&stgsub(i))||i.iurl) ? "hand" : "default";
}
function stgiws(o)
{
if(stgpar(o).pver)
return stgpar(o).plmw>0 ? " WIDTH="+(stgpar(o).plmw+2) : "";
else
return o.iicw>0 ? " WIDTH="+(o.iicw+2) : "";
}
function stgaws(o)
{
if(stgpar(o).pver)
return stgpar(o).prmw>0 ? " WIDTH="+(stgpar(o).prmw+2) : "";
else
return o.iarw>0 ? " WIDTH="+(o.iarw+2) : "";
}
function stgme(ip)
{
return st_ms[ip.mei];
}
function stgpar(ip)
{
if(typeof(ip.iti)!="undefined")
return st_ms[ip.mei].ps[ip.ppi];
else
return !ip.par ? null : st_ms[ip.par[0]].ps[ip.par[1]].is[ip.par[2]];
}
function stgsub(i)
{
return !i.sub ? null : st_ms[i.sub[0]].ps[i.sub[1]];
}
function stgcl()
{
return parseInt(nNN||nOP ? window.pageXOffset : document.body.scrollLeft);
}
function stgct()
{
return parseInt(nNN||nOP ? window.pageYOffset : document.body.scrollTop);
}
function stgcw()
{
return parseInt(nNN||nOP ? window.innerWidth : (nIEW&&document.compatMode=="CSS1Compat" ? document.documentElement.clientWidth : document.body.clientWidth));
}
function stgch()
{
return parseInt(nNN||nOP ? window.innerHeight : (nIEW&&document.compatMode=="CSS1Compat" ? document.documentElement.clientHeight : document.body.clientHeight));
}
function stgobj(id,t)
{
if(nNN6)
return document.getElementById(id);
else if(nNN4)
return document.layers[id];
else
return t ? document.all.tags(t)[id] : document.all[id];
}
function stglay(ip)
{
if(!ip.layer)
{
if(typeof(ip.iti)=='undefined')
ip.layer=stgobj(ip.ids,st_ttb ? 'table' : 'div');
else
ip.layer=nNN4 ? stglay(stgpar(ip)).document.layers[0].document.layers[ip.ids] : stgobj(ip.ids,nIEW ? 'table' : null);
}
return ip.layer;
}
function stgstlay(i)
{
return stglay(i).document.layers[0].document.layers;
}
function stgrc(ip)
{
if(nNN4)
{
var ly=stglay(ip);
return [ly.pageX,ly.pageY,ly.clip.width,ly.clip.height];
}
else
{
var l=0,t=0;
var ly=stglay(ip);
var w=typeof(ip.rc)=="undefined"?parseInt(nOP&&nVER<7?ly.style.pixelWidth:ly.offsetWidth):ip.rc[2];
var h=typeof(ip.rc)=="undefined"?parseInt(nOP&&nVER<7?ly.style.pixelHeight:ly.offsetHeight):ip.rc[3];
while(ly)
{
l+=parseInt(ly.offsetLeft);
t+=parseInt(ly.offsetTop);
ly=ly.offsetParent;
}
if(nIEM)
{
l+=parseInt(document.body.leftMargin);
l-=ip.ipbw;
t-=ip.ipbw;
}
if(typeof(ip.iti)!='undefined')
{
if(st_delb)
{
l-=ip.ipbw;
t-=ip.ipbw;
}
if(st_addb)
{
l+=stgpar(ip).ipbw;
t+=stgpar(ip).ipbw;
}
}
return [l,t,w,h];
}
}
function stgxy(p)
{
var x=p.poffx;
var y=p.poffy;
var sr=stgrc(p);
p.rc=sr;
if(p.ppi==0)
{
if(stgme(p).mtyp==2)
return [stgme(p).mcox,stgme(p).mcoy];
else if(stgme(p).mtyp==1)
return [eval(stgme(p).mcox),eval(stgme(p).mcoy)];
else
return [sr[0],sr[1]];
}
var ir=stgirc(stgpar(p));
var cl=stgcl();
var ct=stgct();
var cr=cl+stgcw();
var cb=ct+stgch();
if(p.pdir==1)
x=p.poffx+ir[0]-sr[2]+p.psds;
else if(p.pdir==2)
x=p.poffx+ir[0]+ir[2]-p.psds;
else
x=p.poffx+ir[0]-p.psds;
if(x+sr[2]>cr)
x=cr-sr[2];
if(x<cl)
x=cl;
if(p.pdir==3)
y=p.poffy+ir[1]-sr[3]+p.psds;
else if(p.pdir==4)
y=p.poffy+ir[1]+ir[3]-p.psds;
else
y=p.poffy+ir[1]-p.psds;
if(y+sr[3]>cb)
y=cb-sr[3];
if(y<ct)
y=ct;
return [x,y];
}
function stbuf(s)
{
if(s)
{
var i=new Image();
st_ims[st_ims.length]=i;
i.src=s;
}
return s;
}
function stgsrc(s,m,f)
{
if(s=='')
return f ? m.mbnk : '';
var sr=s.toLowerCase();
if(sr.indexOf('http://')==0||(sr.indexOf(':')==1&&sr.charCodeAt(0)>96&&sr.charCodeAt(0)<123)||sr.indexOf('ftp://')==0||sr.indexOf('/')==0||sr.indexOf('gopher')==0)
return s;
else
return m.mweb+s;
}
function showFloatMenuAt(n,x,y)
{
if(nDM)
{
var m=stmenu(n);
if(m&&typeof(m.ready)!="undefined"&&m.mtyp==2&&m.ps.length&&!m.ps[0].issh)
{
ststxy(m,[x,y]);
stshow(m.ps[0]);
}
}
}
function hideMenu(n)
{
var m=stmenu(n);
var w=m.sfrm;
if(w!=window)
m=w.stmenu(n);
if(m.hdid)
{
w.clearTimeout(m.hdid);
m.hdid=null;
}
w.sthdall(m,1);
}
function stmenu(n)
{
for(var l=st_ms.length-1;l>=0;l--)
if(st_ms[l].mnam==n)
return st_ms[l];
return null;
}
function stgtsub(i)
{
var m=stgme(i);
var w=m.tfrm;
if(i.ppi||w==window)
return stgsub(i);
m=w.stmenu(m.mnam);
return w.stgsub(m.ps[i.ppi].is[i.iti]);
}
function stgirc(i)
{
var m=stgme(i);
var w=m.sfrm;
if(i.ppi||w==window)
return stgrc(i);
m=w.stmenu(m.mnam);
var rc=w.stgrc(m.ps[0].is[i.iti]);
var x=rc[0]-w.stgcl();
var y=rc[1]-w.stgct();
switch(m.mcfd)
{
case 0:y-=w.stgch();break;
case 1:y+=stgch();break;
case 2:x-=w.stgcw();break;
case 3:x+=stgcw();break;
}
x+=stgcl()+m.mcfx;
y+=stgct()+m.mcfy;
return [x,y,rc[2],rc[3]];
}
function stfrm(m)
{
var a=m.mcff.split(".");
var w="top";
for(var l=0;l<a.length-1;l++)
if(typeof(eval(w+"."+a[l]))=="undefined")
return 0;
w=eval("top."+m.mcff);
if(typeof(w.st_load)!="undefined"&&w.st_load)
{
var t=w.stmenu(m.mnam);
if(typeof(t)=="object")
{
if(w!=window)
{
if(t.mhdd<1000)
m.mhdd=t.mhdd=1000;
hideMenu(m.mnam);
m.sfrm=t.sfrm=window;
m.tfrm=t.tfrm=w;
}
m.mcff="";
return 1;
}
}
return 0;
} |
/**
* Created by hanwen on 30.05.14.
*/
'use strict';
var mongoose = require('mongoose');
//var fsHandle = require('fs');
var constructObj, readObj, updateObj, destroyObj;
constructObj = function(obj_type, obj_map, callback){
var newObj = new obj_type(obj_map);
newObj.save(function(err, result_map){
if(err){
console.warn(err.name);
console.dir(err.error);
}
console.log('successful add the object'+ result_map);
callback(result_map);// send back the object
});
};
readObj = function(obj_type, find_map, fields_map, callback){
var newObj = new obj_type(obj_map);
newObj.save(function(err, result_map){
if(err){
console.warn(err.name);
console.dir(err.error);
}
console.log('successful add the object'+ result_map);
callback(result_map);// send back the object
});
};
updateObj = function(obj_type, obj_map, callback){
var newObj = new obj_type(obj_map);
newObj.save(function(err, result_map){
if(err){
console.warn(err.name);
console.dir(err.error);
}
console.log('successful add the object'+ result_map);
callback(result_map);// send back the object
});
};
destroyObj = function(obj_type, obj_map, callback){
var newObj = new obj_type(obj_map);
newObj.save(function(err, result_map){
if(err){
console.warn(err.name);
console.dir(err.error);
}
console.log('successful add the object'+ result_map);
callback(result_map);// send back the object
});
};
module.exports = {
create : constructObj,
read : readObj,
update : updateObj,
delete : destroyObj
}; |
var AjaxActionTypes = {
Null: -1,
DeleteFile: 1,
SaveRolePermission: 2,
ClearAuditSession: 3,
SaveUserPermission: 4,
SaveReplacedProductAsset: 5
}
var EOwnerTypes = {
Company: 1,
Supplier: 2,
Client: 3,
Producer: 4,
Product: 5
}
//订单类型
var ESaleOrderTypes = {
DaBaoMode: 1,
AttractBusinessMode: 2,
AttachedMode: 3
};
//收款方式
var EPaymentMethods = {
BankTransfer: 1,
Deduction: 2
};
//导入数据类型
var EImportDataTypes = {
DCFlowData: 1,
DCInventoryData: 2,
ProcureOrderData: 3
};
|
'use strict'
const snapshot = require('snap-shot-it')
const la = require('lazy-ass')
const is = require('check-more-types')
/* eslint-env mocha */
describe('isColonSeparated', () => {
const { isColonSeparated } = require('./utils')
it('checks for dashes and underscores', () => {
snapshot(
isColonSeparated,
// true
'foo',
'foo:bar',
// false
'foo-bar',
'fooBar',
'foo_bar',
'_foo',
'FOO'
)
})
})
describe('verifyColonSeparated', () => {
const { verifyColonSeparated } = require('./utils')
it('checks empty list', () => {
verifyColonSeparated([])
})
it('checks single string', () => {
verifyColonSeparated(['foo'])
})
it('checks two strings', () => {
verifyColonSeparated(['foo', 'test:foo'])
})
it('throws on dashes', () => {
la(
is.raises(
() => {
verifyColonSeparated(['foo', 'test-foo'])
},
e => {
snapshot(e.message)
return true
}
)
)
})
})
|
var React = require('react');
var connect = require('react-redux').connect;
var DashboardMenu = require('./DashboardMenu');
var DashboardPageLayout = require('./DashboardPageLayout');
var router = require('react-router');
var Router = router.Router;
var Route = router.Route;
var IndexRoute = router.IndexRoute;
var withRouter = router.withRouter;
var Link = router.Link;
var actions = require('./actions');
var PageStats = React.createClass({
_createChart: function() {
Circles.create({
id: 'angular2-satisfaction-circle',
radius: 70,
value: this.props.angular2Satisfaction,
maxValue: 100,
width: 10,
text: function(value){return value + '%';},
colors: ['black', 'red']
});
Circles.create({
id: 'angular2-interest-circle',
radius: 70,
value: this.props.angular2Interest,
maxValue: 100,
width: 10,
text: function(value){return value + '%';},
colors: ['black', 'firebrick']
});
Circles.create({
id: 'angular-satisfaction-circle',
radius: 70,
value: this.props.angularSatisfaction,
maxValue: 100,
width: 10,
text: function(value){return value + '%';},
colors: ['black', 'mediumvioletred']
});
Circles.create({
id: 'angular-interest-circle',
radius: 70,
value: this.props.angularInterest,
maxValue: 100,
width: 10,
text: function(value){return value + '%';},
colors: ['black', 'palevioletred']
});
Circles.create({
id: 'ember-satisfaction-circle',
radius: 70,
value: this.props.emberSatisfaction,
maxValue: 100,
width: 10,
text: function(value){return value + '%';},
colors: ['black', 'orange']
});
Circles.create({
id: 'ember-interest-circle',
radius: 70,
value: this.props.emberInterest,
maxValue: 100,
width: 10,
text: function(value){return value + '%';},
colors: ['black', 'coral']
});
Circles.create({
id: 'react-satisfaction-circle',
radius: 70,
value: this.props.reactSatisfaction,
maxValue: 100,
width: 10,
text: function(value){return value + '%';},
colors: ['black', 'blue']
});
Circles.create({
id: 'react-interest-circle',
radius: 70,
value: this.props.reactInterest,
maxValue: 100,
width: 10,
text: function(value){return value + '%';},
colors: ['black', 'steelblue']
});
},
componentDidMount() {
this.props.dispatch(actions.fetchData());
this._createChart();
console.log(this.props);
},
render: function() {
this._createChart();
return (
<div>
<h4 className="column center">State of JavaScript 2016: {this.props.name}</h4>
<div className="segment">
<div className="flex">
<div className="half column stat">
<h6>Interested in using {this.props.name}?</h6>
<div className="circle" id={this.props.id + '-interest-circle'}></div>
</div>
<div className="half column stat">
<h6>Used {this.props.name} and would use it again?</h6>
<div className="circle" id={this.props.id + '-satisfaction-circle'}></div>
</div>
</div>
</div>
<div className="segment">
<div className="two thirds column left">
<h3>What People Are Saying</h3>
{/*<Feed />*/}
</div>
<div className="one third column right">
<h3>Latest News</h3>
<dl className="news">
<dt>
<a href="#">How to combine Angular 2, React and Aurelia just because.</a>
</dt>
<dd>
Posted on November 3, 2016
</dd>
<dt>
<a href="#">Is it too soon for React 2?</a>
</dt>
<dd>
Posted on November 2, 2016
</dd>
<dt>
<a href="#">Why Aurelia is about to bring Meteor crashing down.</a>
</dt>
<dd>
Posted on October 29, 2016
</dd>
</dl>
</div>
</div>
</div>
);
}
})
var mapStateToProps = function(state, props) {
return {
angular2Interest: state.angular2Interest,
angular2NotInterested: state.angular2NotInterested,
angular2Satisfaction: state.angular2Satisfaction,
angular2NotSatisfied: state.angular2NotSatisfied,
reactInterest: state.reactInterest,
reactNotInterested: state.reactNotInterested,
reactSatisfaction: state.reactSatisfaction,
reactNotSatisfied: state.reactNotSatisfied,
emberInterest: state.emberInterest,
emberNotInterested: state.emberNotInterested,
emberSatisfaction: state.emberSatisfaction,
emberNotSatisfied: state.emberNotSatisfied,
angularInterest: state.angularInterest,
angularNotInterested: state.angularNotInterested,
angularSatisfaction: state.angularSatisfaction,
angularNotSatisfied: state.angularNotSatisfied
};
};
var Container = connect(mapStateToProps) (withRouter(PageStats));
module.exports = Container;
|
import React, {useState} from 'react'
import Description from './Description/Description'
import Compra from './Compra/Compra'
import style from './Panel.module.css'
function Panel() {
const [compra, setCompra] = useState(false)
const redirectToDescription = ()=>{
setCompra(false)
}
const redirectToCompra = ()=>{
setCompra(true)
}
return (
<div className={`${style.panel} !important`}>
<h3 className={style.title}>INFORMACION BASICA DE PARCELA</h3>
{compra? <Compra redirectToDescription={redirectToDescription} /> : <Description redirectToCompra={redirectToCompra} /> }
</div>
)
}
export default Panel
|
//引入数据库
const mongoose = require('mongoose');
//链接数据库
mongoose.connect('mongodb://localhost/kuazhu',{useUnifiedTopology: true,useNewUrlParser: true });
const db = mongoose.connection;
db.on('err',function(err){
console.log(err);
throw err;
})
db.once('open',function(){
console.log('connect success..');
//1.定义文档模型
const userSchema = new mongoose.Schema({
name:String,
age:Number,
major:String
})
//2.根据文档模型生成对应模型(集合),也是一个类
//第一个参数是需要生成的集合名称,第二个参数是需要用到的文档模型
const userModle = mongoose.model('user',userSchema)
//3.根据模型(集合)进行数据库操作
//查询
//find方法返回的query
//filte:就是条件
//[projection]:就是让谁显示,写出谁,如果不想让显示,前面加上-
//[options]:限制条件
/*
userModle.find({age:{$lt:20}},null,{limit:3},(err,docs) =>{
if(err){
console.log(err)
}else{
console.log(docs)
}
})
*/
/*//更新一条
userModle.updateOne({age:{$lt:20}},{$set:{age:22}},(err,docs)=>{
if(err){
console.log(err)
}else{
console.log(docs)
}
})*/
//updateMany不要更新更新操作符也能更新
userModle.updateMany({age:{$lt:20}},{age:22},(err,docs)=>{
if(err){
console.log(err)
}else{
console.log(docs)
}
})
}) |
import React from "react";
import _ from "lodash";
import {
StyleSheet,
View,
ScrollView,
Text,
Picker,
TouchableOpacity
} from "react-native";
import * as helper from "../../utils/helper";
import * as Rules from "../../components/CalculationRules";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isResultLoaded: false,
showPicker: false,
selectedBusName: null,
selectedBusInfo: {},
calculationDetails: {},
busInfo: []
};
}
componentDidMount = async () => {
const busInfo = await helper.fetchBusesInfo();
this.setState({
busInfo,
isResultLoaded: true
});
};
renderPickerItems = () => {
return this.state.busInfo.map((bus, idx) => (
<Picker.Item
key={idx}
label={bus.Bus_ID__c}
value={bus.Bus_ID__c}
/>
));
};
renderPicker = () => (
<View style={styles.pickerStyle}>
<Picker
itemStyle={{ fontSize: 22 }}
selectedValue={this.state.selectedBusName}
onValueChange={(itemValue, itemIndex) => {
const selectedBusInfo = this.state.busInfo[itemIndex];
this.setState(
{
selectedBusName: itemValue,
selectedBusInfo,
showPicker: false
},
() => {
const calculationDetails = helper.calculateResaleValue(
selectedBusInfo
);
this.setState({ calculationDetails });
}
);
}}
>
{this.renderPickerItems()}
</Picker>
</View>
);
renderCalculationDetails = () => {
const { resaleValue } = this.state.calculationDetails;
if (!resaleValue) return null;
return (
<View style={styles.DetailViewContainer}>
<Text style={styles.DetailTitleStyle}>
Resale value of the bus{" "}
{this.state.selectedBusInfo.Bus_ID__c} is calculated as
follow:
</Text>
<View style={{ margin: 5, borderWidth: 1 }}>
<View style={styles.DetailContainer}>
<Text style={styles.DetailTextStyle}>
Number of Seats:
</Text>
<Text style={styles.DetailTextStyle}>
{this.state.selectedBusInfo.Maximum_Capacity__c}
</Text>
</View>
<View style={styles.DetailContainer}>
<Text style={styles.DetailTextStyle}>
Starting selling price of{" "}
{this.state.selectedBusInfo.Maximum_Capacity__c}{" "}
seater bus is :
</Text>
<Text style={styles.DetailTextStyle}>
{this.state.calculationDetails.priceBasedOnSeats}
</Text>
</View>
</View>
<View style={{ margin: 5, borderWidth: 1 }}>
<View style={styles.DetailContainer}>
<Text style={styles.DetailTextStyle}>
Odometer reading:
</Text>
<Text style={styles.DetailTextStyle}>
{this.state.selectedBusInfo.Odometer_Reading__c}
</Text>
</View>
<View style={styles.DetailContainer}>
<Text style={styles.DetailTextStyle}>
Discount for every mile over 100,000 :
</Text>
<Text style={styles.DetailTextStyle}>
{this.state.calculationDetails.discount}
</Text>
</View>
</View>
<View style={{ margin: 5, borderWidth: 1 }}>
<View style={styles.DetailContainer}>
<Text style={styles.DetailTextStyle}>
Does bus have air conditioning system:
</Text>
<Text style={styles.DetailTextStyle}>
{this.state.selectedBusInfo.Has_Air_Conditioning__c
? "Yes"
: "No"}
</Text>
</View>
<View style={styles.DetailContainer}>
<Text style={styles.DetailTextStyle}>
Extra charge of air conditioning system :
</Text>
<Text style={styles.DetailTextStyle}>
{this.state.calculationDetails.pricebasedOnFeature}
</Text>
</View>
</View>
<View style={{ margin: 5, borderWidth: 1 }}>
<View style={styles.DetailContainer}>
<Text style={styles.DetailTextStyle}>
Bus manufacturing year:
</Text>
<Text style={styles.DetailTextStyle}>
{this.state.selectedBusInfo.Year__c}
</Text>
</View>
<View style={styles.DetailContainer}>
<Text style={styles.DetailTextStyle}>
Extra price if the bus year is 1972 or older :
</Text>
<Text style={styles.DetailTextStyle}>
{this.state.calculationDetails.priceBasedOnYear}
</Text>
</View>
</View>
{Rules.printCulculationRules()}
</View>
);
};
renderContainer = () => (
<ScrollView style={styles.Container}>
<View style={styles.HeaderContainer}>
<Text style={styles.AppTitleStyle}>Fleet Management</Text>
</View>
<View style={styles.MainContainer}>
<View style={styles.FilterContainer}>
<TouchableOpacity
style={styles.button}
onPress={() =>
this.setState({
showPicker: !this.state.showPicker
})
}
>
<View
style={{
flexDirection: "row",
justifyContent: "space-between"
}}
>
<Text style={styles.TitleStyle}>
{this.state.selectedBusName
? "Bus: "
: "Please Select Bus"}
</Text>
<Text style={styles.TitleStyle}>
{this.state.selectedBusName
? this.state.selectedBusName
: ""}
</Text>
</View>
</TouchableOpacity>
{this.state.showPicker && this.renderPicker()}
</View>
<View style={styles.seperator} />
<View style={styles.ResultContainer}>
<Text style={styles.TitleStyle}>Resale Value:</Text>
<Text style={styles.TitleStyle}>
${this.state.calculationDetails.resaleValue > 0
? this.state.calculationDetails.resaleValue
: 0}
</Text>
</View>
</View>
{this.renderCalculationDetails()}
</ScrollView>
);
render() {
return this.state.isResultLoaded ? this.renderContainer() : null;
}
}
const styles = StyleSheet.create({
Container: {
flex: 1,
margin: 4,
marginTop: 25
},
HeaderContainer: {
flexDirection: "row",
justifyContent: "center",
alignItems: "flex-start",
padding: 4,
margin: 1
},
AppTitleStyle: {
padding: 4,
margin: 1,
fontSize: 28,
fontWeight: "700"
},
MainContainer: {
padding: 4,
margin: 1
},
FilterContainer: {
padding: 4,
margin: 1,
borderWidth: 1
},
seperator: {
margin: 5
},
ResultContainer: {
flexDirection: "row",
justifyContent: "space-between",
padding: 4,
margin: 1,
borderWidth: 1
},
DetailViewContainer: {
marginTop: 10,
marginLeft: 10,
marginBottom: 10
},
DetailContainer: {
flexDirection: "row",
justifyContent: "space-between",
padding: 4,
margin: 1
},
DetailTitleStyle: {
fontSize: 16
},
DetailTextStyle: {
fontSize: 14
},
TitleStyle: {
fontSize: 22,
fontWeight: "600"
}
});
|
var member=new Vue({
el:"#member",
data:{
updateuser:{"id":0,"username":"","name":"","pwd":"","email":"","tel":"","date":""},
user:{"id":0,"username":"","name":"","pwd":"","email":"","tel":"","date":""},
users:[],
standbyusers:[]
},
mounted:function(){
this.$nextTick(function () {
this.init();
})
},
methods:{
init:function () {
var _this=this;
this.$http.get("http://localhost:8088/music/member").then(function (res) {
_this.users=res.data;
_this.standbyusers=res.data;
})
},
addUser:function () {
//$("#li_signup").attr("style", "display:none");
//var username = $("#signup_username").val();
var password = $("#signup_password").val();
var password2 = $("#signup_password2").val();
// if(password!=password2){
// confirm("密码输入不一致");
// }
//$("#li_span_signin").text(username).off('click', '**');
//$("#li_signout").attr("style", "display:inline");
//confirm("11111111111");
if(this.user.username==""||this.user.name==""||this.user.pwd==""||this.user.tel==""||this.user.email==""||this.user.pwd==""){
confirm("输入内容不能为空!");
// this.user={"id":0,"username":"","name":"","pwd":"","email":"","tel":"","date":""};
}else if(password!=password2){
confirm("密码输入不一致");
}else
{
var localdate=new Date();
var newTime = localdate.toLocaleString(); //把日期转换成2018/6/4 下午10:45:19 格式
var arr = newTime.split(" "); //把2018/6/4提取出来
var arr2 = arr[0].split('/');
var resultedate=arr2[0]+'年'+arr2[1]+'月'+arr2[2]+'日';
this.user.date=resultedate;
// this.users.push(this.user);
// this.user={"id":0,"username":"","name":"","pwd":"","email":"","tel":"","date":""};
// $("#signup").fadeOut();
// $("div.modal-backdrop.fade.in").fadeOut();
var _this=this;
this.$http.post("http://localhost:8088/music/member",this.user).then(function (res) {
_this.users.push(_this.user);
_this.user={"id":0,"username":"","name":"","pwd":"","email":"","tel":"","date":""};
$("#signup").fadeOut();
$("div.modal-backdrop.fade.in").fadeOut();
})
}
},
login:function(){
var username = $("#signin_username").val();
var password = $("#signin_password").val();
var tab=this.users;
var name=0;
var pwd=0;
for(i in tab){
if(tab[i].username==username){
name=1;
if(tab[i].pwd==password){
pwd=1;
}
}
}
if(name==0){
confirm("对不起...暂无用户信息");
$("#signin").fadeOut();
$("div.modal-backdrop.fade.in").fadeOut();
}else if(pwd==0){
confirm("密码错误!");
$("#signin").fadeOut();
$("div.modal-backdrop.fade.in").fadeOut();
}else {
sessionStorage.setItem("lastname",username);
$("#li_signup").attr("style", "display:none");
$("#signin").fadeOut();
$("div.modal-backdrop.fade.in").fadeOut();
$("#li_span_signin").text(username).off('click', '**');
$("#li_signout").attr("style", "display:inline");
}
},
removeUser:function (data) {
if(confirm("确定要删除吗?")){
// var index=this.users.indexOf(data);
// this.users.splice(index,1);
var _this=this;
this.$http.delete("http://localhost:8088/music/member/"+data.id).then(function (res) {
if(res.data>0){
var index=_this.users.indexOf(data);
_this.users.splice(index,1);
}
})
}else{
return;
}
},
updateUser:function (data){
index=this.users.indexOf(data);
this.updateuser.id=data.id;
this.updateuser.username=data.username;
this.updateuser.name=data.name;
this.updateuser.pwd=data.pwd;
this.updateuser.email=data.email;
this.updateuser.tel=data.tel;
this.updateuser.date=data.date;
//this.updatemusiclist=JSON.stringify(data);
// var index=
// this.musiclists.splice(index,1);
},
update:function () {
// this.users.splice(index,1,this.updateuser);
// this.updateuser={"id":0,"username":"","name":"","pwd":"","email":"","tel":"","date":""};
// confirm(this.musiclists.findIndex(index));
var _this=this;
// this.$http.post("http://localhost:8088/music/musiclist/"+this.updatemusic.id,this.updatemusic,{emulateJSON:true}).then(function (res) {
this.$http.post("http://localhost:8088/music/member/"+this.updateuser.id,this.updateuser).then(function (res) {
if(res.data>0){
_this.users.splice(index,1,this.updateuser);
_this.updateuser={"id":0,"username":"","name":"","pwd":"","email":"","tel":"","date":""};
}
})
},
setMusics(arr){
this.users=JSON.parse(JSON.stringify(arr));
//confirm(JSON.stringify(this.musics));
},
search(e){
var key=e.target.value;
var _this=this;
//每次给的都是整套数据
var tab=this.standbyusers;
//confirm(v+"11");
if(key){
//将筛选后的数据放到ss中
var ss=[];
//遍历歌曲列表
for (i in tab){
//判断歌曲名是否含有输入值
if(tab[i].name.indexOf(key)>-1){
ss.push(tab[i]);
}
//判断歌手名是否含有输入值
if(tab[i].tel.indexOf(key)>-1){
ss.push(tab[i]);
}
}
//confirm("sssss"+JSON.stringify(ss));
this.setMusics(ss);
}else{
//输入框为空时把备用数据发送过去
this.setMusics(this.standbyusers);
}
}
}
}) |
appExcel.directive('ngFiles', ['$parse', function ($parse) {
function fn_link(scope, element, attrs) {
var onChange = $parse(attrs.ngFiles);
element.on('change', function (eve) {
onChange(scope, { $files: eve.target.files });
})
};
return {link: fn_link};
}]);
// appExcel.directive()
|
ig.module(
'game.entities.abilities.fireball-caster'
)
.requires(
'game.entities.abilities.fireball',
'plusplus.abilities.ability-shoot',
'impact.sound',
'plusplus.entities.explosion'
)
.defines(function () {
ig.FireballCaster = ig.AbilityShoot.extend({
spawningEntity: ig.Fireball,
offsetVelX: 400,
offsetVelY: 400,
// Nothing is free
costActivate: 5,
castSound: new ig.Sound(ig.CONFIG.PATH_TO_SOUNDS + 'fireball-cast.*'),
/**
* Play a sound when casting, and ensure the fireball goes somewhere
* if the player is standing still
*/
activate: function (settings) {
this.castSound.play();
var projectile = this.parent(settings);
if (projectile.vel.x === 0 && projectile.vel.y === 0) {
if (this.entity.facing.x !== 0) {
projectile.vel.x = this.entity.facing.x > 0 ? this.offsetVelX : -this.offsetVelX;
} else if (this.entity.facing.y !== 0) {
projectile.vel.y = this.entity.facing.y > 0 ? this.offsetVelY : -this.offsetVelY;
}
}
}
});
}); |
'use strict';
/**
* @ngdoc function
* @name findteacherApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the findteacherApp
*/
angular.module('app').controller('MainCtrl', function($scope, $http ,$location, Data, Server, localStorageService) {
Data.header = "找老师";
Data.goback = false;
// var hot = [];
var hot_idx = 0;
var hot_each = 8;
var late = localStorageService.get('late');
$scope.late = late && late.split('\n') || [];
$scope.lately = $scope.late.length > 0;
$scope.replace = true;
$scope.data = Data;
$scope.data.key = '';
// 点击“换一批”时更新数据
$scope.updateHot = function() {
$scope.hot = Data.hot.slice(hot_idx * hot_each, (hot_idx + 1) * hot_each);
hot_idx++;
hot_idx = Data.hot.length > hot_idx * hot_each ? hot_idx:0;
}
// 点击“清除” 清除本地数据
$scope.cleanUp = function() {
$scope.lately = false;
localStorageService.add('late', '');
}
// 搜索
$scope.search =function(key){
Data.key = key;
Server.search();
$location.path('/list');
}
// 异步取热门搜索
if(Data.hot){
$scope.updateHot();
}else{
Server.getHot(function(json){
Data.hot = json;
$scope.updateHot();
})
}
}); |
import React from 'react';
/* Props Components For Tutorial */
// import ContactCard from './Props Tutorial/ContactCard';
/* Prop-styling Practice Puncline Joke Activity */
// import Joke from './Props and Styling Practice/props-styling-practice';
/* Mapping Components Practice One */
// import QandAData from './Mapping Components Practice/QuestionAndAnswer/question-answer';
// import QuestionandAnswer from './Mapping Components Practice/QuestionAndAnswer/QandA';
/* Mapping Components Practice Two */
// import SchoolProductData from './Mapping Components Practice/School Product/SchoolProductData';
// import SchoolProduct from './Mapping Components Practice/School Product/SchoolProduct'
const App = () => {
//This is Mapping Components Practice One
/*
const QandAComponents = QandAData.map((QandA) => {
return (
<QuestionandAnswer
key={QandA.id}
question={QandA.question}
answer={QandA.answer}
/>
)
})
*/
//This is Mapping Components Practice Two
/*
const SchoolProductComponents = SchoolProductData.map((product) => {
return (
<SchoolProduct
key={product.id}
name={product.name}
price={product.price}
description={product.description}
/>
)
})
*/
return (
<main className="main container">
{ /* TODOLIST CRASH COURSE */}
{/* <TodoApp /> */}
{/* <ContactCard
contact={{
name: "Kitten One",
imgUrl: "http://placekitten.com/200/300",
phone: "0123-123-1234",
email: "kittinOne21@gmail.com"
}} />
<ContactCard
contact={{
name: "Kitten Two",
imgUrl: "https://placekitten.com/g/200/300",
phone: "0123-123-1234",
email: "kittenTwo21@gmail.com"
}}
/>
<ContactCard
contact={{
name: "Kitten Three",
imgUrl: "https://placekitten.com/g/200/300",
phone: "0123-123-1234",
email: "kittenThree21@gmail.com"
}}
/>
<ContactCard
contact={{
name: "Kitten Four",
imgUrl: "http://placekitten.com/200/300",
phone: "0123-123-1234",
email: "kittinFour21@gmail.com"
}}
/> */}
{/* Props and Styling Practice */}
{/* <Joke
question={{
imgPunchline: "https://th.bing.com/th/id/OIP.5JDg0pdTYjZgXIZq5N7rGAHaLH?pid=Api&rs=1",
propsQuestion: "You know why the old lady fell down the well?",
punchLine: "She didn't see that well!"
}}
/>
<Joke
question={{
imgPunchline: "https://memegenerator.net/img/images/5170470.jpg",
propsQuestion: "What do you call a dead fly?",
punchLine: "A flew!"
}}
/>
<Joke
question={{
imgPunchline: "https://memegenerator.net/img/images/300x300/9848987/meme-doge.jpg",
propsQuestion: "Once, i told a chemistry joke",
punchLine: "There was no reaction!"
}}
/>
<Joke
question={{
imgPunchline: "https://memegenerator.net/img/images/6224248/high-llama.jpg",
propsQuestion: "When you check you bank account",
punchLine: "The day after christmas!"
}}
/>
<Joke
question={{
imgPunchline: "https://th.bing.com/th/id/OIP.GwZAIBmBSsP7zuKvly6HDQAAAA?pid=Api&rs=1",
propsQuestion: "When the patient tells you ",
punchLine: "They haven't pooped in 13 days!"
}}
/> */}
{/* Mapping Components Practice One */}
{/* <QandA /> */}
{/* <div className="QandACards container">
{QandAComponents}
</div> */}
{/* Mapping Components Practice Two */}
{/* <div className="school-products-container">
<div className="school-products row">
{SchoolProductComponents}
</div>
</div> */}
{/* Class Base Components Course */}
</main>
)
}
export default App; |
const TwingNodeExpressionConstant = require('../../../../../../../lib/twing/node/expression/constant').TwingNodeExpressionConstant;
const TwingTestMockCompiler = require('../../../../../../mock/compiler');
const TwingNodeExpressionUnaryPos = require('../../../../../../../lib/twing/node/expression/unary/pos').TwingNodeExpressionUnaryPos;
const TwingNodeType = require('../../../../../../../lib/twing/node').TwingNodeType;
const tap = require('tap');
tap.test('node/expression/unary/pos', function (test) {
test.test('constructor', function (test) {
let expr = new TwingNodeExpressionConstant(1, 1);
let node = new TwingNodeExpressionUnaryPos(expr, 1);
test.same(node.getNode('node'), expr);
test.same(node.getType(), TwingNodeType.EXPRESSION_UNARY_POS);
test.end();
});
test.test('compile', function (test) {
let compiler = new TwingTestMockCompiler();
let expr = new TwingNodeExpressionConstant(1, 1);
let node = new TwingNodeExpressionUnaryPos(expr, 1);
test.same(compiler.compile(node).getSource(), ' +1');
test.end();
});
test.end();
});
|
function runTest()
{
FBTest.openNewTab(basePath + "console/2914/issue2914.html", function(win)
{
FBTest.openFirebug(function()
{
FBTest.enablePanels(["console", "script"], function()
{
FBTest.reload(function()
{
var panelNode = FBTest.getSelectedPanel().panelNode;
var errorNode = panelNode.querySelector(".objectBox.objectBox-errorMessage");
var titleNode = errorNode.querySelector(".errorTitle");
// Verify the error message
FBTest.compare(titleNode.textContent, "iframe error",
"An error message must be displayed");
// The expandable button must be displayed.
FBTest.ok(FW.FBL.hasClass(errorNode, "hasTwisty"),
"The error must be expandable.");
// Open stack trace info.
FBTest.click(titleNode);
// Verify stack trace.
var traceNode = errorNode.querySelector(".errorTrace");
FBTest.compare(
"logError()" + FW.FBL.$STRF("Line", ["issue2...me.html", 11]) +
"issue2914-innerFrame.html()" + FW.FBL.$STRF("Line", ["issue2...me.html", 13]),
traceNode.textContent,
"The stack trace must be properly displayed.");
FBTest.testDone();
});
});
});
});
}
|
// 文字列の左を0埋めする
var paddingZeroLeft = function(str, length) {
str = "" + str;
while (str.length < length) {
str = "0" + str;
}
return str;
}
// 日付の文字列を返す(YYYY/MM/DD)
var getDateString = function(date) {
var year = date.getFullYear();
var month = paddingZeroLeft((date.getMonth() + 1), 2);
var date = paddingZeroLeft(date.getDate(), 2);
return year + "/" + month + "/" + date;
}
// 時刻の文字列を返す(HH:mm:ss)
var getTimeString = function(date) {
var hour = date.getHours();
var minute = paddingZeroLeft(date.getMinutes(), 2);
var second = paddingZeroLeft(date.getSeconds(), 2);
return hour + ":" + minute + ":" + second;
}
// <audio>の音源を鳴らす
// <audio>のidを渡す
var audioPlay = function(audioObj) {
var isPlaing = false;
return function() {
if (!isPlaing) {
isPlaing = true;
audioObj.pause();
audioObj.currentTime = 0;
audioObj.play();
audioObj.addEventListener("ended", function() {
isPlaing = false;
}, false);
}
}
}
|
import React, { Component } from 'react';
import Select from 'react-select';
import StopsContainer from '../containers/StopsContainer';
import ResetButton from '../helpers/reset';
export default class HomePage extends Component {
state = {
route: {},
invalidEntry: "invalidEntry__hide"
};
displayInvalidEntry = () => {
this.setState({
invalidEntry: "invalidEntry__show invalidEntry__show--home"
})
}
hideInvalidEntry = () => {
this.setState({
invalidEntry: "invalidEntry__hide"
})
}
selectRoute = (event) => {
event.preventDefault();
let selectedRoute = event.target.routeList.value;
if (selectedRoute === event.target.routeList.placeholder) {
this.displayInvalidEntry();
} else {
this.setState({
route: selectedRoute
});
}
}
render() {
if (!this.props.routes || Object.keys(this.props.routes).length === 0) {
return (
<div>
<h3> Loading... </h3>
</div>
);
} else {
return (
<>
<div className='home__prompt'>Please select your bus route:</div>
<form onSubmit={this.selectRoute}>
<RouteDropdown routes={this.props.routes} />
<div className='buttons'>
<button type='submit' className='buttons__selectButton'>Select</button>
<button type='button' onClick={ResetButton} className='buttons__resetButton'>Cancel</button>
</div>
<div className={`${this.state.invalidEntry}`}>
<div>
<div>Please choose a valid route.</div>
<button type='button' onClick={this.hideInvalidEntry} className='invalidEntry__close'>Close</button>
</div>
</div>
</form>
<StopsContainer route={this.state.route} />
</>
);
};
}
}
function RouteDropdown(props) {
const routeDropdownArray = props.routes
if (Object.keys(routeDropdownArray).length === 0) return <div>Loading...</div>
const routeDropdown = routeDropdownArray.map((route) => {
return { label: route.route, value: route.id }
})
return (
<Select name='routeList' placeholder='Select your route' defaultValue='Select your route' options={routeDropdown} />
)
} |
import React, { memo } from 'react'
export default memo(function CMFriends() {
return (
<div>
<h2>CMFriends</h2>
</div>
)
})
|
import React from 'react';
import { AppRegistry, AppState, Platform, View, StyleSheet } from 'react-native';
import { AppLoading } from 'expo';
import * as firebase from "firebase";
import TabNavigation from './src/navigation/TabNavigation/TabNavigation';
import StackNavigation from './src/navigation/StackNavigation/StackNavigation';
import StatusBarBackground from './src/subcomponents/StatusBarBackground/StatusBarBackground';
import Colours from './src/utils/Colours';
export default class App extends React.Component {
state = {
loggedIn : false,
isReady : false,
appState : AppState.currentState,
statusBarColour : Colours.HEX_COLOURS.SOFT_BLUE
};
static pauseFuncs = [];
static resumeFuncs = [];
async componentWillMount () {
firebase.auth ().onAuthStateChanged ( user =>
this.setState (
{
loggedIn : user,
statusBarColour : user ? Colours.HEX_COLOURS.DARK_WHITE : Colours.HEX_COLOURS.SOFT_BLUE
}
)
);
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
App.resumeFuncs.map ( func =>
{
func ();
}
)
} else {
console.log('App has gone to the background!')
App.pauseFuncs.map ( func =>
{
func ();
}
)
}
this.setState (
{
appState: nextAppState
}
);
}
static addPauseFunction (func) {
App.pauseFuncs.push (func);
}
static addResumeFunction (func) {
App.resumeFuncs.push (func);
}
static emptyPauseFunctions () {
App.pauseFuncs = [];
}
static emptyResumeFunctions () {
App.resumeFuncs = [];
}
render() {
if (this.state.isReady)
return (
<View style = { styles.container }>
<StatusBarBackground style = {
{
backgroundColor : this.state.statusBarColour
}
} />
{ this.state.loggedIn ? <TabNavigation /> : <StackNavigation /> }
</View>
);
else
return (
<AppLoading
startAsync = { () => {} }
onFinish = { () => {
this.setState (
{
isReady : true
}
)
}
}
onError = { (error) => {
console.warn (error)
}
} />
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff'
},
})
AppRegistry.registerComponent ('App', () => App); |
import axios from 'axios';
const API_URL = 'https://api.giphy.com/v1/gifs/search?';
const API_KEY = '2avmiOWGNza4KPBO2fsDSt5oHN8vR168';
export function fetchPics(inputVal, page) {
const RESULT_URL = `${API_URL}api_key=${API_KEY}&q=${inputVal.toLowerCase()}&limit=15&offset=${page}&rating=PG&lang=en`;
return axios.get(RESULT_URL).then(response => response.data.data);
}
const BACKEND_URL = 'http://localhost:3113';
export function fetchCurrentUser() {
const RESULT_URL = `${BACKEND_URL}/auth/current`;
return axios.get(RESULT_URL).then(response => response.data.user);
}
export function likePhoto(userId, url) {
const RESULT_URL = `${BACKEND_URL}/like`;
console.log(userId);
return axios
.post(RESULT_URL, { data: { userId, likeItemUrl: url } })
.then(response => console.log(response.data))
.catch(err => console.log(err));
}
|
const loginFields = require('../config/user').loginFields;
const User = require('../models').User;
exports.validateLogin = (req, res, next) => {
req.check(loginFields);
req.getValidationResult();
// const errors = req.validationResult();
var errors = req.validationErrors();
if (errors) {
req.flash('error', errors);
res.redirect(req.header('Referer') || '/account');
} else {
next();
}
}
exports.check = (req, res, next) => {
if (!req.isAuthenticated || !req.isAuthenticated()) {
let url = '/login?clientId=' + req.client.clientId;
if (req.query.redirect_uri) {
url = url + '&redirect_uri=' + encodeURIComponent(req.query.redirect_uri);
}
if (req.session) {
req.session.returnTo = req.originalUrl || req.url;
}
return res.redirect(url);
} else {
new User({ id: req.user.id })
.fetch()
.then((user) => {
req.userModel = user;
req.user = user.serialize();
next();
})
.catch((err) => {
next(err);
});
}
}
exports.passwordValidate = (req, res, next) => {
if (req.body.password.length >= 8) {
next();
} else {
req.flash('error', {msg: 'Wachtwoord moet min 8 karakters lang zijn'});
res.redirect(req.header('Referer') || '/account');
}
}
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const AnswerSchema = new Schema({
answerCorrect: { type: String, max: 300, required: true },
answerOption: [{ type: String, max: 300, required: true }],
});
module.exports = mongoose.model('Answer', AnswerSchema);
|
// optional chaining
`use strict`;
const tox = ["Jan", "feb", "march", "april"];
const pot = {
[tox[0]]: {
open: "9 AM",
close: "10 PM"
},
[tox[1]]: {
open: "10 AM",
close: "9 PM"
}
};
const restorant = {
pot,
printom(x) {
return x + 10;
// console.log("hello World");
}
};
const month = ["Jan", "feb", "march"]
for (const x of month) {
// ?? this is called nullish collaison operator
const op = restorant.pot[x]?.open ?? "closed !";
console.log(`on ${x} we open at ${op} `);
}
// With method optional chaining
console.log(restorant.printom?.(10) ?? "Not present");
// with Array optional chaining
//const arr1 = [{ Name: "Divyam" }];
const arr1 = [];
console.log(arr1[0]?.Name ?? "Not Exist");
// or
if (arr1.length > 0) console.log(arr1[0].Name);
else console.log("Not exist");
|
import React from 'react';
import StarRatings from 'react-star-ratings';
class Bar extends React.Component {
render() {
return (
<StarRatings
rating={this.props.rating}
numberOfStars={10}
starDimension="13px"
starSpacing="1px"
starRatedColor="#ffd700"
starEmptyColor="#69696991"
/>
);
}
}
export default Bar; |
$(document).ready (
function(){
$('#inputGroupSelect3').change(function(){
$('.business-select').hide();
$('#' + $(this).val()).show();
});
});
|
/*****************************************************************************/
/* PublicationsList: Lifecycle Hooks */
/*****************************************************************************/
Template.PublicationsList.onRendered(function() {
function organizeIsotope(argument) {
container.imagesLoaded(function() {
container.isotope('reloadItems').isotope('layout').isotope();
if (!container.children().not('#noResultsMessage').length) {
$('#noResultsMessage').removeClass('hidden').hide().fadeIn(600);
} else {
$('#noResultsMessage').hide();
}
});
}
var container = $('#container');
//Load Isotope with Masonry
container.imagesLoaded(function() {
container.isotope({
layoutMode: 'masonry',
itemSelector: '.ms-item',
transitionDuration: '0s'
}).isotope('layout').isotope();
});
container[0]._uihooks = {
insertElement: function(node, next) {
$(node).insertBefore(next);
organizeIsotope();
},
removeElement: function(node, next) {
$(node).remove();
organizeIsotope();
}
};
});
|
angular
.module('Mobidul')
.controller('StationController', StationController);
StationController.$inject = [
'$log', '$rootScope', '$sce', '$scope', '$compile', '$timeout',
'$state', 'StateManager', '$translate',
'StationService', 'MobidulService', 'HeaderService',
'UserService', 'RallyService', 'GeoLocationService', 'FontService'
];
function StationController (
$log, $rootScope, $sce, $scope, $compile, $timeout,
$state, StateManager, $translate,
StationService, MobidulService, HeaderService,
UserService, RallyService, GeoLocationService, FontService
) {
var station = this;
/// constants
// ...
/// vars
station.isCordovaIos = isCordova && isIos;
station.mediaList = [];
station.imageList = [];
station.content = '';
station.text = $translate.instant('LOADING');
// station.loading = 'visible';
station.loading = 'block';
station.stationId = 0;
station.panZoomConfig = {};
station.panZoomModel = {};
station.myFont = '';
station.isRalley = true;
station.comeFromSocial = false;
/// functions
// station.getStation = getStation;
station.renderText = renderText;
station.getPictureByHash = getPictureByHash;
station.checkIfRalley = checkIfRalley;
$scope.actionPerformed = actionPerformed;
/// XXX temp function
station.setRallyState = setRallyState;
station.progressToNext = __progressToNext;
station.activateThis = activateThis;
// XXX why is this nicer or better than calling what it returns ?
station.__isStatusActivated = function () {
return RallyService.isStatusActivated();
};
station.__isStatusOpen = function () {
return RallyService.isStatusOpen();
};
/// construct
_init();
/// XXX temp functions
function setRallyState(state){
RallyService.setStatus(state)
.then(function(newState){
renderJSON();
//Stop position watching and timeout on state change
GeoLocationService.stopPositionWatching();
$timeout.cancel($rootScope.timeout);
// Todo: is this necessary?
//$rootScope.timeout = undefined;
//$state.go($state.current, {}, {reload: true});
});
}
function __progressToNext () {
$log.warn('StationController.__progressToNext(): Please don\'t use this any longer');
RallyService.activateNext()
.then(function(){
RallyService.progressToNext();
});
}
function activateThis () {
$log.warn('StationController.activateThis(): Please don\'t use this any longer');
RallyService.setProgress(station.order)
.then(function () {
$state.go($state.current, {}, {reload: true});
});
}
/// private functions
function _init ()
{
$log.debug('StationController init');
_initStation();
_initActionListener();
_listenToConfig();
checkIfRalley();
}
function _initStation () {
if (
StateManager.state.params.mobidulCode &&
StateManager.state.params.stationCode &&
StateManager.state.params.stationCode != StateManager.NEW_STATION_CODE
) {
StationService.getStation(
StateManager.state.params.mobidulCode,
StateManager.state.params.stationCode
)
.success(function (response, status, headers, config) {
// $log.info('_initStation station response :');
// $log.debug(response);
if ( response === '' ) {
station.text = $translate.instant('NO_STATION_FOR_CODE');
UserService.Permit.EditStation = false;
} else {
var goToCurrentTesting = true;
RallyService.isEligible(response.order)
.then(function (isEligible) {
if (
! isEligible &&
! StateManager.isStationCreator() &&
! goToCurrentTesting
) {
RallyService.goToCurrent();
} else {
UserService.Permit.EditStation = response.canEdit && UserService.Permit.EditStation;
station.content = response.content;
station.stationId = response.stationId;
station.stationName = response.stationName;
station.order = response.order;
station.coords = response.coords;
// console.debug("BLUE::StationController::_initStation::station.content");
// console.debug(station.content);
/// XXX: this is just for testing purposes
/// choosing right content based on Mobidul type
RallyService.refresh();
var statusContent = [];
statusContent[ RallyService.STATUS_HIDDEN ] = '' +
'<p style="background: #eee; font-weight: bold">' +
'Diese Station hat für den Status "' + RallyService.STATUS_HIDDEN + '" keinen Inhalt.' +
'</p>';
statusContent[ RallyService.STATUS_ACTIVATED] = '' +
'<p style="background: #eee; font-weight: bold">' +
'Diese Station hat für den Status "' + RallyService.STATUS_ACTIVATED + '" keinen Inhalt.' +
'</p>';
statusContent[ RallyService.STATUS_OPEN] = '' +
'<p style="background: #eee; font-weight: bold">' +
'Diese Station hat für den Status "' + RallyService.STATUS_OPEN + '" keinen Inhalt.' +
'</p>';
statusContent[ RallyService.STATUS_COMPLETED] = '' +
'<p style="background: #eee; font-weight: bold">' +
'Diese Station hat für den Status "' + RallyService.STATUS_COMPLETED + '" keinen Inhalt.' +
'</p>';
// station.content = statusContent[ RallyService.getStatus( station.order ) ] + response.content;
// station.content = response.content;
StationService.setName( response.stationName );
//get length of all stations belonging to this mobidul to display progressbar correctly
RallyService.getRallyLength()
.then(function (length) {
station.rallyLength = parseInt(length);
});
RallyService.getProgress()
.then(function (progress) {
station.currentStation = progress.progress;
station.currentState = progress.state;
});
MobidulService.getMobidulConfig(
StateManager.state.params.mobidulCode
)
.then(function (config) {
station.mobidulConfig = config;
});
// TODO: document what the following is doing !
station.mediaList[ response.stationId ] = [];
for (var i = 0; i < response.mediaList.length; i++) {
var currMediaListHash = response.mediaList[i].hash;
station.mediaList[ response.stationId ].push({
'hash' : currMediaListHash,
'timestamp' : response.mediaList[i].timestamp
});
if (
typeof station.imageList[currMediaListHash] == 'undefined'
) {
station.imageList[currMediaListHash] = {
'url' : response.mediaList[i].url,
'uploaded' : true,
'uploadprogress' : 100
};
}
}
// Check whether Station has JSON Content
try {
station.config = JSON.parse(station.content);
// $log.info('station.config:');
// $log.debug(station.config);
// console.debug("BLUE::StationController::_initStation::station.config");
// console.debug(station.config);
// Display dev tools for rally
station.isOwner = UserService.Session.role == 1;
renderJSON();
} catch (e) {
// TODO: Add better error !
$log.warn('No JSON');
$log.error(e);
// station.renderText();
}
}
});
}
station.loading = 'none';
})
.error(function (response, status, headers, config) {
$log.error('couldn\'t get station');
$log.error(response);
$log.error(status);
station.loading = 'none';
})
.then(function () {
HeaderService.refresh();
$rootScope.$emit('rootScope:toggleAppLoader', { action : 'hide' });
});
}
}
function _initActionListener () {
$scope.$on('action', function (event, msg) {
actionPerformed(msg);
});
}
function _listenToConfig ()
{
var setConfigListener =
$rootScope.$on('rootScope:setConfig', function (event, config) {
// $log.debug('Listened to "rootScope:setConfig" in StationController');
// $log.debug(config);
station.myFont = FontService.getFontClass( MobidulService.Mobidul.font );
});
$scope.$on('$destroy', setConfigListener);
}
function renderText ()
{
$log.warn('RenderText() is deprecated - please don\'t use it any longer!');
var ergebnis = station.content; //.replace(/<.[^>]*>/g, '');
ergebnis = '\n' + ergebnis; // billiger Trick - so ist auch vor Beginn der ersten Zeile ein \n, und das gilt auch als Whitespace also \s
var regexp = [
// fett: beginnender * nach einem Whitespace (auch \n)
/(\s)\*([^*\s][^*]*[^*\s])\*/g,
// H1: beginnender ** nach einem Whitespace (auch \n)
/\s\*\*([^*\s][^*]*[^*\s])\*\*/g,
// kursiv: beginnender _ nach einem Whitespace (auch \n)
/(\s)\_([^*\s][^_]*[^*\s])\_/g,
// Links werden einfach am http... erkannt
/(\s)(https?:\/\/\S+)(\s)/g,
// normale Links, die mit --- markiert sind
/(\s)-{3}(https?:\/\/[^\s]+)-{3}/g,
// Links auf eine interne Mobilot-Seite - soll per JS geladen werden!!
/*/(\s)-{3}(\w+)-{3}/g,*/
// BILDxxx nur am Anfang einer Zeile
/\nBILD([0-9]+)/g,
// VIDEOxyz nur am Anfang einer Zeile, gibt den Dateinamen (ohne Dateierweiterung an)
/\nVIDEO(\w)/g,
// AUDIOxyz nur am Anfang einer Zeile, gibt den Dateinamen (ohne Dateierweiterung an)
/\nAUDIO(\w)/g,
// löscht führende Zeilenumbruch weg (u.a. den billigen Trick) - wir starten nicht mir leeren Zeilen
/^\n+/,
// Carriage Return (also eingegebenes Enter) - muss als letztes ersetzt werden!!!
/\n/g
];
var ersetzung = [
// fett: $1 ist das Leerzeichen oder CR vor dem *, $2 der fette Text
'$1<b>$2</b>',
// $1 ist der Text (das vorherige Leerzeichen oder CR brauchen wir bei H1 (=Blockelement) nicht)
'<h1>$1</h1>',
// $1 ist das Leerzeichen oder CR vor dem *, $2 der kursive Text
'$1<i>$2</i>',
// ersetzt URLs automatisch durch Link auf die URL
'$1<a href="$2">$2</a>$3',
// externe Links mit --- Syntax
'$1<a href="$2">$2</a>',
// es werden 2 Params übergeben, 1) der Match, 2) die Bildnummer (weil in runden Klammern)
null,
// es werden 2 Params übergeben, 1) der Match, 2) das Video (weil in runden Klammern)
null,
// es werden 2 Params übergeben, 1) der Match, 2) das Audio (weil in runden Klammern)
null,
'',
'</p><p>'
];
for (var i = 0; i < regexp.length; i++) {
oneRegExp = regexp[i];
oneErsetzung = ersetzung[i];
if ( i != 5 && i != 6 && i != 7 ) {
ergebnis = ergebnis.replace(oneRegExp, oneErsetzung);
}
if ( i == 5 ) {
var scope = station;
//ergebnis.replace bei Bild geht nicht, da die Bilder() funktion dann nicht auf this zugreifen.
ergebnis = ergebnis.replace(oneRegExp, function (match, bildNummer) {
var myMediaList = [];
//for new stations: images should be at -1 in medialist
var stationid = ( scope.stationId != '' ) ? scope.stationId : -1;
//make it safe!!
if ( typeof scope.stationId != 'undefined'
&& typeof scope.mediaList != 'undefined'
) {
if ( typeof scope.mediaList[ stationid ] != 'undefined' ) {
for (var i = 0; i < scope.mediaList[ stationid ].length; i++) {
myMediaList.push(scope.mediaList[ stationid ][ i ]);
}
myMediaList.sort(function (x, y) {
return x.timestamp - y.timestamp;
});
/// getPictureByHash
// not sure if bildNummer -1 or bildNummer
if ( bildNummer > myMediaList.length || myMediaList.length == 0 ) {
return '<p>Ungültige Bildnummer: ' + bildNummer + '</p>';
} else {
// an der Stelle wird für die Bildnummer die URL des Bildes (sollte md5-Hash sein) eingesetzt.
var image = scope.getPictureByHash( myMediaList[ bildNummer-1 ].hash );
if ( image != null ) {
var imgSrc = cordovaUrl + '/image/' + window.screen.availWidth + '/' + image.url;
if ( Boolean(image.uploaded) ) {
return '<a href="#/' + StateManager.state.params.mobidulCode + '/media/' + image.url +'">' +
'<img' +
' class="picture"' +
' src="' + imgSrc + '"' +
' width="100%"' +
' height="auto"' +
' style="max-width: ' + window.screen.availWidth + 'px"' +
'>' +
'</a>';
} else {
// TODO maybe add missing image default image (thumbnail)
return '<a href="#/' + StateManager.state.params.mobidulCode + '/media/' + image.url + '">' +
'<img' +
' class="picture"' +
' src="' + imgSrc + '"' +
' width="100%"' +
' height="auto"' +
' style="max-width: ' + window.screen.availWidth + 'px"' +
'>' +
'</a>';
}
} else {
// $log.debug("image was null");
$log.debug('image was null');
}
}
}
}
return "Bild " + bildNummer + " nicht gefunden";
});
}
if ( i == 6 ) {
var stateParams = StateManager.state.params;
ergebnis = ergebnis.replace(oneRegExp, function (match, videoFileName) {
var videostring = '<video controls style="width: 100%;" ' +
'poster="http://mobilot.at/media/' +
stateParams.mobidulCode +
'/' + videoFileName + '.jpg"' +
'>' +
'<source src="http://mobilot.at/media/' +
stateParams.mobidulCode +
'/' + videoFileName + '.mp4" ' +
'type="video/mp4"' +
'>' +
'</video>';
return videostring;
});
}
if ( i == 7 ) {
var stateParams = StateManager.state.params;
ergebnis = ergebnis.replace(oneRegExp, function (match, audioFileName) {
var audiostring = '<audio controls style="width : 100%">' +
'<source src="http://mobilot.at/media/' +
stateParams.mobidulCode + '/' +
audioFileName + '.mp3" ' +
'type="audio/mp3"' +
'>' +
'</audio>';
return audiostring;
});
}
}
if ( this.disablelinks ) {
ergebnis = ergebnis.replace(/-{3}(\w+)-{3}/g, '<font color="blue" style="text-decoration:underline">Klick</font>');
} else {
ergebnis = ergebnis.replace(/-{3}(\w+)-{3}/g, '<a href="#/' + StateManager.state.params.mobidulCode + '/$1/">Station $1</a>');
}
///*href="' + location.protocol + '//' + location.host + '/' + this.mobidul + '/#/content/$1\"
ergebnis = '<p>' + ergebnis + '</p>';
// replace (some) empty paragraph tags
ergebnis = ergebnis.replace(/<p><\/p>/gmi, '');
// replace (the rest of) empty paragraph tags
ergebnis = ergebnis.replace(/<p><\/p>/gmi, '');
station.text = $sce.trustAsHtml( ergebnis );
}
/**
* Appends Rally Directives to their container
*/
function renderJSON () {
RallyService.getStatus(station.order)
.then(function (status) {
$log.info('StationController - renderJSON');
station.currentState = status;
var isSocial = StateManager.getParams().verifier;
var socialCode = StateManager.getParams().socialCode;
var socialComponentId = StateManager.getParams().socialStatus;
// Check if socialConfirm, then go for confirm social component
if(isSocial == "socialConfirm"){
station.comeFromSocial = true;
}else{
station.comeFromSocial = false;
}
if ( ! StateManager.isStationCreator() ) {
var config = station.config[status];
$log.debug("StationController::config");
$log.debug(config);
var container = document.getElementById('station_container');
container.innerHTML = '';
if (config) {
config.forEach(function (obj) {
var type = obj.type;
if ( ! type ) {
$log.error('JSON Object doesn\'t have a type ! (ignoring)');
} else {
switch (type) {
case 'HTML':
angular
.element(container)
.append($compile('<mbl-html-container>' + obj.content + '</mbl-html-container>')($scope));
break;
case 'INPUT_CODE':
angular
.element(container)
.append($compile("<mbl-input-code data-id='" + obj.id + "' verifier='" + obj.verifier + "' success='" + obj.success + "' error='" + obj.error + "'></mbl-input-code>")($scope));
break;
case 'BUTTON':
angular
.element(container)
.append($compile("<mbl-action-button success='" + obj.success + "'>" + obj.content + "</mbl-action-button>")($scope));
break;
case 'IF_NEAR':
// HACK: force to startwatching after stopwatching event from headerservice
$timeout(function () {
GeoLocationService.startPositionWatching(station.coords);
}, 0);
angular
.element(container)
.append($compile("<mbl-trigger-near range='" + obj.range + "' fallback='" + obj.fallback + "' success='" + obj.success + "'></mbl-trigger-near>")($scope));
break;
case 'BLUETOOTH':
// HACK: force to startwatching after stopwatching event from headerservice
// $timeout(function () {
// // TODO: add service for bluetooth searching which ranges for bluetooth ranging.
// console.debug("Bluetooth Service triggered... Theoretically.")
// }, 0);
if ( isCordova ) {
angular
.element(container)
.append($compile("<mbl-blue-tooth beaconname='" + obj.beaconname + "' " +
"beaconkey='" + obj.beaconkey + "' " +
"fallback='" + obj.fallback + "' " +
"success='" + obj.success + "' " +
"selectedrange='" + obj.selectedrange + "'></mbl-blue-tooth>")($scope));
} else {
angular
.element(container)
.append($compile('<mbl-html-container>{{ "BLUETOOTH_NOT_AVAILABLE_WEB\" | translate }}</mbl-html-container>')($scope))
.append($compile("<mbl-input-code verifier='" + obj.fallback + "' success='" + obj.success + "' error='SAY:{{ \"INPUT_CODE_DEFAULT_ERROR_MSG\" | translate }}'></mbl-input-code>")($scope));
}
// console.debug("BLUE-->range-->fallback-->success");
// console.debug(obj.range);
// console.debug(obj.fallback);
// console.debug(obj.success);
break;
// case 'PHOTO_UPLOAD':
// angular
// .element(container)
// .append($compile('<mbl-photo-upload data-id="' + obj.id + '" data-success="' + obj.success + '" data-content="' + obj.content + '"></mbl-photo-upload>')($scope));
// break;
case 'SET_TIMEOUT':
angular
.element(container)
.append($compile('<mbl-set-timeout data-show="' + obj.show + '" data-delay="' + obj.delay + '" data-action="' + obj.action + '"></mbl-set-timeout>')($scope));
break;
case 'FREE_TEXT':
angular
.element(container)
.append($compile('<mbl-free-text-input success="' + obj.success + '" question="' + obj.question + '" id="' + obj.id + '"></mbl-free-text-input>')($scope));
break;
case 'CONFIRM_SOCIAL':
$log.debug("StationController::CONFIRM_SOCIAL");
var isConfirmed = false;
if(station.comeFromSocial && socialComponentId == obj.id) {
// set isConfirmed true to show PERFORM_ACTION Button
isConfirmed = true;
//$rootScope.$broadcast('action', obj.success);
}
angular
.element(container)
.append($compile('<mbl-confirm-social data-success="' + obj.success + '" data-id="' + obj.id + '" data-confirm="' + isConfirmed + '"></mbl-confirm-social>')($scope));
break;
case 'SHOW_SCORE':
angular
.element(container)
.append($compile('<mbl-show-score data-content="' + obj.content + '"></mbl-show-score>')($scope));
break;
default:
$log.error("Objecttype not known: " + type);
break;
}
}
});
}
}
});
}
/**
* Rally-Directives trigger these actions
*
* @param actionString
*/
function actionPerformed (actionString) {
RallyService.performAction(actionString)
.then(function (refresh) {
if (refresh) {
renderJSON();
}
}, function (error) {
$log.error(error);
});
}
function getPictureByHash (hash) {
if ( hash != null ) {
// suche in Bildliste nach Bild
if ( typeof station.imageList[hash] != 'undefined' ) {
return station.imageList[hash];
}
}
return null;
}
function checkIfRalley () {
MobidulService.getMobidulMode(StateManager.state.params.mobidulCode)
.then(function (mobidulMode) {
station.isRalley = mobidulMode == MobidulService.MOBIDUL_MODE_RALLY;
});
}
/// events
// ...
}
|
import instance from '../../helpers/axios';
export default {
state: {
merchants: [],
},
mutations: {
setMerchants(state, payload) {
state.merchants = payload;
},
addMerchants(state, payload) {
state.merchants = [...state.merchants, ...payload];
},
},
actions: {
async MERCHANTS({ commit }, payload = {}) {
try {
const { lastId = '' } = payload;
const { data } = await instance.get(`/merchant?lastId=${lastId}`);
if (!lastId) { commit('setMerchants', data.data || []); }
if (lastId) { commit('addMerchants', data.data || []); }
return data.data || [];
} catch (err) {
return Promise.reject(err);
}
},
},
getters: {
merchants: (state) => state.merchants,
},
};
|
(function () {
'use strict';
angular.module('wug').
controller('NavCtrl', ['$scope', 'tabsService', function ($scope, tabsService) {
$scope.addTab = function () {
tabsService.addTab();
};
// implicitly watched from view binding
// This method only gets called once during assignment.
// The result is the object and the link to the method is
// broken afterward.
// In subsequent digest loops, we keep comparing the
// resulting object, not calling the service method again.
// The data in the service has changed. If we run this method
// again, we will get a different value. However, we're not
// running it again. We're just looking at $scope.counts
// and comparing it with the previous $scope.counts.
// They're equal, so nothing happens.
$scope.counts = tabsService.getCounts();
// digest loop never re-runs tabsService.getCounts();
// Create watch that will manually re-run it.
$scope.$watch(function () {
var counts = tabsService.getCounts();
if (!angular.equals(counts, $scope.counts)) {
$scope.counts = counts;
}
});
}]);
}()); |
describe('pixi/textures/Texture', function () {
'use strict';
var expect = chai.expect;
var Texture = PIXI.Texture;
it('Module exists', function () {
expect(Texture).to.be.a('function');
expect(PIXI).to.have.property('TextureCache').and.to.be.an('object');
});
it('Members exist', function () {
expect(Texture).itself.to.respondTo('fromImage');
expect(Texture).itself.to.respondTo('fromFrame');
expect(Texture).itself.to.respondTo('fromCanvas');
expect(Texture).itself.to.respondTo('addTextureToCache');
expect(Texture).itself.to.respondTo('removeTextureFromCache');
// expect(Texture).itself.to.have.deep.property('frameUpdates.length', 0);
});
it('Confirm new instance', function (done) {
var texture = Texture.fromImage('/base/test/textures/bunny.png');
pixi_textures_Texture_confirmNew(texture, done);
});
});
|
function getSearch() {
console.log("aaa");
$.ajax({
type: "POST",
url: "/search/result",
dataType: "json",
data: {mySearch: $("#sch").val(), typeSearch: $("#typeSch").val()},
success: successGetSearch
});
}
function successGetSearch(data, textStatus) {
$("#tabResult tr").remove();
data.listLinkFound.forEach(function(val, idx) {
$("#tabResult > tbody:last").append('<tr class="success"><td>'+(idx+1)+'</td><td><a href='+val+'>'+val+'</a></td><td>...</td></tr>');
saveId=(idx+1);
});
} |
import React from 'react';
import styled, { keyframes } from 'styled-components';
import bg from '../Images/bg-dots.png';
const Skills = () => {
return (
<StackWrapper>
<StackContainer className='fog-to-bottom' color='rgb(255,30,30)' bg={bg}>
<div className='tech'>
<h1>Stack</h1>
<hr className="neon"></hr>
<ul>
<li><i className='icon-html5-1'></i>HTML5</li>
<li><i className='icon-css3-1'></i>CSS3</li>
<li><i className='icon-sass-original'></i>Sass</li>
<li><i className='icon-javascript'></i>JavaScript (ES6+)</li>
<li><i className='icon-typescript'></i>TypeScript</li>
<li><i className='icon-react'></i>React</li>
<li><i className='icon-angular'></i>Angular</li>
</ul>
</div>
<div className='tools'>
<h1 >Additional experience</h1>
<hr className="neon"></hr>
<ul>
<li><i className='icon-bootstrap-plain'></i>Bootstrap</li>
<li><i className='icon-node'></i>NodeJS</li>
<li><i className='icon-express-original'></i>ExpressJS</li>
<li><i className='icon-postgresql-plain'></i>PostgreSQL</li>
<li><i className='icon-mapbox'></i>MapBox</li>
<li><i className='icon-rxjs'></i>RxJS</li>
</ul>
</div>
<div className='other'>
<h1>Tools</h1>
<hr className="neon"></hr>
<ul>
<li><i className='icon-git-plain'></i>Git/GitHub</li>
<li><i className='icon-npm'></i>npm</li>
<li><i className='icon-visualstudio-plain'></i>Visual Studio Code</li>
<li><i className='icon-jira'></i>Jira</li>
</ul>
</div>
</StackContainer>
</StackWrapper>
)
};
//keyframes
const makegray = keyframes`
41% {filter:grayscale(0%)}
42% {filter:grayscale(100%)}
43% {filter:grayscale(0%)}
49% {filter:grayscale(0%)}
50% {filter:grayscale(100%)}
65% {filter:grayscale(100%)}
66% {filter:grayscale(0%)}
`;
function blink (props) {
return keyframes`
41% { border:0.5px solid white;box-shadow: 0 0 20px 3px ${props.color}; }
42% { border:0.5px solid gray;box-shadow:none }
43% { border:0.5px solid white;box-shadow: 0 0 20px 3px ${props.color} }
49% { border:0.5px solid white;box-shadow: 0 0 20px 3px ${props.color}; }
50% { border:0.5px solid gray;box-shadow:none }
65% { border:0.5px solid gray;box-shadow:none}
66% { border:0.5px solid white;box-shadow: 0 0 20px 3px ${props.color}; }
`};
const turnon = keyframes `
100%{text-shadow: 0 0 2px, 0 0 1em #ff4444, 0 0 0.5em #ff4444, 0 0 0.1em #ff4444, 0 10px 3px #000;color:#fee}
`;
const show = keyframes `
100%{opacity:1}
`;
const StackWrapper = styled.div `
max-width:90vw;
margin:3em auto;
ul{
padding:0;
list-style:none;
font-size: 1.1em;
li{
text-align:left;
padding:0.4em;
i:before{
width:30px;
padding-right:0.5em;
}
}
}
div.tech{
/* hr{animation:${turnon} 0.2s 1 0.4s forwards}; */
ul{opacity:0;animation:${show} 0.2s 1 0.4s forwards}}
div.tools{
/* hr{animation:${turnon} 0.2s 1 0.7s forwards}; */
ul{opacity:0;animation:${show} 0.2s 1 0.7s forwards}}
div.other{
/* hr{animation:${turnon} 0.2s 1 1s forwards}; */
ul{opacity:0;animation:${show} 0.2s 1 1s forwards}}
`;
const StackContainer = styled.div `
max-width:1100px;
/* width:100%; */
margin:0 auto;
display:flex;
justify-content:space-between;
box-shadow: -3px 3px 6px 5px black;
border: double 6px rgba(150,150,150,0.8);
border-radius:10px;
padding:1em;
background-image:linear-gradient(rgba(0,0,0,0.85),rgba(0,0,0,0.85)),url(${props => props.bg});
h1 {
/* font-family: "neontubes"; */
font-weight:300;
margin:14px 0;
font-size:1.3em;
text-shadow: none;
color:transparent;
background: -webkit-linear-gradient(
270deg,
rgb(201, 201, 201) , rgb(95, 95, 95), ${props => props.color});
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
animation: ${makegray} 5s infinite alternate;
}
hr {
/* height:0px; */
border:0.5px solid white;
border-radius:50px;
background-color: white;
width:200px;
height:1px;
box-shadow: 0 0 20px 3px ${props => props.color};
animation: ${props => blink(props)} 5s infinite alternate;
}
.tech, .tools, .other {
margin:0 auto;
display: flex;
flex-direction: column;
text-align:center;
line-height:1.5em;
color:rgb(160, 160, 160);
font-family: 'Nunito', sans-serif;
/* height:400px; */
}
@media (max-width:700px) {
/* margin:0 auto; */
flex-direction:column;
}
`;
export default Skills; |
import {
useState,
useEffect,
useRef,
useLayoutEffect,
useContext,
lazy,
} from "react";
import {
X_svg,
Combobox,
Err_svg,
Succ_svg,
calculatePrice,
calculateDiscount,
Minus_svg,
Plus_svg,
addToCart,
Header,
Footer,
Tip,
Cart_svg,
Img,
Moment,
useOnScreen,
Arrow_left_svg,
LS,
ShareButtons,
} from "./Elements";
import { AddressForm } from "./Forms";
import { SiteContext, ChatContext, socket } from "../SiteContext";
import { Link, Redirect } from "react-router-dom";
import { Modal, Confirm } from "./Modal";
import { Chat } from "./Deals";
import queryString from "query-string";
import { toast } from "react-toastify";
import TextareaAutosize from "react-textarea-autosize";
const Helmet = lazy(() => import("react-helmet"));
const MilestoneForm = lazy(() =>
import("./Forms").then((mod) => ({ default: mod.MilestoneForm }))
);
require("./styles/marketplace.scss");
const Marketplace = ({ history, location, match }) => {
const { userType } = useContext(SiteContext);
const [nativeShare, setNativeShare] = useState(false);
const [share, setShare] = useState(false);
const [loadingRef, loadingVisible] = useOnScreen({ rootMargin: "100px" });
const sortOptions = useRef([
{
label: "Newest first",
value: { column: "createdAt", order: "dsc" },
},
{
label: "Oldest first",
value: { column: "createdAt", order: "asc" },
},
{
label: "Price high-low",
value: { column: "price", order: "dsc" },
},
{
label: "Price low-high",
value: { column: "price", order: "asc" },
},
]);
const [categories, setCategories] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [type, setType] = useState(
queryString.parse(location.search).type || ""
);
const [perPage, setPerPage] = useState(
queryString.parse(location.search).perPage || 20
);
const [page, setPage] = useState(1);
const [search, setSearch] = useState(
queryString.parse(location.search).q || ""
);
const [sort, setSort] = useState({
column: queryString.parse(location.search).sort || "createdAt",
order: queryString.parse(location.search).order || "dsc",
});
const [products, setProducts] = useState([]);
const [msg, setMsg] = useState(null);
const [category, setCategory] = useState("");
const [seller, setSeller] = useState(
queryString.parse(location.search).seller
);
const [sellerDetail, setSellerDetail] = useState(null);
const [buyerDetail, setBuyerDetail] = useState(null);
const [loadingMore, setLoadingMore] = useState(false);
const [chatOpen, setChatOpen] = useState(false);
const loadMore = () => {
setLoadingMore(true);
fetch(`/api/getProducts${location.search}&page=${page + 1}`)
.then((res) => res.json())
.then((data) => {
setLoadingMore(false);
if (data.code === "ok") {
if (data.products.length) {
setProducts((prev) => [...prev, ...data.products]);
setPage((prev) => prev + 1);
} else {
}
} else {
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>Could not get products. Please try again.</h4>
</div>
</>
);
}
})
.catch((err) => {
setLoadingMore(false);
console.log(err);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>Could not get products. Make sure you're online.</h4>
</div>
</>
);
});
};
useEffect(() => {
fetch(`/api/getProducts?${location.search.replace("?", "")}&page=${1}`)
.then((res) => res.json())
.then((data) => {
if (data.code === "ok") {
setTotal(data.total);
setProducts(data.products);
if (data.seller) {
setSellerDetail(data.seller);
if (data.categories) {
setCategories(data.categories);
}
} else {
setSellerDetail(null);
}
if (data.buyer) {
setBuyerDetail(data.buyer);
} else {
setBuyerDetail(null);
}
} else {
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>Could not get products. Please try again.</h4>
</div>
</>
);
}
})
.catch((err) => {
console.log(err, 156);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>Could not get products. Make sure you're online.</h4>
</div>
</>
);
});
}, [location.search]);
useEffect(() => {
history.replace({
pathname: history.location.pathname,
search:
"?" +
new URLSearchParams({
...(seller && { seller }),
...(search.length >= 4 && { q: search }),
perPage,
sort: sort.column,
order: sort.order,
...(type && { type }),
...(category && { category }),
...(userType === "seller" &&
LS.get("buyer") && { buyer: LS.get("buyer") }),
}).toString(),
});
}, [page, search, sort, seller, type, category]);
useEffect(() => {
if (loadingVisible && total > products.length) {
loadMore();
}
}, [loadingVisible]);
useEffect(() => {
if (navigator.share) {
setNativeShare(true);
}
}, []);
return (
<div className={`generic marketplace ${chatOpen ? "chatOpen" : ""}`}>
<Header />
<div style={{ display: "none" }}>
<X_svg />
</div>
<div className="benner">
<h1>Delivery Pay Marketplace</h1>
</div>
<div className="content">
<div className="mainContent">
{sellerDetail && (
<div className="sellerDetail">
{sellerDetail?.shopInfo?.logo && (
<Img className="logo" src={sellerDetail.shopInfo.logo} />
)}
<p>
{sellerDetail.shopInfo?.name ||
sellerDetail.firstName + " " + sellerDetail.lastName}
</p>
</div>
)}
<div className="filters">
<section className="categories">
<label>Category</label>
<Combobox
defaultValue={0}
options={[
{ label: "All", value: "" },
...categories.map((item) => ({ label: item, value: item })),
]}
onChange={(e) => {
setCategory(e.value);
}}
/>
</section>
<section className="search">
<svg
xmlns="http://www.w3.org/2000/svg"
width="23"
height="23"
viewBox="0 0 23 23"
>
<path
id="Icon_ionic-ios-search"
data-name="Icon ionic-ios-search"
d="M27.23,25.828l-6.4-6.455a9.116,9.116,0,1,0-1.384,1.4L25.8,27.188a.985.985,0,0,0,1.39.036A.99.99,0,0,0,27.23,25.828ZM13.67,20.852a7.2,7.2,0,1,1,5.091-2.108A7.155,7.155,0,0,1,13.67,20.852Z"
transform="translate(-4.5 -4.493)"
fill="#707070"
opacity="0.74"
/>
</svg>
<input
value={search}
onChange={(e) => {
setSearch(e.target.value);
}}
placeholder="Search for products or services"
/>
{search && (
<button onClick={() => setSearch("")}>
<X_svg />
</button>
)}
</section>
<section className="sort">
<label>Sort by:</label>
<Combobox
defaultValue={sortOptions.current.find(
(item) =>
item.value.column === sort.column &&
item.value.order === sort.order
)}
options={sortOptions.current}
onChange={(e) => setSort(e.value)}
/>
</section>
{nativeShare && (
<section className="share">
<button
onClick={async () => {
setShare(true);
// try {
// await navigator.share({
// title: `Delivery Pay | ${
// sellerDetail
// ? `${
// sellerDetail.firstName +
// " " +
// sellerDetail.lastName
// }`
// : "Marketplace"
// }`,
// url: window.location.href,
// });
// } catch (err) {}
}}
>
Share this page
</button>
</section>
)}
</div>
<div className={`products ${products.length === 0 ? "empty" : ""}`}>
{products.map((item) => (
<Product key={item._id} data={item} />
))}
{total > products.length && (
<div className="placeholder">Loading</div>
)}
{products.length === 0 && (
<div className="placeholder">
<Img src="/open_box.png" />
<p>No Product Found</p>
</div>
)}
</div>
</div>
<Modal
open={share}
setOpen={setShare}
label="Share this page"
head={true}
className="shareModal"
>
<ShareButtons url={window.location.href} />
</Modal>
<Modal className="msg" open={msg}>
{msg}
</Modal>
</div>
<div ref={loadingRef} />
{sellerDetail && (
<MiniChat
client={userType === "seller" ? buyerDetail : sellerDetail}
onToggle={setChatOpen}
/>
)}
<Footer />
</div>
);
};
const MiniChat = ({ client, onToggle }) => {
const { user } = useContext(SiteContext);
const { contacts, setContacts } = useContext(ChatContext);
const [open, setOpen] = useState(false);
const [userCard, setUserCard] = useState(null);
const [chat, setChat] = useState(null);
useEffect(() => {
if (user && client) {
const clientChat = contacts.find(
(contact) => contact.client._id === client._id
);
if (clientChat) {
setUserCard({
...clientChat.client,
status: clientChat.userBlock ? "blocked" : "",
});
setChat(clientChat.messages);
socket.emit("initiateChat", {
client_id: client._id,
...(clientChat.messages === undefined && { newChat: true }),
});
}
}
}, [client, contacts]);
useEffect(() => {
onToggle?.(open);
}, [open]);
if (!client) {
return null;
}
if (!open) {
return (
<button
className="chatBtn"
onClick={() => {
if (user && !userCard) {
const clientChat = contacts.find(
(contact) => contact.client._id === client._id
);
console.log(clientChat);
if (clientChat) {
setUserCard({
...clientChat.client,
status: clientChat.userBlock ? "blocked" : "",
});
setChat(clientChat.messages);
socket.emit("initiateChat", {
client_id: client._id,
...(clientChat.messages === undefined && { newChat: true }),
});
} else {
setContacts((prev) => [
...prev,
{ client, messages: [], status: "" },
]);
socket.emit("initiateChat", {
client_id: client._id,
newChat: true,
});
}
}
setOpen(true);
}}
>
{
<svg
xmlns="http://www.w3.org/2000/svg"
width="26.55"
height="25.219"
viewBox="0 0 26.55 25.219"
>
<path
id="Path_1"
data-name="Path 1"
d="M-242.2-184.285h-13l26.55-10.786-4.252,25.219-5.531-10.637-2.127,4.68v-6.382l7.659-9.148h2.34"
transform="translate(255.198 195.071)"
fill="#fff"
/>
</svg>
}
</button>
);
}
if (!user) {
return (
<div className="chatWrapper">
<button className="closeChat" onClick={() => setOpen(false)}>
<Arrow_left_svg />
</button>
<div className="chat">
<div className="startChat">
<Link to="/u/login">
<p>Login to start chat with this seller.</p>
</Link>
</div>
</div>
</div>
);
}
return (
<div className="chatWrapper">
<button className="closeChat" onClick={() => setOpen(false)}>
<Arrow_left_svg />
</button>
<Chat
chat={chat}
setContacts={setContacts}
userCard={userCard}
setUserCard={setUserCard}
user={user}
setChat={setChat}
/>
</div>
);
};
const Product = ({ data }) => {
const { user, userType, setCart, setSellerCart } = useContext(SiteContext);
let finalPrice = calculatePrice({ product: data, gst: data.user?.gst });
return (
<div className="product">
<Link to={`/marketplace/${data._id}`}>
<div className={`thumb ${data.images[0] ? "" : "noThumb"}`}>
<Img src={data.images[0] || "/open_box.png"} />
</div>
</Link>
<div className="detail">
<h3>{data.name}</h3>
<p className="dscr">{data.dscr}</p>
<div className="price">
<span className="symbol">₹ </span>
{finalPrice}{" "}
{finalPrice !==
calculatePrice({
product: data,
gst: data.user.gst,
discount: false,
}) && (
<span className="originalPrice">
{calculatePrice({
product: data,
gst: data.user?.gst,
discount: false,
})}
</span>
)}
</div>
</div>
<div className="actions">
{userType === "buyer" && data?.user._id === user?._id && (
<p className="note">Can't buy product from self.</p>
)}
<button
disabled={
!data.available ||
(data?.user._id === user?._id && userType === "buyer")
}
onClick={() => {
data?.user._id === user?._id
? setSellerCart((prev) => addToCart(prev, data, "seller"))
: setCart((prev) => addToCart(prev, data));
}}
>
{data?.user._id === user?._id ? "Add to order" : "Add to Cart"}
</button>
</div>
</div>
);
};
export const SingleProduct = ({ match }) => {
const { user, setCart, setSellerCart, userType } = useContext(SiteContext);
const [nativeShare, setNativeShare] = useState(false);
const [share, setShare] = useState(false);
const [product, setProduct] = useState(null);
const [msg, setMsg] = useState(null);
const [chatOpen, setChatOpen] = useState(false);
useEffect(() => {
fetch(`/api/singleProduct?_id=${match.params._id}`)
.then((res) => res.json())
.then((data) => {
if (data.code === "ok") {
setProduct(data.product);
} else {
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>Product does not exists.</h4>
</div>
</>
);
}
})
.catch((err) => {
console.log(err);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>Could not get product. Make sure you're online.</h4>
</div>
</>
);
});
if (navigator.share) {
setNativeShare(true);
}
}, []);
if (product) {
return (
<>
<Helmet>
<title>{product.name} | Delivery Pay</title>
<meta name="description" content={product.dscr} />
<meta
property="og:url"
content={`https://deliverypay.in/marketplace/${product._id}`}
/>
<meta property="og:type" content="product" />
<meta
property="og:title"
content={`${product.name} | Delivery Pay`}
/>
<meta property="og:description" content={product.dscr} />
<meta property="og:image" content={product.images[0]} />
</Helmet>
<div className={`generic singleProduct ${chatOpen ? "chatOpen" : ""}`}>
<Header />
<div className="content">
<Gallery images={product.images} />
<div className="detail">
<h1>{product.name}</h1>
<p>{product.dscr}</p>
<p className="price">
<label>Price: </label> <span className="symbol">₹</span>
{calculatePrice({ product, gst: product.user?.gst })}{" "}
{calculatePrice({ product, gst: product.user?.gst }) !==
calculatePrice({
product,
gst: product.user?.gst,
discount: false,
}) && (
<span className="originalPrice">
{calculatePrice({
product,
gst: product.user?.gst,
discount: false,
})}
</span>
)}
</p>
{
// product.user?.gst?.verified && (
// <p className="gst">
// Including {product.gst || product.user.gst.amount}% GST
// </p>
// )
}
<p>
{product.type === "product" && (
<>
Available: {product.available && product.available}{" "}
{product.available === 0 && <>Out of stock</>}
{product.available < 7 && product.available > 0 && (
<>Low stock</>
)}
</>
)}
{product.type !== "product" && (
<>
Availability:{" "}
{product.available ? "Available" : "Unavailable"}
</>
)}
</p>
<div className="actions">
<button
disabled={
!product.available ||
(userType === "buyer" && product.user?._id === user?._id)
}
onClick={() => {
product?.user?._id === user?._id
? setSellerCart((prev) =>
addToCart(prev, product, "seller")
)
: setCart((prev) => addToCart(prev, product));
}}
>
{product?.user?._id === user?._id
? "Add to order"
: "Add to Cart"}
</button>
<button
onClick={async () => {
setShare(true);
// try {
// await navigator.share({
// title: `${product.name} | Delivery Pay`,
// url: window.location.href,
// });
// } catch (err) {}
}}
>
Share this Product
</button>
{userType === "seller" && product?.user?._id !== user?._id && (
<p className="note">
Switch to buyer profile to buy this product.
</p>
)}
{userType === "buyer" && product?.user?._id === user?._id && (
<p className="note">Can't buy product from self.</p>
)}
</div>
{product.user && (
<div className="seller">
<label>Being sold by:</label>
<Link to={`/marketplace?seller=${product.user._id}`}>
<div className="profile">
{product.user.shopInfo?.logo && (
<Img src={product.user.shopInfo?.logo} />
)}
{product.user.shopInfo?.name ? (
<p className="name">{product.user.shopInfo.name}</p>
) : (
<p className="name">
{product.user.firstName} {product.user.lastName}
</p>
)}
</div>
</Link>
</div>
)}
</div>
<Modal
open={share}
setOpen={setShare}
label="Share this page"
head={true}
className="shareModal"
>
<ShareButtons url={window.location.href} />
</Modal>
<Modal className="msg" open={msg}>
{msg}
</Modal>
</div>
{product && (
<MiniChat
client={
userType === "seller" ? { _id: LS.get("buyer") } : product.user
}
onToggle={setChatOpen}
/>
)}
<Footer />
</div>
</>
);
}
return (
<div className={`generic singleProduct ${chatOpen ? "chatOpen" : ""}`}>
<Header />
loading
<Modal className="msg" open={msg}>
{msg}
</Modal>
<Footer />
</div>
);
};
const Gallery = ({ images }) => {
const [view, setView] = useState(images[0]);
return (
<div className="gallery">
<ImageView img={view} />
<div className="thumbs">
{images.map((item, i) => (
<Img key={i} src={item} onClick={() => setView(item)} />
))}
{images.length === 0 && <p>No image was provided by the seller.</p>}
</div>
</div>
);
};
const ImageView = ({ img }) => {
const [src, setSrc] = useState(img || "/open_box.png");
const [boundingBody, setBoundingBody] = useState(null);
const [applyStyle, setApplyStyle] = useState(false);
const [style, setStyle] = useState({});
const container = useRef();
useEffect(() => {
setSrc(img || "/open_box.png");
}, [img]);
return (
<div
ref={container}
className={`mainView ${!img ? "noImg" : ""}`}
onMouseMove={(e) => {
if (img) {
const x =
Math.abs(
Math.round(
(e.clientX - boundingBody?.x) / (boundingBody?.width / 100)
)
) * 0.65;
const y =
Math.round(
(e.clientY - boundingBody?.y) / (boundingBody?.height / 100)
) * 0.65;
setStyle({
transform: `scale(2) translateY(${Math.max(
30 + -y,
-30
)}%) translateX(${Math.max(30 + -x, -30)}%)`,
});
}
}}
onTouchStart={(e) => {
document.querySelector("body").style.overflow = "hidden";
setBoundingBody(container.current?.getBoundingClientRect());
setApplyStyle(true);
}}
onTouchEnd={(e) => {
document.querySelector("body").style.overflow = "auto";
setApplyStyle(false);
}}
onTouchMove={(e) => {
if (img) {
const x =
Math.abs(
Math.round(
(e.touches[0].clientX - boundingBody.x) /
(boundingBody.width / 100)
)
) * 0.65;
const y =
Math.round(
(e.touches[0].clientY - boundingBody.y) /
(boundingBody.height / 100)
) * 0.65;
setStyle({
transform: `scale(2) translateY(${Math.max(
30 + -y,
-30
)}%) translateX(${Math.max(30 + -x, -30)}%)`,
transition: "none",
});
}
}}
onMouseEnter={() => {
setApplyStyle(true);
setBoundingBody(container.current?.getBoundingClientRect());
}}
onMouseLeave={() => setApplyStyle(false)}
>
<img
className={applyStyle ? "scale" : ""}
style={applyStyle ? style : {}}
src={src}
onError={() => setSrc("/img_err.png")}
/>
</div>
);
};
export const Cart = () => {
const { setCart, cart, userType } = useContext(SiteContext);
const [loading, setLoading] = useState(true);
const [carts, setCarts] = useState(null);
const [msg, setMsg] = useState(null);
useEffect(() => {
setLoading(true);
fetch("/api/getCartDetail", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
cart,
}),
})
.then((res) => res.json())
.then((data) => {
setLoading(false);
if (data.code === "ok") {
setCarts(data.carts);
}
})
.catch((err) => {
console.log(err);
setLoading(false);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>Could not get cart detail. Make sure you're online.</h4>
</div>
</>
);
});
}, [cart]);
if (carts) {
return (
<div className="fullCart">
{userType === "seller" && <Redirect to="/account/sellerCart" />}
<div className="head">
<h1>Cart</h1>
</div>
<div className="allCarts">
{carts.map(({ seller, products }) =>
seller && products?.length ? (
<Shop
key={seller._id}
seller={seller}
products={products}
loading={loading}
/>
) : null
)}
{carts?.length === 0 && <p>Cart is empty</p>}
</div>
<Modal open={msg} className="msg">
{msg}
</Modal>
</div>
);
}
return (
<div className="fullCart">
{userType === "seller" && <Redirect to="/account/sellerCart" />}
<div className="head">
<h1>Cart</h1>
</div>
<div className="allCarts">Cart is empty.</div>
<Modal open={msg} className="msg">
{msg}
</Modal>
</div>
);
};
export const SellerCart = () => {
const { sellerCart, setSellerCart, userType } = useContext(SiteContext);
const [loading, setLoading] = useState(true);
const [carts, setCarts] = useState(null);
const [msg, setMsg] = useState(null);
useEffect(() => {
setLoading(true);
fetch("/api/getSellerCartDetail", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ cart: sellerCart }),
})
.then((res) => res.json())
.then((data) => {
setLoading(false);
if (data.code === "ok") {
setCarts(data.carts);
}
})
.catch((err) => {
console.log(err);
setLoading(false);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>Could not get cart detail. Make sure you're online.</h4>
</div>
</>
);
});
}, [sellerCart]);
if (carts) {
return (
<div className="fullCart">
{userType === "buyer" && <Redirect to="/account/cart" />}
<div className="head">
<h1>Create Orders</h1>
</div>
<div className="allCarts">
{carts.map(({ buyer, products }) =>
buyer && products?.length ? (
<SellerShop
key={buyer._id}
buyer={buyer}
products={products}
loading={loading}
/>
) : null
)}
{carts?.length === 0 && <p>Cart is empty</p>}
</div>
<Modal open={msg} className="msg">
{msg}
</Modal>
</div>
);
}
return (
<div className="fullCart">
{userType === "buyer" && <Redirect to="/account/cart" />}
<div className="head">
<h1>Create Orders</h1>
</div>
<div className="allCarts">Cart is empty.</div>
<Modal open={msg} className="msg">
{msg}
</Modal>
</div>
);
};
const Shop = ({ seller, products, loading }) => {
const { user, setCart, config } = useContext(SiteContext);
const [msg, setMsg] = useState(null);
const [deliveryDetail, setDeliveryDetail] = useState({
name: user.firstName + " " + user.lastName,
phone: user.phone,
});
const [addressForm, setAddressForm] = useState(false);
const [milestoneForm, setMilestoneForm] = useState(false);
const [showTerms, setShowTerms] = useState(false);
const [couponCode, setCouponCode] = useState("");
const [validCoupon, setValidCoupon] = useState(false);
const [couponCodeForm, setCouponCodeForm] = useState(false);
const [note, setNote] = useState("");
const productPrice = products.reduce(
(a, c) =>
(
a +
calculatePrice({ product: c.product, gst: seller.gst }) * c.qty
).fix(),
0
);
const couponCodeDiscount =
(validCoupon?.type === "percent" &&
Math.min(
(productPrice / 100) * validCoupon.amount,
validCoupon.maxDiscount
)) ||
(validCoupon?.type === "flat" && validCoupon?.amount) ||
0;
const total =
+(productPrice - couponCodeDiscount) +
(seller.shopInfo?.shippingCost || 0).fix();
const fee = (total * ((100 + config.fee) / 100) - total).fix();
return (
<>
<div className="shop">
<div className="seller">
<div className="profile">
{seller.shopInfo?.logo && <Img src={seller.shopInfo?.logo} />}
<p className="name">
{seller.shopInfo?.name ||
seller.firstName + " " + seller.lastName}{" "}
• <span className="role">Seller</span>
<span className="contact">
{seller.shopInfo?.phone || seller.phone}
</span>
</p>
</div>
</div>
<div className="cart">
<ul className="items">
{products.map(({ product, qty }, i) => (
<CartItem key={i} gst={seller.gst} product={product} qty={qty} />
))}
<div className="total">
<p>
<label>Total</label>₹{productPrice}
</p>
<hr />
<div className="coupon">
{!validCoupon ? (
<label>Coupon</label>
) : (
<label>
Coupon Code {validCoupon.code}
<br />
Discount{" "}
{validCoupon.type === "percent" ? (
<>
{validCoupon.amount}% (Upto ₹{validCoupon.maxDiscount})
</>
) : (
<>flat</>
)}
</label>
)}
{!couponCodeForm && !validCoupon && (
<button onClick={() => setCouponCodeForm(true)}>
Add Coupon
</button>
)}
{validCoupon && <span>₹{couponCodeDiscount}</span>}
{couponCodeForm && (
<form
onSubmit={(e) => {
e.preventDefault();
fetch(`/api/getCoupon/${couponCode}`)
.then((res) => res.json())
.then(({ code, coupon }) => {
if (code === "ok") {
if (
!coupon.sellers ||
coupon.sellers?.filter(
(_id) => _id === seller._id
).length === 0
) {
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Err_svg />
<h4>
This seller does not accept this coupon
code.
</h4>
</div>
</>
);
} else if (total < coupon.threshold) {
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Err_svg />
<h4>
Coupon code {couponCode} can only be
applied on order more that ₹
{coupon.threshold}.
</h4>
</div>
</>
);
} else if (coupon.usage >= coupon.validPerUser) {
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Err_svg />
<h4>
Each user can use this Coupon{" "}
{coupon.validPerUser} times.
</h4>
</div>
</>
);
} else {
setValidCoupon(coupon);
setCouponCodeForm(false);
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Succ_svg />
<h4>
Coupon code {couponCode} has been applied.
</h4>
</div>
</>
);
}
} else {
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Err_svg />
<h4>Invalid Coupon code.</h4>
</div>
</>
);
}
})
.catch((err) => {
console.log(err);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>
Could not apply Coupon code. Make sure you're
online.
</h4>
</div>
</>
);
});
}}
>
<input
required={true}
value={couponCode}
onBlur={(e) => {
if (!couponCode) {
setCouponCodeForm(false);
}
}}
onChange={(e) =>
setCouponCode(e.target.value.toUpperCase())
}
/>
<button>Apply</button>
</form>
)}
</div>
<hr />
<p>
<label>Shipping</label>₹{seller.shopInfo?.shippingCost}
</p>
<p>
<label>Delivery Pay Fee {config.fee}%</label>₹{fee}
</p>
<hr />
<p>
<label>Grand total</label>₹{(total + fee).fix()}
</p>
{
// <span className="note">
// All tax and fee inclued.
// <Tip>
// Seller specified GST TAX and 10% Delivery Pay Fee applies to
// all orders.
// </Tip>
// </span>
}
</div>
<div className="terms">
<p>
<label>Refundable: </label>
{seller.shopInfo?.refundable || "N/A"}
</p>
<p>
By proceeding, I agree to seller's all{" "}
<span className="btn" onClick={() => setShowTerms(true)}>
Terms
</span>
</p>
</div>
</ul>
<span className="devider" />
<div className="deliveryDetail">
<div className="head">
<h3>Delivery Information</h3>
<button onClick={() => setAddressForm(true)}>Edit</button>
</div>
<ul>
{Object.entries(deliveryDetail).map(([key, value], i) => (
<li key={i}>
<label>{key}</label>
{value}
</li>
))}
</ul>
<div className="head">
<h3>Note to Seller</h3>
</div>
<TextareaAutosize
value={note}
onChange={(e) => setNote(e.target.value)}
/>
</div>
</div>
<div className="actions">
<button onClick={() => setMilestoneForm(true)}>Place order</button>
</div>
<Modal
open={addressForm}
head={true}
label="Delivery Address"
setOpen={setAddressForm}
className="addAddress"
>
<AddressForm
client={{
name: deliveryDetail.name,
phone: deliveryDetail.phone,
address: deliveryDetail,
}}
onSuccess={(data) => {
setDeliveryDetail((prev) => ({ ...prev, ...data.address }));
setAddressForm(false);
}}
onCancel={() => setAddressForm(false)}
/>
</Modal>
<Modal
className="milestoneRequest"
head={true}
label="Checkout"
open={milestoneForm}
setOpen={setMilestoneForm}
>
<MilestoneForm
action="create"
client={seller}
definedAmount={total + fee}
order={{
products,
deliveryDetail: {
...deliveryDetail,
deliveryWithin: seller.shopInfo?.deliveryWithin,
},
...(note && { note }),
...(validCoupon && { couponCode: validCoupon?.code }),
}}
onSuccess={({ milestone, order }) => {
setCart((prev) =>
prev.filter(({ product }) => {
return !order.products.some(
(order) => order.product._id === product._id
);
})
);
setMilestoneForm(false);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Succ_svg />
<h4>Order successfully submitted.</h4>
<Link to="/account/myShopping/orders">View All orders</Link>
</div>
</>
);
}}
/>
</Modal>
<Modal
open={showTerms}
setOpen={setShowTerms}
head={true}
label="Seller's Terms"
className="shopTerms"
>
<ul>
{seller.shopInfo?.terms?.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
</Modal>
<Modal className="msg" open={msg}>
{msg}
</Modal>
</div>
{loading && (
<div className="spinnerContainer">
<div className="spinner" />
</div>
)}
</>
);
};
const SellerShop = ({ buyer, products, loading }) => {
const { user, setSellerCart, config } = useContext(SiteContext);
const [msg, setMsg] = useState(null);
const [deliveryDetail, setDeliveryDetail] = useState({
name: buyer.firstName + " " + buyer.lastName,
phone: buyer.phone,
});
const [addressForm, setAddressForm] = useState(false);
const [milestoneForm, setMilestoneForm] = useState(false);
const [showTerms, setShowTerms] = useState(false);
const [couponCode, setCouponCode] = useState("");
const [validCoupon, setValidCoupon] = useState(false);
const [couponCodeForm, setCouponCodeForm] = useState(false);
const [note, setNote] = useState("");
const productPrice = products.reduce(
(a, c) =>
(a + calculatePrice({ product: c.product, gst: user.gst }) * c.qty).fix(),
0
);
const couponCodeDiscount =
(validCoupon?.type === "percent" &&
Math.min(
(productPrice / 100) * validCoupon.amount,
validCoupon.maxDiscount
)) ||
(validCoupon?.type === "flat" && validCoupon?.amount) ||
0;
const total =
+(productPrice - couponCodeDiscount) +
(user.shopInfo?.shippingCost || 0).fix();
const fee = (total * ((100 + config.fee) / 100) - total).fix();
return (
<>
<div className="shop">
<div className="seller">
<div className="profile">
<Img src={buyer.profileImg || "/profile-user.jpg"} />
<p className="name">
{buyer.firstName} {buyer.lastName} •{" "}
<span className="role">Buyer</span>
<span className="contact">{buyer.phone}</span>
</p>
</div>
</div>
<div className="cart">
<ul className="items">
{products.map(({ product, qty }, i) => (
<CartItem key={i} gst={user.gst} product={product} qty={qty} />
))}
<div className="total">
<p>
<label>Total</label>₹{productPrice}
</p>
<hr />
<div className="coupon">
{!validCoupon ? (
<label>Coupon</label>
) : (
<label>
Coupon Code {validCoupon.code}
<br />
Discount{" "}
{validCoupon.type === "percent" ? (
<>
{validCoupon.amount}% (Upto ₹{validCoupon.maxDiscount})
</>
) : (
<>flat</>
)}
</label>
)}
{!couponCodeForm && !validCoupon && (
<button onClick={() => setCouponCodeForm(true)}>
Add Coupon
</button>
)}
{validCoupon && <span>₹{couponCodeDiscount}</span>}
{couponCodeForm && (
<form
onSubmit={(e) => {
e.preventDefault();
fetch(`/api/getCoupon/${couponCode}`)
.then((res) => res.json())
.then(({ code, coupon }) => {
if (code === "ok") {
if (
!coupon.sellers ||
coupon.sellers?.filter((_id) => _id === user._id)
.length === 0
) {
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Err_svg />
<h4>
This seller does not accept this coupon
code.
</h4>
</div>
</>
);
} else if (total < coupon.threshold) {
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Err_svg />
<h4>
Coupon code {couponCode} can only be
applied on order more that ₹
{coupon.threshold}.
</h4>
</div>
</>
);
} else if (coupon.usage >= coupon.validPerUser) {
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Err_svg />
<h4>
Each user can use this Coupon{" "}
{coupon.validPerUser} times.
</h4>
</div>
</>
);
} else {
setValidCoupon(coupon);
setCouponCodeForm(false);
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Succ_svg />
<h4>
Coupon code {couponCode} has been applied.
</h4>
</div>
</>
);
}
} else {
setMsg(
<>
<button onClick={() => setMsg(null)}>
Okay
</button>
<div>
<Err_svg />
<h4>Invalid Coupon code.</h4>
</div>
</>
);
}
})
.catch((err) => {
console.log(err);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Err_svg />
<h4>
Could not apply Coupon code. Make sure you're
online.
</h4>
</div>
</>
);
});
}}
>
<input
required={true}
value={couponCode}
onBlur={(e) => {
if (!couponCode) {
setCouponCodeForm(false);
}
}}
onChange={(e) =>
setCouponCode(e.target.value.toUpperCase())
}
/>
<button>Apply</button>
</form>
)}
</div>
<hr />
<p>
<label>Shipping</label>₹{user.shopInfo?.shippingCost}
</p>
<p>
<label>Delivery Pay Fee {config.fee}%</label>₹{fee}
</p>
<hr />
<p>
<label>Grand total</label>₹{(total + fee).fix()}
</p>
</div>
<div className="terms">
<p>
<label>Refundable: </label>
{user.shopInfo?.refundable || "N/A"}
</p>
<p>
By proceeding, I agree to seller's all{" "}
<span className="btn" onClick={() => setShowTerms(true)}>
Terms
</span>
</p>
</div>
</ul>
<span className="devider" />
<div className="deliveryDetail">
<div className="head">
<h3>Delivery Information</h3>
<button onClick={() => setAddressForm(true)}>Edit</button>
</div>
<ul>
{Object.entries(deliveryDetail).map(([key, value], i) => (
<li key={i}>
<label>{key}</label>
{value}
</li>
))}
</ul>
<div className="head">
<h3>Note to Buyer</h3>
</div>
<TextareaAutosize
value={note}
onChange={(e) => setNote(e.target.value)}
/>
</div>
</div>
<div className="actions">
<button onClick={() => setMilestoneForm(true)}>Create order</button>
</div>
<Modal
open={addressForm}
head={true}
label="Delivery Address"
setOpen={setAddressForm}
className="addAddress"
>
<AddressForm
client={{
name: deliveryDetail.name,
phone: deliveryDetail.phone,
address: deliveryDetail,
}}
onSuccess={(data) => {
setDeliveryDetail((prev) => ({ ...prev, ...data.address }));
setAddressForm(false);
}}
onCancel={() => setAddressForm(false)}
/>
</Modal>
<Modal
className="milestoneRequest"
head={true}
label="Checkout"
open={milestoneForm}
setOpen={setMilestoneForm}
>
<MilestoneForm
action="request"
client={buyer}
definedAmount={(total + fee).fix()}
order={{
products,
deliveryDetail: {
...deliveryDetail,
deliveryWithin: user.shopInfo?.deliveryWithin,
},
...(note && { note }),
...(validCoupon && { couponCode: validCoupon?.code }),
}}
onSuccess={({ milestone, order }) => {
setSellerCart((prev) =>
prev.filter(({ product, buyer }) => {
return !order.products.find(
(order) =>
order.product._id === product._id &&
buyer === milestone.buyer._id
);
})
);
setMilestoneForm(false);
setMsg(
<>
<button onClick={() => setMsg(null)}>Okay</button>
<div>
<Succ_svg />
<h4>Order successfully submitted.</h4>
<Link to="/account/myShop/orders">Manage orders</Link>
</div>
</>
);
}}
/>
</Modal>
<Modal
open={showTerms}
setOpen={setShowTerms}
head={true}
label="Seller's Terms"
className="shopTerms"
>
<ul>
{user.shopInfo?.terms?.map((item, i) => (
<li key={i}>{item}</li>
))}
</ul>
</Modal>
<Modal className="msg" open={msg}>
{msg}
</Modal>
</div>
{loading && (
<div className="spinnerContainer">
<div className="spinner" />
</div>
)}
</>
);
};
export const CartItem = ({ product, gst, qty }) => {
const { setCart, setSellerCart, userType } = useContext(SiteContext);
const price = calculatePrice({ product, gst: gst || product.user?.gst });
return (
<li className={`item ${!product.images.length && "noImg"}`}>
<Img src={product.images[0] || "/open_box.png"} />
<div className="detail">
<p className="name">{product.name}</p>
<div className="qty">
QTY:{" "}
<div className="addRemove">
<button
onClick={() => {
if (userType === "seller") {
setSellerCart((prev) =>
prev
.map((item) => {
if (item.product._id === product._id) {
return {
...item,
qty: item.qty - 1,
};
} else {
return item;
}
})
.filter((item) => item.qty > 0)
);
} else {
setCart((prev) =>
prev
.map((item) => {
if (item.product._id === product._id) {
return {
...item,
qty: item.qty - 1,
};
} else {
return item;
}
})
.filter((item) => item.qty > 0)
);
}
}}
>
<Minus_svg />
</button>
{qty}
<button
onClick={() => {
if (userType === "seller") {
setSellerCart((prev) =>
prev.map((item) => {
if (item.product._id === product._id) {
return {
...item,
qty: item.qty + 1,
};
} else {
return item;
}
})
);
} else {
setCart((prev) =>
prev.map((item) => {
if (item.product._id === product._id) {
return {
...item,
qty: item.qty + 1,
};
} else {
return item;
}
})
);
}
}}
>
<Plus_svg />
</button>
</div>
</div>
</div>
<div className="price">
<span className="qty">
{price} x {qty}
</span>
₹{(price * qty).fix()}
</div>
{gst?.verified && <Tip>Including {product.gst}% GST.</Tip>}
</li>
);
};
export default Marketplace;
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _jquery = __webpack_require__(1);
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _jquery2.default)(document).ready(function () {
(0, _jquery2.default)('[data-toggle="tooltip"]').tooltip();
if ((0, _jquery2.default)('#indexSlider').length > 0) {
(0, _jquery2.default)('#indexSlider').owlCarousel({
items: 1,
autoHeight: true,
dots: false,
nav: true
});
}
if ((0, _jquery2.default)('.js-placeholder-search').length > 0) {
(0, _jquery2.default)('.js-placeholder-search').select2();
}
if ((0, _jquery2.default)('.js-placeholder-single').length > 0) {
(0, _jquery2.default)('.js-placeholder-single').select2({
minimumResultsForSearch: 10
});
}
// filter
(0, _jquery2.default)(".filter__item").on("click", function () {
var filter = (0, _jquery2.default)(this).attr("id");
var leftFilterContainer = (0, _jquery2.default)(".filter .container").offset().left;
var leftFilter = (0, _jquery2.default)(this).offset().left;
(0, _jquery2.default)(".filter-dropdown").each(function () {
if ((0, _jquery2.default)(this).data("filter") === filter) {
(0, _jquery2.default)(this).css("left", leftFilter - leftFilterContainer);
(0, _jquery2.default)(this).slideToggle();
} else {
(0, _jquery2.default)(this).css("display", "none");
}
});
});
(0, _jquery2.default)(".filter__item#filter-security").on("click", function () {
(0, _jquery2.default)(this).toggleClass("filter__item--active");
});
(0, _jquery2.default)(window).scroll(function () {
if ((0, _jquery2.default)(this).scrollTop() > 150) {
// $('#scroll_top').css('opacity','1');
(0, _jquery2.default)('.sticky-top').addClass("scroll");
(0, _jquery2.default)('.sticky-top .header-top').slideUp();
} else if ((0, _jquery2.default)(this).scrollTop() < 60) {
// $('#scroll_top').css('opacity','0');
(0, _jquery2.default)('.sticky-top').removeClass("scroll");
(0, _jquery2.default)('.sticky-top .header-top').slideDown();
}
});
});
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = jQuery;
/***/ })
/******/ ]); |
import { SAVE_DATA} from "../action/weather";
const initialState={
list:[]
}
export default (state=initialState,action)=>
{
switch(action.type)
{
case SAVE_DATA:
{
state.list=action.data
return{
data:state.list
}
}
default:
return state
}
} |
// Initial state
/*
userId: string,
*/
const initialState = {
userId: ''
}
// Action types
const SET_USER_ID = 'account/set_user_id'
// Action creators
export const accountActions = {
setUserId: userId => ({ type: SET_USER_ID, userId })
}
// Reducer
export function accountReducer (state = initialState, action) {
switch (action.type) {
case SET_USER_ID: {
return { ...state, userId: action.userId }
}
default: {
return state
}
}
}
|
import React, { Component } from 'react';
import {
Link,
} from 'react-router-dom';
import API from '../utils/API'
class Profile extends Component {
state = {
user: {},
location: 'profile',
discovers: []
};
componentDidMount() {
this.loadInfo(this.props.match.params.id);
}
loadInfo = id => {
API.getUser(id)
.then(res => this.setState({ user: res.data }))
.catch(err => console.log(err));
};
locationHandler = local => {
this.setState({location: local});
}
handlePlayerFormSubmit = event => {
event.preventDefault();
if (this.state.user.firstName && this.state.user.lastName) {
API.updateUser( this.state.user._id, {
firstName: this.state.user.firstName,
lastName: this.state.user.lastName,
heroesOfTheStorm: this.state.user.heroesOfTheStorm,
gamerTag: this.state.user. gamerTag,
rank: this.state.user.rank,
heroesOfTheStormPrimary: this.state.user.heroesOfTheStormPrimary,
heroesOfTheStormSecondary: this.state.user.heroesOfTheStormSecondary,
age: this.state.user.age,
city: this.state.user.city,
state: this.state.user.state
})
.then(res => console.log(res))
.catch(err => console.log(err));
}
};
handleUniversityFormSubmit = event => {
event.preventDefault();
if (this.state.user.schoolName) {
API.updateUser( this.state.user._id, {
schoolName: this.state.user.schoolName,
scoutName: this.state.user.scoutName,
coach: this.state.user.coach,
heroesOfTheStormOffered: this.state.user.heroesOfTheStormOffered,
overwatchOffered: this.state.user.overwatchOffered,
leagueOfLegendsOffered: this.state.user.leagueOfLegendsOffered,
schoolCity: this.state.user.schoolCity,
schoolState: this.state.user.schoolState,
})
.then(res => console.log(res))
.catch(err => console.log(err));
}
};
handleInputChange = event => {
const { name, value } = event.target;
let user = {...this.state.user}
user[name] = value
this.setState({user
});
};
pressMe = () => {
console.log(this.state)
}
trueFalse = (name, v) => {
let user = {...this.state.user}
user[name] = v
this.setState({user
})
}
discoverUniversities = event => {
event.preventDefault();
API.getSpecificUsers({type: 'university'})
.then(res => this.setState({discovers: res.data}))
.catch(err => console.log(err));
}
discoverPlayers = event => {
event.preventDefault();
API.getSpecificUsers({type: 'player'})
.then(res => this.setState({discovers: res.data}))
.catch(err => console.log(err));
}
signOut = () => {
API.signOut()
.then(res => console.log(res))
.catch(err => console.log(err));
};
render() {
return (
<div>
<header>
<button type='submit' onClick={() => this.signOut()}>Sign Out</button>
</header>
<nav>
<ul>
<li onClick={() => this.locationHandler('profile')}>Profile</li>
<li onClick={() => this.locationHandler('discover')}>Discover</li>
</ul>
</nav>
{this.state.user._id === this.props.match.params.id && this.state.user.type === 'player' && this.state.location==='profile' ? (
<div>
<main>
<form>
First name:<br />
<input type='text' name="firstName" defaultValue={this.state.user.firstName}
onChange={this.handleInputChange}/>
<br />
Last name:<br />
<input name="lastName" defaultValue={this.state.user.lastName}
onChange={this.handleInputChange} />
<br />
Heroes of the Storm:<br />
<button type='button' onClick={() => this.trueFalse('heroesOfTheStorm', true)}>yes</button>
<button type='button' onClick={() =>this.trueFalse('heroesOfTheStorm', false)}>no</button>
<br />
Gamer Tag:<br />
<input name="gamerTag" defaultValue={this.state.user.gamerTag}
onChange={this.handleInputChange} />
<br />
{this.state.user.heroesOfTheStorm ? (
<div>
Primary Heroes of the Storm Role:<br />
<input name="heroesOfTheStormPrimary" defaultValue={this.state.user.heroesOfTheStormPrimary}
onChange={this.handleInputChange}/>
<br />
Secondary Heroes of the Storm Role:<br />
<input name="heroesOfTheStormSecondary" defaultValue={this.state.user.heroesOfTheStormSecondary}
onChange={this.handleInputChange}/>
<br />
</div>
):(<div></div>)}
<br />
Rank:<br />
<input name="rank" defaultValue={this.state.user.rank}
onChange={this.handleInputChange}/>
<br />
Age:<br />
<input name="age" defaultValue={this.state.user.age}
onChange={this.handleInputChange}/>
<br />
City:<br />
<input name="city" defaultValue={this.state.user.city}
onChange={this.handleInputChange}/>
<br />
State:<br />
<input name="state" defaultValue={this.state.user.state}
onChange={this.handleInputChange}/>
<br />
<br />
<button type='submit' onClick={this.handlePlayerFormSubmit}>Update</button>
</form>
</main>
</div>
) :
this.state.user._id === this.props.match.params.id && this.state.user.type === 'university' && this.state.location==='profile' ?(
<div>
<main>
<form>
School Name:<br />
<input type='text' name="schoolName" defaultValue={this.state.user.schoolName}
onChange={this.handleInputChange}/>
<br />
Head Coach:<br />
<input name="coach" defaultValue={this.state.user.coach}
onChange={this.handleInputChange} />
<br />
Head Scout:<br />
<input name="scoutName" defaultValue={this.state.user.scoutName}
onChange={this.handleInputChange} />
<br />
Heroes of the Storm:<br />
<button type='button' onClick={() => this.trueFalse('heroesOfTheStormOffered', true)}>yes</button>
<button type='button' onClick={() =>this.trueFalse('heroesOfTheStormOffered', false)}>no</button>
<br />
Overwatch:<br />
<button type='button' onClick={() => this.trueFalse('overwatchOffered', true)}>yes</button>
<button type='button' onClick={() =>this.trueFalse('overwatchOffered', false)}>no</button>
<br />
League of Legends:<br />
<button type='button' onClick={() => this.trueFalse('leagueOfLegendsOffered', true)}>yes</button>
<button type='button' onClick={() =>this.trueFalse('leagueOfLegendsOffered', false)}>no</button>
<br />
City:<br />
<input name="schoolCity" defaultValue={this.state.user.schoolCity}
onChange={this.handleInputChange}/>
<br />
State:<br />
<input name="schoolState" defaultValue={this.state.user.schoolState}
onChange={this.handleInputChange}/>
<br />
<br />
<button type='submit' onClick={this.handleUniversityFormSubmit}>Update</button>
</form>
</main>
</div>
) :
this.state.user._id === this.props.match.params.id && this.state.user.type === 'player' && this.state.location==='discover' ? (
<div>
<button type='submit' onClick={this.discoverUniversities}>Discover</button>
{this.state.discovers.length ? (<ul>
{this.state.discovers.map(discovered => (
<li key={discovered._id}>
<h1>
<strong>
{discovered.schoolName} {discovered.schoolCity}, {discovered.schoolState} <br />
</strong>
</h1>
<h3>Esports available on campus</h3>
<ul>
{discovered.overwatchOffered ? (<li>Overwatch</li>):(<div></div>)}
{discovered.heroesOfTheStormOffered ? (<li>Hero of the Storm</li>):(<div></div>)}
{discovered.leagueOfLegendsOffered ? (<li>League of Legends</li>):(<div></div>)}
</ul>
<span>Coach {discovered.coach}</span> <br />
<span>Scout {discovered.scoutName}</span>
</li>
))}
</ul>) : ( <h3>No Results to Display</h3>)}
</div>
) :
this.state.user._id === this.props.match.params.id && this.state.user.type === 'university' && this.state.location==='discover' ? (
<div>
<button type='submit' onClick={this.discoverPlayers}>Discover</button>
{this.state.discovers.length ? (<ul>
{this.state.discovers.map(discovered => (
<li key={discovered._id}>
<h1>
<strong>
{discovered.firstName} "{discovered.gamerTag}" {discovered.lastName} <br />
</strong>
</h1>
<h3>Games Played</h3>
<ul>
{discovered.heroesOfTheStorm ? (
<div>
<div>Primary Role: {discovered.heroesOfTheStormPrimary}</div>
<div>Secondary Role: {discovered.heroesOfTheStormSecondary}</div>
</div>):(<div></div>)}
</ul>
<span>age {discovered.age}</span> <br />
<span>city {discovered.city}</span> <span>state {discovered.state}</span>
</li>
))}
</ul>) : ( <h3>No Results to Display</h3>)}
</div>) : (
<div>
nothing for you!
</div>
)}
<button onClick={() => this.pressMe()}>
press me
</button>
</div>
);
}
}
export default Profile;
|
import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import styles from 'Lesson/components/stylesheets/LessonPagination.scss';
const { array, number } = PropTypes;
/**
* Build the links for pagination
*
* @param {Object} lesson - The current lesson
* @param {Number} index - The current index from looping through the props.lessons array
* @param {Number} lessonIndex - The index of the current lesson in the array of lessons
*
* @return {Object} Link - React Router Link component, wrapped in <li>'s, with appropriate slug
*
* @since 1.0.0
*/
const renderLinks = (lesson, index, lessonIndex) => {
const c1ass = (index === lessonIndex) ? `${ styles.active }` : '';
const { slug } = lesson;
const label = index + 1;
return (
<li className={ `${ styles.item } ${ c1ass }` } key={ index }>
<Link
to={ slug }
id={ slug }
className={ styles.link }>
{ label }
</Link>
</li>
);
};
/**
* The Lesson pagination component
*
* @param {Object} props - The React props object
*
* @since 1.0.0
*/
const LessonPagination = (props) => {
const { lessons, lessonIndex } = props;
const links = lessons.map((lesson, index) => renderLinks(lesson, index, lessonIndex));
return <ul className={ `${ styles.page } lesson-pagination` }>{ links }</ul>;
};
LessonPagination.propTypes = {
lessons: array,
lessonIndex: number
};
export default LessonPagination;
|
import { isVoucherProduct, withLocalState, clientCartItemForAPI } from './utils'
/**
* Getters are used to avoid logic duplication that depends on the state
* FYI: https://vuex.vuejs.org/guide/getters.html
*/
export default {
totalItemsWithoutDiscount: (state) => {
const cart = (state.serverBasket?.cart || [])
.map(cartItem => withLocalState(state.clientBasket.cart, cartItem))
.filter(Boolean);
return cart
.filter(p => !isVoucherProduct(p))
.reduce(
(acc, curr) => {
return {
gross: acc.gross + (curr.price.gross * curr.quantity),
net: acc.net + (curr.price.net * curr.quantity),
quantity: acc.quantity + curr.quantity
};
},
{
gross: 0,
quantity: 0
}
);
},
clientCart: (state) => {
return state.clientBasket.cart.map(clientCartItemForAPI)
},
basketModel: (state, getters) => locale => {
return {
locale,
cart: getters.clientCart,
};
}
} |
import ContactList from '../ContactList/ContactList';
import { useDeleteContactMutation } from "../../redux/contactSlice";
export const ContactItem = ({ contacts }) => {
const [deleteContact, { isLoading: isDeleting }] = useDeleteContactMutation();
return <div>{contacts && <ContactList contacts={contacts} onDelete={deleteContact} deleting={isDeleting} />}</div>
}; |
//MODEL
/*----- constants -----*/
/*----- app's state (variables) -----*/
let result, operated, clickedNum, clickedOperator, num1, num2, previousOperator;
let selected_nums = [];
//CONTROLLER
/*----- cached element references -----*/
//data binding
const displayEl = document.getElementById('display');
const calcButtonsEl = document.getElementById('calc-buttons')
const circlesEls = document.getElementsByClassName('circle');
const buttonEl = document.querySelector('button');
/*----- event listeners -----*/
calcButtonsEl.addEventListener('click', handleClick);
buttonEl.addEventListener('click', init)
/*----- functions -----*/
init(); //call function so that immediately on game mode start game then
//calling render and visualizing data to the dom
function init() {
result = 0;
num1 = 0;
num2 = null;
operated = false;
render();
}
function handleClick(e) {
//get integer equivalent of button clicked
clickedNum = parseInt(e.target.innerText);
//if it's not a number, but one of the operators or decimal point
if (Number.isNaN(clickedNum)) {
//if it is a decimal
if (e.target.innerText === '.') {
console.log('decimal');
//add to array of selected nums
selected_nums.push(clickedNum);
}
//if it's not a decimal (and still not a number)
else {
//get operator sign
clickedOperator = e.target.innerText;
console.log(clickedOperator);
//call the operator function
handleOperation();
//set operator check to true
operated = true;
selected_nums = [];
//get text value of button clicked
}
}
//else if it is a number
else {
if (operated === false) {
//push all numbers into the numbers array
selected_nums.push(clickedNum);
num1 = parseInt(selected_nums.join(''));
console.log(num1);
}
else {
//push all numbers into the numbers array
selected_nums.push(clickedNum);
num2 = parseInt(selected_nums.join(''));
console.log(num2);
}
}
render();
}
//when we click on an operater, change operated to true and completed operator function
function handleOperation() {
if (clickedOperator === '=') {
if (previousOperator === '+') {
result = num1 + num2;
console.log(result);
}
else if (previousOperator === '-') {
result = num1 - num2;
console.log(result);
}
else if (previousOperator === 'x') {
result = num1 * num2;
console.log(result);
}
else if (previousOperator === '÷') {
result = num1/num2;
console.log(result);
}
}
previousOperator = clickedOperator;
selected_nums = [];
};
function render() {
if (operated === false) {
displayEl.textContent = num1;
}
else if (!num2) {
displayEl.textContent = `${num1}${previousOperator}`;
}
else if (previousOperator !== '=') {
displayEl.textContent = `${num1}${previousOperator}${num2}`;
}
else {
displayEl.textContent = result;
}
} |
// JavaScript Document
var PageManagement = function () {
this.Pages = {
index: false,
overview: false,
socialwork: false,
eco: false,
edu: false,
culture: false,
food: false,
tradition: false,
history: false,
figure: false,
poi: false,
geo: false,
bbs: false
};
this.Names = {
index: '主页',
overview: '概览',
socialwork: '社会事业',
eco: '经济产业',
edu: '教育事业',
culture: '文化基因',
food: '食系茂名',
tradition: '传统习俗',
history: '历史记忆',
figure: '历史名家',
poi: '遗迹名胜',
geo: '地理位置',
bbs: 'BBS'
}
this.init = function () {
let url = window.location.href;
let index1 = url.lastIndexOf("\/");
let index2 = url.indexOf(".html");
let page = url.substring(index1+1, index2);
this.Pages[page] = true;
switch (page) {
case 'eco':
case 'edu':
this.Pages['socialwork'] = true;
break;
case 'food':
case 'tradition':
this.Pages['culture'] = true;
break;
case 'figure':
case 'poi':
this.Pages['history'] = true;
}
}
}
var pm = new PageManagement();
pm.init();
Vue.component('globalnav', {
data: function () {
let isActive = {
'overview': pm.Pages['overview'],
'socialwork': pm.Pages['socialwork'],
'culture': pm.Pages['culture'],
'history': pm.Pages['history'],
};
let noFixedPages = {
'eco': pm.Pages['eco'],
'edu': pm.Pages['edu'],
'food': pm.Pages['food'],
'tradition': pm.Pages['tradition'],
'figure': pm.Pages['figure'],
'poi': pm.Pages['poi'],
'bbs': pm.Pages['bbs']
};
let isFixed = false;
for (var key in noFixedPages) {
isFixed = isFixed || noFixedPages[key];
}
isFixed = !isFixed;
return {
isActive: isActive,
isFixed: isFixed,
isOpacity: false
}
},
mounted: function () {
window.addEventListener('scroll', this.opacityProc, true);
},
methods: {
getScrollTop: function () {
return document.documentElement.scrollTop;
},
opacityProc: function () {
if (this.getScrollTop() > 104) {
this.isOpacity = true;
} else {
this.isOpacity = false;
}
},
getFocus: function () {
this.isOpacity = false;
},
loseFocus: function () {
if (this.getScrollTop() == 0)
this.isOpacity = false;
else {
this.isOpacity = true;
}
}
},
template: `
<div v-bind:class="[{'gn-fixed': isFixed}, {'gn-opacity': isOpacity},'gn']" @mouseenter="getFocus" @mouseleave="loseFocus">
<nav class="gn-list">
<li class="gn-item gn-index"><a class="gn-link" href="index.html"><span class="gn-link-text">myHometownMaoming-link</span></a></li>
<li class="gn-item"><a href="overview.html" v-bind:class="[{'gn-link-active': isActive['overview']}, 'gn-link']">概览</a></li>
<li class="gn-item"><a href="socialwork.html" v-bind:class="[{'gn-link-active': isActive['socialwork']}, 'gn-link']">社会事业</a></li>
<li class="gn-item"><a href="culture.html" v-bind:class="[{'gn-link-active': isActive['culture']}, 'gn-link']">文化基因</a></li>
<li class="gn-item"><a href="history.html" v-bind:class="[{'gn-link-active': isActive['history']}, 'gn-link']">历史记忆</a></li>
<li class="gn-item gn-geo"><a class="gn-link" href="geo.html"><span class="gn-link-text">geo-link</span></a></li>
<li class="gn-item gn-bbs"><a class="gn-link" href="bbs.html"><span class="gn-link-text">BBS-link</span></a></li>
</nav>
</div>
`
});
var breadcrumbs = {
data: function () {
let seen = true;
let shown = true;
let path = [];
let page_path = [];
let en = false;
for (var key in pm.Pages) {
if (pm.Pages[key]) {
path.push(pm.Names[key]);
page_path.push('./' + key + '.html');
}
}
if (path[0] == '主页') {
path.splice(0, 1);
seen = false;
}
if (path[0] == 'BBS') {
en = true;
}
if (path.length == 1) {
shown = false;
page_path = null;
} else {
page_path = page_path[0];
}
return {
seen: seen,
shown: shown,
path: path,
page_path: page_path,
en: en
}
},
template: `
<ul class="bc-list" v-if="seen">
<li class="bc-item bc-index"><a class="bc-link" href="index.html"><span class="bc-link-text">index</span></a></li>
<li class="bc-item"> > <a class="bc-link" v-bind:href="page_path" v-bind:class="{'bc-link-active': shown, 'bc-en': en}">{{path[0]}}</a></li>
<li class="bc-item" v-if="shown"> > <a class="bc-link">{{path[1]}}</a></li>
</ul>
`
};
Vue.component('globalft', {
data: function () {
let isIndex = pm.Pages['index'];
return {
isIndex: isIndex
}
},
components: {
'breadcrumbs': breadcrumbs
},
template: `
<footer class="gf">
<breadcrumbs></breadcrumbs>
<ul v-bind:class="[{'gf-directory-padding-top': isIndex}, 'gf-directory']">
<ul class="gf-dir-list">
<li class="gf-dir-item"><span class="gf-dir-text">探索茂名</span></li>
<li class="gf-dir-item"><a class="gf-link" href="overview.html">概览</a></li>
<li class="gf-dir-item"><a class="gf-link" href="socialwork.html">社会事业</a></li>
<li class="gf-dir-item"><a class="gf-link" href="culture.html">文化基因</a></li>
<li class="gf-dir-item"><a class="gf-link" href="history.html">历史记忆</a></li>
</ul>
<ul class="gf-dir-list">
<li class="gf-dir-item"><span class="gf-dir-text">地图标记</span></li>
<li class="gf-dir-item"><a class="gf-link" href="geo.html">地理位置</a></li>
</ul>
<ul class="gf-dir-list">
<li class="gf-dir-item"><span class="gf-dir-text">论坛交流</span></li>
<li class="gf-dir-item"><a class="gf-link gf-en" href="bbs.html">BBS</a></li>
</ul>
</ul>
<hr class="gf-hr"/>
<address class="gf-addr">
<span class="gf-mail">联系开发者: <a class="gf-mail-link gf-en" href="mailto:2369798299@qq.com">2369798299@qq.com</a>
</span>
<span class="gf-author gf-en">Developer: <a class="gf-author-text">ZengJia</a>
</span>
</address>
</footer>
`
});
var app_nav = new Vue({
el: '#globalnav'
});
var app_ft = new Vue({
el: '#globalft'
}); |
const api = '90d73af0184663460f0bd390765aade9';
//get html parts
const iconImg = document.querySelector('.weather-icon');
const loc = document.querySelector('#location');
const tempF = document.querySelector('.f');
const desc = document.querySelector('.desc');
const sunriseDOM = document.querySelector('.sunrise');
const sunsetDOM = document.querySelector('.sunset');
window.addEventListener('load', () => {
if(navigator.geolocation){
let long;
let lat;
navigator.geolocation.getCurrentPosition((position) => {
long = position.coords.longitude;
lat = position.coords.latitude;
const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api}&units=metric`;
//check check
console.log(base);
fetch(base)
.then((response)=> {
return response.json();
})
.then((data) => {
//check check
console.log(data);
const place = data.name;
const temp = data.main.temp;
const {description, icon} = data.weather[0];
const { sunrise, sunset } = data.sys;
const iconUrl = `https://openweathermap.org/img/wn/${icon}@4x.png`;
const fahrenheit = (temp * 9) / 5 + 32;
const sunriseGMT = new Date(sunrise * 1000);
const sunsetGMT = new Date(sunset * 1000);
//interacting with html
iconImg.src = iconUrl;
loc.textContent = `${place}`;
desc.textContent = `${description}`;
tempF.textContent = `${fahrenheit.toFixed(1)}°`;
sunriseDOM.textContent = `Sunrise: ${sunriseGMT.toLocaleDateString()}, ${sunriseGMT.toLocaleTimeString()}`;
sunsetDOM.textContent = `Sunset: ${sunsetGMT.toLocaleDateString()}, ${sunsetGMT.toLocaleTimeString()}`;
});
});
}
});
//Getting Date and Time
function doDate() {
//arrays for month and date
var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
//create new Date info
var now = new Date();
let hour = (now.getHours() + 24) % 12 || 12;
//am or pm?
let stamp = "am";
if(now.getHours() >= 12){
stamp = "pm";
}
let min = now.getMinutes();
if(now.getMinutes() <= 9){
min = "0" + now.getMinutes();
}
//Attaching to HTML
document.querySelector(".date").textContent = `${months[now.getMonth()]} ${now.getDate()}, ${now.getFullYear()}`;
document.querySelector(".day").textContent = `${days[now.getDay()]}`;
document.querySelector(".time").textContent = `${hour}:${min} ${stamp}`;
}
//Every 30 Seconds, Refresh
setInterval(doDate, 3000); |
/*
* @Author: dlidala
* @Github: https://github.com/dlidala
* @Date: 2017-04-25 13:58:41
* @Last Modified by: dlidala
* @Last Modified time: 2017-04-25 14:10:22
*/
'use strict'
|
import React, { Component } from 'react';
import './stylesheets/App.css'
import { Segment } from 'semantic-ui-react';
import WestworldMap from './components/WestworldMap'
import Headquarters from './components/Headquarters'
let areaUrl = 'http://localhost:4000/areas'
let hostUrl = 'http://localhost:4000/hosts'
class App extends Component {
constructor(){
super()
this.state = {
areaData: [],
hostData: [],
selectedHost: {},
dropDownOptions: {}
}
}
componentDidMount(){
fetch(areaUrl).then(res => res.json()).then((data) => {
this.setState({ areaData: data });
const dropDownOptions = data.map((area)=> {
return {key: area.name, text: area.name, value: area.name}
})
this.setState({dropDownOptions: dropDownOptions}, () => console.log(this.state))
})
fetch(hostUrl).then(res => res.json()).then(hosts => this.setState({ hostData: hosts }))
}
handleSelectedHostClick = (host) => {
this.setState({selectedHost: host})
}
// As you go through the components given you'll see a lot of functional components.
// But feel free to change them to whatever you want.
// It's up to you whether they should be stateful or not.
render(){
return (
<Segment id='app'>
<WestworldMap areaState={this.state.areaData} hostState={this.state.hostData}/>
<Headquarters hostState={this.state.hostData} handleSelectedHostClick={this.handleSelectedHostClick} selectedHost={this.state.selectedHost} areaState={this.state.areaData} dropDownOptions={this.state.dropDownOptions}/>
{/* What components should go here? Check out Checkpoint 1 of the Readme if you're confused import headquarters list later*/}
</Segment>
)
}
}
export default App;
|
import React from 'react';
import '../../App.css';
import './Header.css';
import Logo from '../../img/logo.png';
import Lupa from '../../img/lupa.png';
import Aa from '../../img/Aa.png';
import Notificacion from '../../img/notificacion01.png';
import Foto from '../../img/foto.png';
import FlechaAbajo from '../../img/flechaAbajo.png';
const Header = () => {
return (
<header className="col-12">
<div className="col-3 logoContainer">
<img src={Logo} alt="logo" className="logo" />
</div>
<nav className="col-9 navigation">
<input type="search" placeholder="Buscar" className="search" />
<button type="button" className="btnSearch">
<img src={Lupa} alt="lupa" className="icon" />
</button>
<button type="button" className="btnCircle">
<img src={Aa} alt="accesibilidad" className="icon" />
</button>
<button type="button" className="btnCircle">
<img src={Notificacion} alt="notificacion" className="icon" />
</button>
<div className="imgCircle">
<img src={Foto} alt="fotoPerfil" className="icon" />
</div>
<div className="profile">
<h3>Julieta Salgado</h3>
<h4>julietasalgado@gmail.com</h4>
</div>
<button type="button" className="btnTransparent">
<img src={FlechaAbajo} alt="flecha" className="icon" />
</button>
</nav>
</header>
);
};
export default Header;
|
$(document).ready(function(){
$(".wl").click(function(){
$(".wl1").animate({marginTop:"-450px"});
$(".big").height(1750);
});
$(".la").click(function(){
$(".wl1").animate({marginTop:"-862px"});
$(".big").height(1338);
});
$(".nj").click(function(){
$(".wl1").animate({marginTop:"-1274px"});
$(".big").height(926);
});
$(".jr").click(function(){
$(".wl1").animate({marginTop:"-1686px"});
$(".big").height(514);
});
});
|
import parseEntries from './parseEntries.js';
import extractIcon from './extractIcon.js';
let icons;
const iconsDiv = document.getElementById('iconsDiv');
icons = await parseEntries(message => iconsDiv.textContent = message);
if (location.search) {
document.getElementsByName('search')[0].value = location.search.slice('?'.length);
}
document.getElementsByName('search')[0].addEventListener('input', event => {
history.replaceState(null, null, '?' + event.currentTarget.value);
renderList();
windowList();
});
let scrollTimeout;
let lastScroll;
renderList();
windowList();
window.addEventListener('scroll', handleWindowScroll, { passive: true /* We do not need `preventDefault` */ });
// Handle `resize` for debugging responsive layout, no harm done leaving this in
window.addEventListener('resize', handleWindowScroll, { passive: true /* We do not need `preventDefault` */ });
function renderList() {
let filteredIcons = icons;
if (location.search) {
filteredIcons = {};
const filter = location.search.slice('?'.length);
const keys = Object.keys(icons).filter(icon => icon.toUpperCase().includes(filter.toUpperCase()));
for (const key of keys) {
filteredIcons[key] = icons[key];
}
resultsDiv.textContent = `Showing ${Object.keys(filteredIcons).length} matching icons`;
}
else {
resultsDiv.textContent = `Showing all ${Object.keys(icons).length} icons`;
}
const iconsDiv = document.getElementById('iconsDiv');
iconsDiv.innerHTML = '';
const fragment = document.createDocumentFragment();
for (let key of Object.keys(filteredIcons)) {
const iconDiv = document.createElement('div');
iconDiv.className = 'iconDiv';
iconDiv.id = key;
fragment.append(iconDiv);
}
iconsDiv.append(fragment);
}
async function handleDownloadButtonClick(event) {
const name = event.currentTarget.dataset.name;
const type = event.currentTarget.dataset.type;
const dimension = event.currentTarget.dataset.dimension;
if (type === 'ico') {
alert('Sorry, ICO downloads are not available at the moment. Contact me at tomas@hubelbauer.net');
return;
}
const url = await extractIcon(icons, name, dimension);
const downloadA = document.getElementById('downloadA');
downloadA.href = url;
downloadA.target = '_blank';
downloadA.download = `${name}-${dimension}.${type}`;
downloadA.click();
}
function renderItem(fileName) {
const iconDiv = document.getElementById(fileName);
// Ignore if this is being called while the list is being rebuilt (`innerHTML = ''`)
if (iconDiv === null) {
return;
}
// Double check the element is still on the screen since it has been requested
const boundingClientRect = iconDiv.getBoundingClientRect();
if (boundingClientRect.bottom < 0 && boundingClientRect.top > window.innerHeight) {
// Bail if the element has not been on the screen long enough
return;
}
if (iconDiv.textContent !== '') {
// Bail since this item has already been rendered
return;
}
const icon16Img = document.createElement('img');
icon16Img.title = fileName + ' 16';
icon16Img.className = 'icon16';
extractIcon(icons, fileName, '16')
.then(url => icon16Img.src = url)
.catch(console.log)
;
const icon32Img = document.createElement('img');
icon32Img.title = fileName + ' 32';
icon32Img.className = 'icon32';
extractIcon(icons, fileName, '32')
.then(url => icon32Img.src = url)
.catch(console.log)
;
const nameA = document.createElement('a');
nameA.textContent = fileName.replace(/_/g, ' ');
nameA.href = `icon.html#${fileName}`;
nameA.target = '_blank';
const png16Button = document.createElement('button');
png16Button.textContent = '16\npng';
png16Button.dataset.name = fileName;
png16Button.dataset.type = 'png';
png16Button.dataset.dimension = '16';
png16Button.addEventListener('click', handleDownloadButtonClick);
const png32Button = document.createElement('button');
png32Button.textContent = '32\npng';
png32Button.dataset.name = fileName;
png32Button.dataset.type = 'png';
png32Button.dataset.dimension = '32';
png32Button.addEventListener('click', handleDownloadButtonClick);
const ico16Button = document.createElement('button');
ico16Button.textContent = '16\nico';
ico16Button.dataset.name = fileName;
ico16Button.dataset.type = 'ico';
ico16Button.dataset.dimension = '16';
ico16Button.addEventListener('click', handleDownloadButtonClick);
const ico32Button = document.createElement('button');
ico32Button.textContent = '32\nico';
ico32Button.dataset.name = fileName;
ico32Button.dataset.type = 'ico';
ico32Button.dataset.dimension = '32';
ico32Button.addEventListener('click', handleDownloadButtonClick);
iconDiv.append(icon16Img, icon32Img, nameA, png16Button, png32Button, ico16Button, ico32Button);
}
function windowList() {
const iconDivs = [...document.getElementsByClassName('iconDiv')];
if (window.scrollY < lastScroll) {
iconDivs.reverse();
}
for (const iconDiv of iconDivs) {
const boundingClientRect = iconDiv.getBoundingClientRect();
if (boundingClientRect.bottom >= 0 && boundingClientRect.top <= window.innerHeight) {
if (iconDiv.textContent === '') {
// Render the item if it sticks on the screen for at least tenth of a second
window.setTimeout(renderItem, 100, iconDiv.id);
}
} else {
// Clear the element if rendered but not visible
if (iconDiv.textContent !== '') {
// Release the object URLs to avoid leaking their memory
iconDiv.querySelectorAll('img').forEach(img => URL.revokeObjectURL(img.src));
iconDiv.textContent = '';
}
}
}
// Mark the timeout as expired so another scroll stroke can initiate a render
scrollTimeout = undefined;
lastScroll = window.scrollY;
}
function handleWindowScroll() {
if (!scrollTimeout) {
scrollTimeout = window.setTimeout(windowList, 100);
return;
}
// Ignore this scroll stroke if we are already set to render
}
|
const bodyParser = require("body-parser");
const express = require("express");
const cors = require("cors");
const path = require('path');
const fs = require('fs');
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');
const port = 8001;
/*---------------------------------------*/
/*START SERVER*/
/*---------------------------------------*/
const server = express();
server.listen(port, ()=>{console.log(`Server available at http://localhost:${port}`)});
server.use(express.json());
server.set('trust proxy', true);
/*---------------------------------------*/
/*HIDE THE X-POWERED-BY TO AVOID ATTACKERS TO KNOW WHAT TECH POWERS OUR SERVER*/
/*---------------------------------------*/
server.disable('x-powered-by');
/*---------------------------------------*/
/*SET CORS*/
/*---------------------------------------*/
server.use(cors());
/*list of allowed domains*/
var allowedOrigins = [
'file://',
`chrome-extension://aejoelaoggembcahagimdiliamlcdmfm`,
`http://localhost:${port}`,
`http://localhost:8080`,
`http://localhost`,
];
server.use(cors({
credentials: true,
origin: function (origin, callback) {
// allow requests with no origin
// (like mobile apps or curl requests)
if (!origin) return callback(null, true)
if (allowedOrigins.indexOf(origin) === -1) {
const msg = 'The CORS policy for this site does not allow access from the specified Origin.'
return callback(msg, false)
}
return callback(null, true)
}
}));
/*---------------------------------------*/
/*USE BODY PARSER FOR READING DATA SENT VIA AJAX FROM --CLIENTS*/
/*---------------------------------------*/
/*set the body parser this will enable the app to read form-url-encoded data as objects*/
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
/*handle body parser invalid JSON format*/
server.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
// Bad request
return res.status(400).send({ message: 'Invalid JSON format!' });
}
return next();
});
/*---------------------------------------*/
/* Test begins here */
/*---------------------------------------*/
/* generates a key */
let secret = '';
server.get('/get-key', (req, res, next)=>{
const key = speakeasy.generateSecret();
secret = key.base32;
res.send({secret, key});
});
/* Generates the qr code in image file or base 64 format */
server.get('/generate-qr', (req, res) => {
const username = req.query.username || 'johndoe@example.com';
const issuer = req.query.issuer || 'PSSLAI';
const asFile = req.query.asFile;
const otppauth = `otpauth://totp/${issuer}:${username}?secret=${secret}&issuer=${issuer}`;
QRCode.toDataURL(otppauth, function (err, data) {
// path
const qrPath = path.join(__dirname, `/qrfile.png`);
if (asFile === 'true') {
// Remove header
let base64Image = data.split(';base64,').pop();
fs.writeFileSync(qrPath, base64Image, {encoding: 'base64'});
return res.status(200).download(qrPath, 'qrcode.png', (err) => {
if(err){
console.error(err)
}else{
try {
//file removed
fs.unlinkSync(qrPath);
} catch(err) {
console.error(err)
}
}
});
}
return res.send({data});
});
});
/* Verifies the otp code entered */
server.post('/verify', (req, res) => {
var verified = speakeasy.totp.verify({
secret: secret,
encoding: 'base32',
token: req.body.code
});
if (verified) {
return res.send({message: 'Verified'});
}
return res.send({message: 'Incorrect code!'});
});
// Catch all requests that does not have existing route.
server.all('*', (req, res) => {
res.status(404).send({ message: 'Request not found!' });
});
module.exports = server;
|
import React from 'react';
import { connect } from 'react-redux';
//UI
import { View, Text, TouchableOpacity, TextInput,
ScrollView, Keyboard, Image, Dimensions, ActivityIndicator,
ImageBackground } from 'react-native';
import Picker from 'react-native-picker-select';
import BasicButton from '../components/BasicButton';
import { mS } from '../constants/masterStyle';
//redux
import { giveAnswer, secureComputeSMC, secureComputeFHESimple,
secureComputeFHEBuffered, secureComputeInvalidate } from '../redux/actions';
const yearsList = [];
for (var i = 1920; i <= (new Date()).getFullYear(); i++) {
yearsList.push({ label: `${i}`, value: i});
}
const weightList = [];
for (var i = 35; i <= 200; i++) {
weightList.push({label: `${i} kg`, value: i});
}
const heightList = [];
for (var i = 120; i <= 215; i++) {
heightList.push({label: `${i} cm`, value: i});
}
const countriesList = [
{ label: 'USA' , value: 1 },
{ label: 'Other' , value: 2 },
];
const genderList = [
{ label: 'Male' , value: 1 },
{ label: 'Female' , value: 2 }
];
const Binary_1_List = [
{ label: 'No' , value: 1 },
{ label: 'Yes' , value: 2 }
];
const Binary_2_List = [
{ label: 'No' , value: 1 },
{ label: 'Yes' , value: 2 }
];
const screenWidth = Dimensions.get('window').width;
const screenHeight = Dimensions.get('window').height;
const getLabel = (list, value) => {
const listObj = list.find(item => item.value === parseInt(value));
return (listObj ? listObj.label : '');
}
class Questionnaire extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: () => (<Text style={mS.screenTitle}>{'Secure Compute'}</Text>),
headerRight: (<View></View>)//
}
};
constructor (props) {
super(props);
const { compute } = this.props;
const { answers } = this.props.answer;
const { account } = this.props.user;
const { progress } = this.props.fhe;
this.state = {
result: (compute.result || 0.0),
resultCurrent: (compute.current || false),
computing: (compute.computing || false),
compute_type: (compute.compute_type || 'smc'),
birthyear: (answers.birthyear || 0),
country: (answers.country || 0),
gender:(answers.gender || 0),
height: (answers.height || 0),
weight: (answers.weight || 0),
binary_1: (answers.binary_1 || 0),
binary_2: (answers.binary_2 || 0),
percentAnswered: (answers.percentAnswered || 0),
numberAnswered: (answers.numberAnswered || 0),
answersCurrent: (answers.answersCurrent || 0),
FHE_keys_ready: (progress.FHE_keys_ready || false),
recalculating: false,
}
this.inputRefs = {
birthyearInput: null,
countryInput: null,
genderInput: null,
heightInput: null,
weightInput: null,
binary_1_Input: null,
binary_2_Input: null,
}
}
UNSAFE_componentWillReceiveProps(nextProps) {
const { compute } = nextProps;
const { answers } = nextProps.answer;
const { account } = nextProps.user;
const { progress } = nextProps.fhe;
this.setState({
percentAnswered: (answers.percentAnswered || 0),
numberAnswered: (answers.numberAnswered || 0),
answersCurrent: (answers.current || 0),
result: (compute.result || 0.0),
resultCurrent: (compute.current || false),
computing: (compute.computing || false),
compute_type: (compute.compute_type || 'smc'),
FHE_keys_ready: (progress.FHE_keys_ready || false),
});
//go to fresh result once calculation is done
if ( this.state.recalculating && !this.state.computing ) {
this.setState({recalculating: false });
this.props.navigation.navigate('ResultSC');
}
}
componentWillUnmount() {
this.inputRefs = {
birthyearInput: null,
countryInput: null,
genderInput: null,
heightInput: null,
weightInput: null,
binary_1_Input: null,
binary_2_Input: null,
}
}
handleSave = (key, value) => {
const { dispatch } = this.props;
if ( key === 'country' ) {
this.setState({ country : value })
}
else if ( key === 'gender' ) {
this.setState({ gender : value })
}
else if ( key === 'birthyear' ){
this.setState({ birthyear :value })
}
else if ( key === 'height' ) {
this.setState({ height : value })
}
else if ( key === 'weight' ) {
this.setState({ weight : value })
}
else if ( key === 'binary_1' ) {
this.setState({ binary_1 : value })
}
else if ( key === 'binary_2' ) {
this.setState({ binary_2 : value })
}
let newAnswer = [{ question_id : key, answer : value }];
dispatch(giveAnswer(newAnswer));
//this changes the result status from current to current == false,
//triggering display of recompute options
dispatch(secureComputeInvalidate());
}
handleSeeResult = () => {
this.props.navigation.navigate('ResultSC');
}
handleSMCCalculate = () => {
const { answers } = this.props.answer;
this.props.dispatch(secureComputeSMC(answers));
this.setState({recalculating:true,computing:true});
}
handleFHECalculateS = () => {
const { answers } = this.props.answer;
this.props.dispatch(secureComputeFHESimple(answers));
this.setState({recalculating:true,computing:true});
}
handleFHECalculateB = () => {
const { answers } = this.props.answer;
this.props.dispatch(secureComputeFHEBuffered(answers));
this.setState({recalculating:true,computing:true});
}
render() {
const { birthyear, country, gender, height, weight, binary_1, binary_2,
answersCurrent, percentAnswered, numberAnswered, API,
result, resultCurrent, computing, compute_type, FHE_keys_ready
} = this.state;
const pickerStyle = {
done: {color: '#FB2E59'},
icon: {display: 'none'},
inputIOS: {fontSize: 18,color: '#404040',flex: 1,width: 0,height: 0},
inputAndroid: {fontSize: 18,color: '#404040',flex: 1,width: 270,height: 45},
}
return (
<View style={mS.containerMain}>
<ScrollView
scrollEnabled={true}
showsVerticalScrollIndicator={false}
overScrollMode={'always'}
ref={scrollView => this.scrollView = scrollView}
>
{!computing && (numberAnswered >= 7) && !resultCurrent &&
<View style={[mS.shadowBoxClear,{height:180}]}>
<BasicButton
width={200}
text={'SMC Secure Compute'}
onClick={this.handleSMCCalculate}
enable={!computing}
/>
<View style={{marginTop: 20}}>
<BasicButton
width={200}
text={'FHE_S Secure Compute'}
onClick={this.handleFHECalculateS}
enable={!computing}
/>
</View>
<View style={{marginTop: 20}}>
<BasicButton
width={200}
text={'FHE_B Secure Compute'}
onClick={this.handleFHECalculateB}
enable={!computing}
keys_ready={FHE_keys_ready}
/>
</View>
</View>
}
{(numberAnswered >= 7) && resultCurrent &&
<View style={[mS.shadowBoxClear]}>
<BasicButton
width={200}
text={'See Result'}
onClick={this.handleSeeResult}
/>
</View>
}
{/*show progress indicator when calculating risk*/}
{computing &&
<View style={[mS.containerProgress, {marginTop: 100}]}>
<ActivityIndicator size="large" color='#33337F' />
<Text style={mS.progressText}>{'Computing'}</Text>
</View>
}
{/********************************************
App info and status box
**********************************************/}
{computing &&
<View style={mS.shadowBox}>
<ImageBackground source={require('../assets/images/id.png')} style={{width: '100%', height: 50}}>
<Text style={mS.boxTitle}>{'Status'}</Text>
</ImageBackground>
{(compute_type == 'fhes') &&
<View style={mS.textBlock}>
<Text style={mS.mediumDark}>{'Unbuffered FHE calculation.'}</Text>
<Text style={mS.smallGray}>{"This is the 'slowest' way to compute a result. Expect the result to arrive in about 1 minute."}</Text>
</View>
}
{(compute_type == 'fheb') &&
<View style={mS.textBlock}>
<Text style={mS.mediumDark}>{'Buffered FHE calculation.'}</Text>
<Text style={mS.smallGray}>{'This computation uses precomputed FHE keys to provide a better user experience.'}</Text>
</View>
}
{(compute_type == 'smc') &&
<View style={mS.textBlock}>
<Text style={mS.mediumDark}>{'Secure Multiparty Computation.'}</Text>
<Text style={mS.smallGray}>{'This is the fastest way to compute a result.'}</Text>
</View>
}
</View>
}
{/*ask questions when not computing*/}
{!computing && <View style={mS.shadowBoxQ}>
{(numberAnswered < 7) &&
<View style={[mS.rowQ,{height:90, paddingLeft:5, paddingRight:5, paddingBottom: 10}]}>
<Text style={[mS.smallGray,{fontSize:16,fontStyle:'italic'}]}>
{'Please answer the questions. All calculations use ' +
'secure computation to ensure your privacy.'}</Text>
</View>
}
{(numberAnswered >= 7) && resultCurrent &&
<View style={[mS.rowQ,{height:90, paddingLeft:5, paddingRight:5, paddingBottom: 10}]}>
<Text style={[mS.smallGray,{fontSize:16,fontStyle:'italic'}]}>
{'To recompute your score or try a different API, ' +
'change one or more of the values below.'}</Text>
</View>
}
{Platform.OS == 'ios' &&
<TouchableOpacity onPress={()=>{this.inputRefs.countryInput.togglePicker()}}>
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Country'}</Text></View>
<Text style={this.state.country == 0 ? { fontSize: 18, opacity: 0.2 }:{ fontSize: 18 }}>
{ this.state.country == 0 ? 'Please select' : countriesList[this.state.country-1].label }
</Text>
<Picker
items={countriesList}
value={country}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('country',v)}}
onDownArrow={()=>{this.inputRefs.birthyearInput.togglePicker();}}
ref={el => {this.inputRefs.countryInput = el;}}
style={pickerStyle}
/>
</View>
</TouchableOpacity>
}
{Platform.OS == 'android' &&
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Country'}</Text></View>
<Picker
items={countriesList}
value={country}
useNativeAndroidPickerStyle={false}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('country',v)}}
style={pickerStyle}
/>
</View>
}
{Platform.OS == 'ios' &&
<TouchableOpacity onPress={()=>{
this.inputRefs.birthyearInput.togglePicker();
this.state.birthyear == 0 && this.setState({ birthyear : yearsList[30].value });
}}>
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Birthyear'}</Text></View>
<Text style={this.state.birthyear == 0 ? { fontSize: 18, opacity: 0.2 }:{ fontSize: 18 }}>
{ this.state.birthyear == 0 ? 'Please select': this.state.birthyear }
</Text>
<Picker
items={yearsList}
value={birthyear}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('birthyear',v)}}
onUpArrow ={()=>{this.inputRefs.countryInput.togglePicker();}}
onDownArrow={()=>{this.inputRefs.genderInput.togglePicker();}}
ref={el=>{ this.inputRefs.birthyearInput = el}}
style={pickerStyle}
/>
</View>
</TouchableOpacity>
}
{Platform.OS == 'android' &&
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Birthday'}</Text></View>
<Picker
items={yearsList}
value={birthyear}
useNativeAndroidPickerStyle={false}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('birthyear',v)}}
style={pickerStyle}
/>
</View>
}
{Platform.OS == 'ios' &&
<TouchableOpacity onPress={()=>{this.inputRefs.genderInput.togglePicker()}}>
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Gender'}</Text></View>
<Text style={this.state.gender == 0 ? { fontSize: 18, opacity: 0.2 }:{ fontSize: 18 }}>
{ this.state.gender == 0 ? 'Please select': genderList[this.state.gender-1].label }
</Text>
<Picker
items={genderList}
value={gender}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('gender',v)}}
onUpArrow={()=>{this.inputRefs.birthyearInput.togglePicker()}}
onDownArrow={()=>{this.inputRefs.heightInput.togglePicker()}}
ref={el => { this.inputRefs.genderInput = el}}
style={pickerStyle}
/>
</View>
</TouchableOpacity>
}
{Platform.OS == 'android' &&
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Gender'}</Text></View>
<Picker
items={genderList}
value={gender}
useNativeAndroidPickerStyle={false}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('gender',v)}}
style={pickerStyle}
/>
</View>
}
{Platform.OS == 'ios' &&
<TouchableOpacity onPress={() => {
this.inputRefs.heightInput.togglePicker();
this.state.height == 0 && this.setState({ height : heightList[45].value });
}}>
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Height'}</Text></View>
<Text style={this.state.height == 0 ? { fontSize: 18, opacity: 0.2 }:{ fontSize: 18 }}>
{ this.state.height == 0 ? 'Please select': this.state.height + ' cm' }
</Text>
<Picker
items={heightList}
value={height}
useNativeAndroidPickerStyle={false}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('height',v)}}
onUpArrow ={()=>{this.inputRefs.genderInput.togglePicker()}}
onDownArrow={()=>{this.inputRefs.weightInput.togglePicker()}}
ref={el => { this.inputRefs.heightInput = el}}
style={pickerStyle}
/>
</View>
</TouchableOpacity>
}
{Platform.OS == 'android' &&
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Height'}</Text></View>
<Picker
items={heightList}
value={height}
useNativeAndroidPickerStyle={false}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('height',v)}}
style={pickerStyle}
/>
</View>
}
{Platform.OS == 'ios' &&
<TouchableOpacity onPress={() => {
this.inputRefs.weightInput.togglePicker();
this.state.weight == 0 && this.setState({ weight : weightList[45].value });
}}
>
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Weight'}</Text></View>
<Text style={this.state.weight == 0 ? { fontSize: 18, opacity: 0.2 }:{ fontSize: 18 }}>
{ this.state.weight == 0 ? 'Please select': this.state.weight + ' kg'}
</Text>
<Picker
items={weightList}
value={weight}
onpress={() => {this.state.weight == 0 ? this.setState({ weight : weightList[45].value }) : this.setState({ weight : this.state.weight })}}
useNativeAndroidPickerStyle={false}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('weight',v)}}
onUpArrow ={()=>{this.inputRefs.heightInput.togglePicker()}}
onDownArrow={()=>{this.inputRefs.binary_1_Input.togglePicker()}}
ref={el => { this.inputRefs.weightInput = el}}
style={pickerStyle}
/>
</View>
</TouchableOpacity>
}
{Platform.OS == 'android' &&
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Weight'}</Text></View>
<Picker
items={weightList}
value={weight}
onpress={()=>{this.state.weight == 0 ? this.setState({ weight : weightList[45].value }) : this.setState({ weight : this.state.weight })}}
useNativeAndroidPickerStyle={false}
placeholder={{label: 'Please select', value: 0}}
onValueChange={(v)=>{this.handleSave('weight',v)}}
style={pickerStyle}
/>
</View>
}
{Platform.OS == 'ios' &&
<TouchableOpacity onPress={()=>{this.inputRefs.binary_1_Input.togglePicker()}}>
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Binary_1'}</Text></View>
<Text style={this.state.binary_1 == 0 ? { fontSize: 18, opacity: 0.2 }:{ fontSize: 18 }}>
{ this.state.binary_1 == 0 ? 'No/Yes': Binary_1_List[this.state.binary_1-1].label }
</Text>
<Picker
items={Binary_1_List}
value={binary_1}
placeholder={{ label: 'No/Yes', value: 0}}
//do not need the 'city' thing here because the keyboard blocks these anyway
//so its impossible for someone to select these with the keyboard up
onValueChange={(v)=>{this.handleSave('binary_1',v)}}
onUpArrow={()=>{this.inputRefs.weightInput.togglePicker()}}
onDownArrow={()=>{this.inputRefs.binary_2_Input.togglePicker()}}
ref={el => { this.inputRefs.binary_1_Input = el}}
style={pickerStyle}
/>
</View>
</TouchableOpacity>
}
{Platform.OS == 'android' &&
<View style={mS.rowQ}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Binary_1'}</Text></View>
<Picker
items={Binary_1_List}
value={binary_1}
useNativeAndroidPickerStyle={false}
placeholder={{label: 'No/Yes', value: 0}}
onValueChange={(v)=>{this.handleSave('binary_1',v)}}
style={pickerStyle}
/>
</View>
}
{Platform.OS == 'ios' &&
<TouchableOpacity onPress={()=>{this.inputRefs.binary_2_Input.togglePicker()}}>
<View style={[mS.rowQ, {borderBottomColor: '#FFFFFF'}]}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Binary_2'}</Text></View>
<Text style={this.state.binary_2 == 0 ? { fontSize: 18, opacity: 0.2 }:{ fontSize: 18 }}>
{ this.state.binary_2 == 0 ? 'No/Yes': Binary_2_List[this.state.binary_2-1].label }
</Text>
<Picker
items={Binary_2_List}
value={binary_2}
placeholder={{label: 'No/Yes', value: 0}}
onValueChange={(v)=>{this.handleSave('binary_2',v)}}
onUpArrow={()=>{this.inputRefs.binary_1_Input.togglePicker();}}
ref={el=>{this.inputRefs.binary_2_Input = el}}
style={pickerStyle}
/>
</View>
</TouchableOpacity>
}
{Platform.OS == 'android' &&
<View style={[mS.rowQ, {borderBottomColor: '#FFFFFF'}]}>
<View style={mS.labelQ}><Text style={mS.textQ}>{'Binary_2'}</Text></View>
<Picker
items={Binary_2_List}
value={binary_2}
useNativeAndroidPickerStyle={false}
placeholder={{label: 'No/Yes', value: 0}}
onValueChange={(v)=>{this.handleSave('binary_2',v)}}
style={pickerStyle}
/>
</View>
}
</View>
}
</ScrollView>
</View>
);
}}
const mapStateToProps = state => ({
user: state.user,
answer: state.answer,
compute: state.compute,
fhe: state.fhe,
});
export default connect(mapStateToProps)(Questionnaire);
|
import d3 from 'd3';
import {saturateColor} from './calculations';
export function updateFrameworkColors(colors, slave) {
const frameworkColors = slave.focusedOrSelected || !slave.anyFocusedOrSelected
? colors
: colors.map(saturateColor);
d3.select(this).selectAll('.galaxy__node__framework')
.style('fill', f => frameworkColors.get(f.id));
}
export function createFrameworks(selection, data) {
const {frameworks, r} = data;
const diameter = r * 2;
const offset = r;
d3.layout.force()
.size([diameter, diameter])
.charge(-100)
.gravity(1)
.links([])
.nodes(frameworks)
.on('tick', innerTick) //eslint-disable-line
.start();
const framework = selection.selectAll('g.galaxy__node__framework')
.data(frameworks, d => d.id);
const frameworkNode = framework.enter()
.append('g')
.attr('class', 'galaxy__node__framework')
.append('circle')
.attr('id', d => d.id);
frameworkNode
.attr('r', 6); // TODO make this dynamic when nodes resize
function innerTick() {
framework.attr('transform', d => 'translate(' + (d.x - offset) + ',' + (d.y - offset) + ')');
}
framework.exit().remove();
innerTick();
}
|
var webpackDevMiddleware = require("webpack-dev-middleware");
var webpack = require("webpack");
var express = require('express')
var hotMiddleWare = require('webpack-hot-middleware');
var opn = require('opn');
var app = express()
var webpackConfig = require('./webpack.config.js');
var unless = require('../webpack.unless.js');
var merge = require('webpack-merge');
var configunlike = merge( unless, webpackConfig);
var compiler = webpack(configunlike);
app.use(require("webpack-dev-middleware")(compiler, {
publicPath: configunlike.output.publicPath,
stats: {
colors: true,
chunks: false
}
}));
app.use(hotMiddleWare(compiler));
console.log('> Starting dev server...');
app.use(express.static('../index'));
app.get('/', function(req, res, next){
next();
});
const posthttp=7777
console.log('http://localhost:'+posthttp+'。。。。');
app.listen(posthttp,()=>{
opn('http://localhost:'+posthttp+'');
});
|
import querystring from 'querystring'
const apiKey = 'cc1d5484fa10b37a0931266dd6edfcb8'
export default async function getData(address, queryParams) {
const res = await fetch(`http://gateway.marvel.com${address}?apikey=${apiKey}&${querystring.stringify(queryParams)}`)
return await res.json()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.