text stringlengths 7 3.69M |
|---|
import React from 'react';
import './App.css';
import {SearchBar} from '../SearchBar/SearchBar';
import {SearchResults} from "../SearchResults/SearchResults";
import {Playlist} from "../Playlist/Playlist";
import Spotify from "../../util/Spotify";
import {Login} from "../Login/Login";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
searchResults: [],
playlistName: 'My playlist',
playlistTracks: []
}
this.addTrack = this.addTrack.bind(this);
this.removeTrack = this.removeTrack.bind(this);
this.updatePlaylistName = this.updatePlaylistName.bind(this);
this.savePlaylist = this.savePlaylist.bind(this);
this.search = this.search.bind(this);
}
addTrack(track) {
const isDuplicate = this.state.playlistTracks.find(savedTrack =>
savedTrack.id === track.id)
if (isDuplicate) {
return;
} else {
const newPlaylistTracks = this.state.playlistTracks
newPlaylistTracks.push(track);
this.setState({playlistTracks: newPlaylistTracks})
}
}
removeTrack(track) {
const newPlaylistTracks = this.state.playlistTracks.filter(savedTrack => savedTrack.id !== track.id);
this.setState({playlistTracks: newPlaylistTracks})
}
updatePlaylistName(name) {
this.setState({playlistName: name})
}
savePlaylist() {
const trackURIs = this.state.playlistTracks.map(track => track.uri);
Spotify.savePlaylist(this.state.playlistName, trackURIs).then(() => {
this.setState({
playlistName: 'New playlist',
playlistTracks: [],
})
})
}
search(searchTerm) {
// pass the promise returned from search to update searchResults
Spotify.search(searchTerm).then(searchResults => {
console.log('resolved');
this.setState({searchResults: searchResults});
}).catch(error => {console.log(error);});
}
render() {
return (
<div>
<h1><span className="highlight">Spotify</span>Jam</h1>
<div className="App">
<Login />
<SearchBar onSearch={(searchTerm) => this.search(searchTerm)}/>
<div className="App-playlist">
<SearchResults searchResults={this.state.searchResults} onAdd={(track) => this.addTrack(track)}/>
<Playlist playlistName={this.state.playlistName} playlistTracks={this.state.playlistTracks}
onRemove={(track) => this.removeTrack(track)}
onNameChange={(name) => this.updatePlaylistName(name)}
onSave={() => this.savePlaylist()}/>
</div>
</div>
</div>
)};
}
export default App;
|
import { addToCart } from "../API";
import { Paper , Box } from '@material-ui/core'
const SingleProduct = ({ image, title, id, price, description, item, checkedProducts, checkboxChanged, openModal, }) => {
return (
<Box className="product-box"
key={id}
>
<Box item xs={3}
className={`${checkedProducts && checkedProducts.includes(id)
? " products__item--input--highlited"
: "products-item"
}`} >
<div className="checkbox-container">
<input
type="checkbox"
id="products__item--input"
className="products__item--input"
checked={checkedProducts && checkedProducts.includes(id)}
onChange={() => checkboxChanged(id)}
/>
</div>
<Paper className="products-paper">
<input
type="button"
className="hidden-btn"
value="Add To Cart"
onClick={() => {
addToCart(id, 1);
}} />
<div className="products-image" onClick={(e) => openModal(item)}>
<img src={image} alt="img" />
</div>
<div className="products-info">
<div className="products-title">
<h3>{title}</h3>
<p>{description}</p>
</div>
<h3 className="products-supplier">
<span>By:</span>
<button>US-Supplier103</button>
</h3>
</div>
<div className="products-price">
<span>COST {price}$ </span>
</div>
</Paper>
</Box>
</Box>
)
}
export default SingleProduct; |
import React from 'react'
import Button from '@ctkit/button'
import {Col, Row} from '@ctkit/layout'
import {styled} from '@ctkit/theme'
import ReactCodeInput from 'react-code-input'
import classnames from 'classnames';
import Modal from '@ctkit/modal'
import isString from 'lodash.isstring'
//-----------------------------------------------------------------------------
export default ({open,closeModal,handleCode, onClick, messageError, header, description,numInputs,image,actions}) => {
return (
<Modal openModal={open} close={() => closeModal()} closeParam={false}>
<Root className={classnames('clearfix')}>
<div className="rui-content">
{isString(image) ? <img src={image} alt="" width={100}/> : image}
{header && <h4>{header}</h4>}
<p>{description}</p>
<div className="row">
<div className="col-12">
{<ReactCodeInput
onChange={code => handleCode(code)}
numInputs={numInputs}
/>}
{messageError && <div> {messageError}</div>}
</div>
</div>
{actions && (
<>
{actions.submit &&<div className="mt-4 clearfix rui-actions">
<Button size="large" primary onClick={actions.submit.onClick}>{actions.submit.text}</Button>
</div>}
{actions.cancel && <div className="mt-4 clearfix rui-actions">
<a href="#">{actions.cancel.text}</a>
</div>}
</>
)}
</div>
</Root>
</Modal>
)
}
const Root = styled.div`
margin: auto;
width:100%;
text-align:center;
`
|
var map;
var pin;
var latBox;
var longBox;
var zoomBox;
$(window).load(function () {
//attach validator
$("form").validationEngine('attach');
var successUrl = $('#SuccessUrl').attr('value');
var failureUrl = $('#FailureUrl').attr('value');
var window = $("#MessageBox").data("tWindow");
window.center();
$('form').submit(function (e) {
e.preventDefault();
window.center();
window.open();
$.post($(this).attr("action"), $(this).serialize(), function (json) {
// handle response
if (json) {
window.ajaxRequest(successUrl);
}
else {
window.ajaxRequest(failureUrl);
}
window.center();
}, "json");
});
//set up lat box reference
latBox = $("#Latitude").data("tTextBox");
//set up long box reference
longBox = $("#Longitude").data("tTextBox");
zoomBox = $("ZoomLevel").data("tTextBox");
//if you dont know what is happening here, you are a tit.
CreateMap();
});
//inits and creates ajax map
function CreateMap() {
var originalZoomLevel = $('#CurrentZoomLevel').attr('value');
var zoomLevel = DataZoomToMapZoom(parseInt(originalZoomLevel));
// Define the pushpin location
var loc = new Microsoft.Maps.Location(latBox.value(), longBox.value());
// Add a pin to the map
pin = new Microsoft.Maps.Pushpin(loc, { draggable: true });
//wire up drag event
Microsoft.Maps.Events.addHandler(pin, 'mouseup', OnPushPinChange);
//create the map
map = new Microsoft.Maps.Map(document.getElementById("LocaleMap"),
{
credentials: "AsZr5U9t2cAH1YZh8fMdisYJ3479SF2aw4MqdnC8-cK8bnHS_qpyNeAvXdXg8WID",
center: loc,
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: zoomLevel
});
//add the pin
map.entities.push(pin);
}
//handles lat textbox value change
function OnLatChange (data) {
var loc = new Microsoft.Maps.Location(data.newValue, longBox.value());
pin.setLocation(loc);
map.setView({ center: loc });
}
//handles long textbox value change
function OnLongChange(data) {
var loc = new Microsoft.Maps.Location(latBox.value(), data.newValue);
pin.setLocation(loc);
map.setView({ center: loc });
}
//handles push pin drag event
function OnPushPinChange(data) {
var location = pin.getLocation();
latBox.value(location.latitude);
longBox.value(location.longitude);
}
//handles zoom textbox value change
function OnZoomChange(data) {
var mapZoomLevel = DataZoomToMapZoom(data.newValue);
map.setView({ zoom: mapZoomLevel });
}
//helper, converts from data zoom levels to map zoom levels
function DataZoomToMapZoom(data) {
switch (data) {
case 1:
return 8;
case 2:
return 9;
case 3:
return 11;
case 4:
return 12;
}
} |
#pragma strict
var galaz1: GameObject;
var galaz2: GameObject;
var galaz3: GameObject;
var kwiatek1: GameObject;
var kwiatek2: GameObject;
var kwiatek3: GameObject;
var obs_number: int;
var usedNumbers = new List.<int>();
var notDone: boolean=true;
var i: int;
function Start () {
obs_number=Random.Range(0,3);
i=0;
rand_obstacles();
obs_on();
}
function Update () {
}
function rand_obstacles(){
while(notDone){
if(usedNumbers.Count>=obs_number-1){
notDone=false;
}
var newNumber: int=Random.Range(1,4);
while(usedNumbers.Contains(newNumber)){
newNumber=Random.Range(1,4);
}
usedNumbers.Add(newNumber);
}
}
function obs_on(){
for(i=0;i<usedNumbers.Count;i++){
if(choos_fruit.fruit==1){eval("galaz"+usedNumbers[i]+".SetActive(true)");}
if(choos_fruit.fruit==2){eval("kwiatek"+usedNumbers[i]+".SetActive(true)");}
if(choos_fruit.fruit==3){eval("galaz"+usedNumbers[i]+".SetActive(true)");}
if(choos_fruit.fruit==4){eval("kwiatek"+usedNumbers[i]+".SetActive(true)");}
if(choos_fruit.fruit==5){eval("kwiatek"+usedNumbers[i]+".SetActive(true)");}
if(choos_fruit.fruit==6){eval("kwiatek"+usedNumbers[i]+".SetActive(true)");}
}
} |
import { API_URL } from '../store/constant';
let path = 'users/api/';
//Función para realizar la petición al backend mediante api-rest
async function request(method, data, param){
let url;
if(param !== ''){
url = `${API_URL + path + param}/`;
}else{
url = `${API_URL + path}`;
}
const response = await fetch(url, {
method: method,
headers: {
//'Accept': 'Application/json',
//'Content-Type': 'application/json',
},
body: data,
//body: data ? JSON.stringify(data) : undefined,
});
if(method === 'DELETE'){
const response_json = await response;
return response_json;
}else{
const response_json = await response.json();
return response_json;
}
}
/****** CRUD ******/
//Traer los objetos para listarlos
export function read(){
return request('GET', null, '');
}
//Almacenar el objeto
export function store(data){
return request('POST', data, '');
}
//Traer el objeto para actualizarlo
export function edit(id){
return request('GET', null, id);
}
//Enviar el objeto para actualizarlo
export function update(id, data){
return request('PUT', data, id);
}
//Eliminar el objeto
export function remove(id){
return request('DELETE', null, id);
} |
import {SERVICES_FETCH_IN, SERVICES_FETCH_GOOD, SERVICES_FETCH_ERROR, API_GET_SERVICES} from "../constants";
import {request} from "../services/requests";
export default function getServices() {
return (dispatch => {
dispatch( {type: SERVICES_FETCH_IN, payload: {}} );
request(API_GET_SERVICES,"GET")
.then(data => {
dispatch( {type: SERVICES_FETCH_GOOD, payload: data} );
return data;
})
.catch(error => dispatch({ type: SERVICES_FETCH_ERROR, payload: {error: error.message} }) ) ;
});
}
|
'use strict';
app.controller('LoginCtrl', function ($scope, AuthFactory) {
$scope.login = AuthFactory.login;
$scope.getCurrentUser = AuthFactory.getCurrentUser;
}); |
import { connect } from 'react-redux';
import Datalib from './Datalib';
import {EnhanceLoading} from '../../../components/Enhance';
import {buildOrderPageState} from '../../../common/orderAdapter';
import {Action} from '../../../action-reducer/action';
import {getPathValue} from '../../../action-reducer/helper';
import {search} from '../../../common/search';
import {fetchJson, getActions, postOption} from "../../../common/common";
const STATE_PATH = ['config', 'datalib'];
const action = new Action(STATE_PATH);
const URL_CONFIG = '/api/config/datalib/config';
const URL_TRANS_LIST = '/api/config/datalib/trans_list';
const URL_STAN_LIST = '/api/config/datalib/stan_list';
const getSelfState = (rootState) => {
return getPathValue(rootState, STATE_PATH);
};
const buildState = (config, data) => {
const tabs = [
{key: 'transform', title: config.transform, close: false},
{key: 'standard', title: config.standard, close: false}
];
return {
tabs,
...config,
activeKey: 'transform',
transform: buildOrderPageState(data, config.transformConfig.index, {editConfig: config.transformConfig.edit}),
standard: buildOrderPageState({}, config.standardConfig.index, {editConfig: config.standardConfig.edit})
};
};
const initActionCreator = () => async (dispatch) => {
dispatch(action.assign({status: 'loading'}));
let res, data, config;
res = await fetchJson(URL_CONFIG);
if (!res) {
dispatch(action.assign({status: 'retry'}));
return;
}
config = res;
const buttons = config.transformConfig.index.buttons;
const actions = getActions('datalib');
config.transformConfig.index.buttons = buttons.filter(button => actions.findIndex(item => item === button.sign)!==-1);
const buttons1 = config.standardConfig.index.buttons;
const actions1 = getActions('datalib');
config.standardConfig.index.buttons = buttons1.filter(button => actions1.findIndex(item => item === button.sign)!==-1);
const postData = {itemFrom:0, itemTo:10};
const json = await fetchJson(URL_TRANS_LIST, postOption(postData));
if (json.returnCode) {
dispatch(action.assign({status: 'retry'}));
return;
}
const payload = Object.assign(buildState(config, json.result), {status: 'page'});
dispatch(action.create(payload));
};
const tabChangeActionCreator = (key) => async (dispatch,getState) => {
let res, tableItems, maxRecords;
if (key === 'transform') {
res = await search(URL_TRANS_LIST, 0, 10, {});
tableItems = res.result.data;
maxRecords = res.result.returnTotalItem;
dispatch(action.assign({tableItems, maxRecords}, 'transform'));
} else if (key === 'standard') {
res = await search(URL_STAN_LIST, 0, 10, {});
tableItems = res.result.data;
maxRecords = res.result.returnTotalItem;
dispatch(action.assign({tableItems, maxRecords}, 'standard'));
}
dispatch(action.assign({activeKey: key}));
};
const mapStateToProps = (state) => {
return getSelfState(state);
};
const actionCreators = {
onInit: initActionCreator,
onTabChange: tabChangeActionCreator
};
const DatalibContainer = connect(mapStateToProps, actionCreators)(EnhanceLoading(Datalib));
export default DatalibContainer;
|
describe('MaleDancer', function() {
var maleDancer;
beforeEach(function() {
maleDancer = makeMaleDancer(10, 10, 100);
});
it('should be an instance of PersonDancer', function() {
expect(maleDancer).to.be.an.instanceof(PersonDancer);
});
it('should be have MaleDancer as a constructor', function() {
expect(maleDancer.constructor).to.equal(MaleDancer);
});
it('should have a gender of male', function() {
expect(maleDancer._gender).to.equal('male');
});
it('should have a type of person', function() {
expect(maleDancer._type).to.equal('person');
});
it('should have a method named drink', function() {
sinon.spy(maleDancer, 'drink');
expect(maleDancer.drink).to.be.a('function');
maleDancer.drink(2);
expect(maleDancer.drink.called).to.be.true;
});
it('should get more intoxicated after drinking', function() {
expect(maleDancer._intoxicationLevel).to.equal(0);
maleDancer.drink(20);
expect(maleDancer._intoxicationLevel).to.be.above(0);
});
it('should render a node with a class of `person` and `male`', function() {
expect(maleDancer._$node.hasClass('person')).to.be.true;
expect(maleDancer._$node.hasClass('male')).to.be.true;
});
});
|
import Navbar from './components/Navbar/Navbar';
import Footer from './components/Footer/Footer';
import Contact from './components/Contact/Contact';
import Main from './components/Main/Main'
import Projects from './components/Projects/Projects'
function App() {
return (
<div>
<Navbar />
<Main />
<Projects />
<Contact />
<Footer />
</div>
);
}
export default App;
|
const gulp = require('gulp');
const less = require('gulp-less');
const concat = require('gulp-concat');
const minifyCSS = require('gulp-minify-css');
const rename = require('gulp-rename');
const sourcemaps = require('gulp-sourcemaps');
const LessAutoprefix = require('less-plugin-autoprefix');
const autoprefix = new LessAutoprefix({ browsers: ['last 2 versions'] });
const browserSync = require('browser-sync').create();
gulp.task('less', () => {
gulp.src('./src/less/**/*.less')
// .pipe(sourcemaps.init())
.pipe(less({
plugins: [autoprefix]
}))
.pipe(sourcemaps.write())
// .pipe(concat('DEXTemplate.css'))
// .pipe(minifyCSS())
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('./dist/css'))
.pipe(browserSync.stream());
});
gulp.task('serve', ['less'], () => {
browserSync.init({
server: './'
});
gulp.watch('./src/less/**/*.less', ['less']);
gulp.watch('./exemple/*.html').on('change', browserSync.reload);
});
gulp.task('default', ['serve']); |
const { entryPath, appPath, templatePath } = require("./path.config");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const WebPackBarPlugin = require("webpackbar");
module.exports = {
resolve: {
extensions: [".tsx", ".ts", ".js"],
alias: {
"@": appPath,
},
},
cache: {
type: "filesystem", // 使用文件缓存
},
entry: {
index: entryPath,
},
module: {
rules: [
{
// webpack 5 新增 loader 专门处理静态资源
test: /\.(png|svg|jpg|jpeg|gif)$/i,
include: appPath,
type: "asset/resource",
},
{
// 解析字体
test: /.(woff|woff2|eot|ttf|otf)$/i,
include: appPath,
type: "asset/resource",
},
{
test: /\.css$/,
// include: appPath,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 2,
},
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [["postcss-preset-env"]],
},
},
},
{
loader: "thread-loader",
options: {
workerParallelJobs: 2,
},
},
],
},
{
// 解析 css 文件
test: /\.(scss|sass)$/,
include: appPath,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 2,
},
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [["postcss-preset-env"]],
},
},
},
{
loader: "thread-loader",
options: {
workerParallelJobs: 2,
},
},
"sass-loader",
],
},
{
test: /\.(js|jsx|ts|tsx)$/,
include: appPath,
use: [
{
loader: "esbuild-loader",
options: {
loader: "tsx",
target: "es6",
},
},
],
},
],
},
plugins: [
new WebPackBarPlugin({ profile: true }),
// 生成html,自动引入所有bundle
new HtmlWebpackPlugin({
template: templatePath,
}),
],
output: {
pathinfo: false,
},
};
|
const { TonClient, signerKeys} = require("@tonclient/core");
const { Account } = require("@tonclient/appkit");
const { libNode } = require("@tonclient/lib-node");
const fs = require('fs');
const path = require('path');
const keysFile = path.join(__dirname, '../keys.json');
const config = require('../config');
const { get_tokens_from_giver } = require('../giverConfig.js')
const { constructContracts, getLighthouseAddress } = require('../common.js')
const { MultiValidatorExampleContract } = require('../../artifacts/MultiValidatorExampleContract.js')
async function main(client) {
const keys = JSON.parse(fs.readFileSync(keysFile, "utf8"));
const { root, xrt } = await constructContracts(client, keys)
const validator = new Account(MultiValidatorExampleContract,
{signer: signerKeys(keys), client: client,
initData: {
lighthouse: await getLighthouseAddress(client, root, xrt, 'Lighthouse'),
k: 2,
pubkeys: {
1: '0x' + keys.public,
2: '0x' + keys.public,
3: '0x' + keys.public
}
}
});
await get_tokens_from_giver(client, await validator.getAddress(), 5)
console.log(await validator.getAddress());
await validator.deploy();
}
(async () => {
try {
TonClient.useBinaryLibrary(libNode);
const client = new TonClient({
network: {
endpoints: config['network']['endpoints'],
}
});
console.log("Hello TON!");
await main(client);
process.exit(0);
} catch (error) {
console.error(error);
}
})();
|
const http = require('http');
const App = require('./app');
const port = 3004;
const app = new App(port);
const httpServer = http.createServer(app.express);
// listen on provided ports
httpServer.listen(port);
// add error handler
httpServer.on('error', function (err) {
console.log(err);
});
// start listening on port
httpServer.on('listening', function() {
console.log('Use port' + port);
}); |
import createSocket from '../socket/createSocket';
const socket = createSocket({ url: 'http://localhost:8080' });
export default socket; |
import React, { Component } from 'react'
class Products extends Component {
constructor(props) {
super(props)
this.onClick = this.onClick.bind(this)
}
onClick() {
const id = this.props
this.props.addToCart(id)
}
render() {
const {
name,
price,
id,
addToCart
} = this.props
return (
<section style={{width: '30%', textAlign: 'left'}}>
<span>Name: {name}</span><br/>
<span>Price: {price} usd </span>
<button onClick={this.onClick}>Add to cart</button>
</section>
);
}
}
export default Products
|
const { spawnSync: spawn } = require('child_process')
const parseImpact = s => {
if (!s) return ''
let files = 0
let insertions = 0
let deletions = 0
const parts = s.split(', ')
parts.forEach((p, index) => {
const n = parseInt(p, 10)
if (p.includes('insertion')) {
insertions = n
} else if (p.includes('deletion')) {
deletions = n
} else {
files = n
}
})
return {
files,
insertions,
deletions
}
}
const parseLines = (a, dateOnly) => {
return a.map(group => {
const impact = parseImpact(group.pop())
const data = {
date: group.shift(),
author: group.shift(),
subject: group.join('\n'),
impact
}
if (dateOnly) data.date = data.date.split('T')[0]
return data
})
}
const SEP = '#####'
module.exports = (args = {}) => {
const {
cwd,
limit,
mine,
reverse,
skip,
dateOnly,
since
} = args
const params = [
'log',
`--format=${SEP}%cI%n%ae%n%s`,
'--shortstat',
'--no-merges'
]
if (limit) {
params.push(`--max-count=${limit}`)
}
if (since) {
params.push(`--since="${since}"`)
}
if (reverse) {
params.push('--reverse')
}
if (mine) {
const _params = ['config', '--get', 'user.name']
const { stdout, stderr } = spawn('git', _params, { cwd })
if (stderr && stderr.toString().length) {
throw new Error(stderr.toString())
}
params.push(`--author=${stdout.toString().trim()}`)
}
if (skip) {
params.push(`--skip=${skip}`)
}
const { stdout, stderr } = spawn('git', params, { cwd })
if (stderr.length) {
throw new Error(stderr.toString())
}
let lines = stdout
.toString() // stringify the stdout
.split(SEP) // split on new line
.filter(Boolean) // remove blank lines
.map(s => s.trim().split('\n'))
return parseLines(lines, dateOnly)
}
|
$('#demo1').timeliny();
|
function getLang() {
return {
fr: getLangFr(),
en: getLangEn()
}
} |
/***
* @class
* 处理group缓存相关
*/
var weconstants = require('./weconstants');
var qcloud = require('../../../vendor/qcloud-weapp-client-sdk/index');
var config = require('../../../config');
var _request = function (type, data, cb) {
qcloud.request({
url: config.service.groupUrl + type,
login: true,
method: "POST",
data: data,
header: { 'content-type': 'application/json' },
success: (response) => {
var res = response.data;
if ((typeof res.code) != 'undefined') {
if (res.code == 0 &&
(type == "daka" || type == "redaka" || type == "edit" || type == "join" || type == "image")) {
saveLocalGroupStatus(data.group_id, type)
}else if(res.code == 0 && type == "detail" && res.data.group){
saveLocalGroup(res.data.group)
}
typeof cb == "function" && cb(res.code, res.message, res.data);
} else {
typeof cb == "function" && cb(-1, weconstants.WE_DAKA_ERROR_SERVICE, null);
}
},
fail: (error) => {
typeof cb == "function" && cb(-2, weconstants.WE_DAKA_ERROR_NETWORK, error);
}
});
}
// create
// 发布作业
var createGroup = function (params, cb) {
_request("create", params, cb)
}
// get Lists
var getClientGroups = function (params, cb) {
_request("lists", params, cb)
}
// share
var shareGroup = function (params, cb) {
_request("share", params, cb)
}
// get Group Detail
var getClientGroup = function (group_id, cb) {
var params = {
group_id: group_id
}
_request("detail", params, cb)
}
// get Group Rank
var getClientGroupRank = function (group_id, cb) {
var params = {
group_id: group_id
}
_request("rank", params, cb)
}
// get Group Feed
var getClientGroupFeed = function (group_id, params, cb) {
params.group_id = group_id
_request("feed", params, cb)
}
// get Group Member
var getClientGroupMember = function (group_id, cb) {
var params = {
group_id: group_id
}
_request("member", params, cb)
}
var getClientGroupHistory = function (params, cb) {
_request("history", params, cb)
}
// getTask group
var getTask = function (params, cb) {
_request("task", params, cb)
}
// join group
var joinGroup = function (group_id, cb) {
var params = {
group_id: group_id
}
_request("join", params, cb)
}
// edit
var editGroup = function (params, cb) {
_request("edit", params, cb)
}
var imageGroup = function (params, cb) {
_request("image", params, cb)
}
var qrcodeGroup = function (params, cb) {
_request("qrcode", params, cb)
}
// remind
var remindGroup = function (params, cb) {
_request("remind", params, cb)
}
// quit
var quitGroup = function (group_id, user_id, cb) {
var params = {
group_id: group_id,
user_id: user_id
}
_request("quit", params, cb)
}
// dakaGroup
var dakaGroup = function (params, cb) {
_request("daka", params, cb)
}
// dakaGroup
var redakaGroup = function (params, cb) {
_request("redaka", params, cb)
}
var exportGroup = function (params, cb) {
_request("export", params, cb)
}
var saveLocalGroups = function (groups) {
try{
wx.setStorage({
key: weconstants.WE_DAKA_KEY_GROUPS,
data: groups
});
}catch(e){
}
};
var saveLocalGroup = function (group) {
var groups = getLocalGroups();
if (!(groups && typeof groups === 'object' && Array == groups.constructor)) {
groups = [];
}
var isExistFlag = false;
if (groups) {
for (var i in groups) {
if (groups[i]["id"] == group["id"]) {
groups[i] = group;
isExistFlag = true;
break;
}
}
}
if (!isExistFlag) {
groups.push(group);
}
saveLocalGroups(groups);
};
var deleteLocalGroup = function (group_id) {
var groups = getLocalGroups();
var _groups = [];
if (groups) {
for (var j in groups) {
if (groups[j]["id"] != group_id) {
_groups.push(groups[j]);
}
}
}
saveLocalGroups(_groups);
};
var getLocalGroups = function () {
var groups = []
try {
groups = wx.getStorageSync(weconstants.WE_DAKA_KEY_GROUPS)
} catch (e) {
}
return groups;
}
var getLocalGroup = function (group_id) {
try {
var groups = getLocalGroups()
if (groups && groups.length > 0) {
for (var i in groups) {
if (groups[i]["id"] == group_id) {
return groups[i];
}
}
}
} catch (e) {
}
return false;
}
var saveLocalGroupStatus = function (group_id, status) {
var data = {
status: status,
group_id: group_id
}
wx.setStorage({
key: weconstants.WE_DAKA_KEY_GROUP_STATUS,
data: data
});
};
var getLoalGroupStatus = function (group_id, cb) {
wx.getStorage({
key: weconstants.WE_DAKA_KEY_GROUP_STATUS,
success: function (res) {
if (res.data && res.data.status && res.data.group_id == group_id) {
cb(res.data.status);
}
wx.removeStorage({
key: weconstants.WE_DAKA_KEY_GROUP_STATUS,
})
}
})
}
var saveLocalGroupCalendar = function (user) {
try {
wx.setStorageSync(weconstants.WE_DAKA_KEY_GROUP_CALENDAR, user)
} catch (e) {
}
}
var getLocalGroupCalendar = function () {
var user = {}
try {
var value = wx.getStorageSync(weconstants.WE_DAKA_KEY_GROUP_CALENDAR)
if (value) {
user = value
}
} catch (e) {
// Do something when catch error
}
return user
}
var saveLocalStyle = function (style) {
try {
wx.setStorage({
key: weconstants.WE_DAKA_KEY_STYLE,
data: style
});
} catch (e) {
}
}
var getLocalStyle = function(){
var style = 'card'
try {
style = wx.getStorageSync(weconstants.WE_DAKA_KEY_STYLE)
} catch (e) {
}
return style;
}
module.exports = {
saveLocalGroups: saveLocalGroups,
saveLocalGroup: saveLocalGroup,
deleteLocalGroup: deleteLocalGroup,
getLocalGroups: getLocalGroups,
getLocalGroup: getLocalGroup,
getLoalGroupStatus: getLoalGroupStatus,
getClientGroups: getClientGroups,
getClientGroup: getClientGroup,
getClientGroupRank: getClientGroupRank,
getClientGroupFeed: getClientGroupFeed,
getClientGroupMember: getClientGroupMember,
getClientGroupHistory: getClientGroupHistory,
getTask: getTask,
createGroup: createGroup,
editGroup: editGroup,
joinGroup: joinGroup,
quitGroup: quitGroup,
dakaGroup: dakaGroup,
redakaGroup: redakaGroup,
imageGroup: imageGroup,
qrcodeGroup: qrcodeGroup,
shareGroup:shareGroup,
remindGroup: remindGroup,
saveLocalGroupCalendar: saveLocalGroupCalendar,
getLocalGroupCalendar: getLocalGroupCalendar,
saveLocalGroupStatus: saveLocalGroupStatus,
saveLocalStyle: saveLocalStyle,
getLocalStyle: getLocalStyle,
exportGroup:exportGroup
}; |
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('detail-view', 'Integration | Component | detail view', {
integration: true
});
test('it renders', function(assert) {
this.render(hbs`{{detail-view}}`);
assert.equal(this.$('.pull-right span.button:first').text().trim(), 'Delete');
assert.equal(this.$('.pull-right span.button:last').text().trim(), 'Close');
this.set('item', {
name: 'testitem',
description: 'testitem'
});
this.render(hbs`
{{detail-view selectedItem=item}}
`);
var woInstruct = this.$('.panel-body')
.text()
.replace('Click the name above or description below to edit.','')
.trim();
assert.equal(woInstruct, 'testitem');
});
|
// pages/orderRemind/orderRemind.js
Page({
data: {
carts: [{
id: 1,
cimg: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1436948145,4270509323&fm=200&gp=0.jpg',
ctitle: '猪肉猪肉猪肉猪肉猪肉猪肉猪肉猪肉猪肉猪',
cprice: 28.00,
ctype: '在线下单',
ctime: '2018-02-02 18:00',
cstate: '等待发货',
selected: false,
}, {
id: 2,
cimg: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1436948145,4270509323&fm=200&gp=0.jpg',
ctitle: '猪肉猪肉猪肉猪肉猪肉猪肉猪肉猪肉猪肉猪',
cprice: 28.00,
ctype: '在线下单',
ctime: '2018-02-02 18:00',
cstate: '等待发货',
selected: false,
}],
selectAllStatus: false,
},
onLoad: function (options) {
},
selectList: function (e) {
const index = e.currentTarget.dataset.index;
console.log("index" + index)
let carts = this.data.carts;
const selected = carts[index].selected;
carts[index].selected = !selected;
this.setData({
carts: carts
});
},
selectAll: function (e) {
let selectAllStatus = this.data.selectAllStatus;
selectAllStatus = !selectAllStatus;
let carts = this.data.carts;
for (let i = 0; i < carts.length; i++) {
carts[i].selected = selectAllStatus;
}
this.setData({
selectAllStatus: selectAllStatus,
carts: carts
})
},
orderDetails: function (e) {
var id = e.currentTarget.dataset.id;
wx.navigateTo({
url: '/pages/orderDetails/orderDetails?id=' + id,
})
},
}) |
var Person = [] || JSON.parse(localStorage.getItem('Person')); //設定一個物件Person用來記錄BMIDate (儲存於localStorage)
var btn = document.querySelector('.btn');
var BMI_text = document.querySelector('#BMI_text');
var list = document.querySelector('.list');
function bmi() { //計算bmi
var hei = document.getElementById('hei').value;
var wei = document.getElementById('wei').value;
var bmi = wei / Math.pow(hei * 0.01, 2);
var text = bmi.toFixed(1); //將bmi取自小數點後一位
//顯示BMI到main_p上
var main_p = document.getElementById('main_p');
main_p.textContent = text;
//記錄時間
var NowDate = new Date();
var year = NowDate.getFullYear();
var mon = NowDate.getMonth();
var day = NowDate.getDate();
var h = NowDate.getHours();
var m = NowDate.getMinutes();
var time = year+ '年' + mon + '月' + day + '日 ' + h + '時' + m + '分';
//變換#circle,#re,#main,#BMI_text的顏色
function color(text) {
if (text < 18.5) {
return 'thin'
} else if (text >= 18.5 && text < 24) {
return 'perfect'
} else if (text >= 24 && text < 27) {
return 'over-weight'
} else if (text >= 27 && text < 35) {
return 'heavy'
} else if (text >= 35) {
return 'obese'
} else{
return 'perfect'
}
}
var addColor = color(text);
document.getElementById('circle').className = addColor;
document.getElementById('re').className = 'fa fa-repeat '+addColor;
document.getElementById('main').className = 'text-'+addColor;
document.getElementById('BMI_text').className = 'text-'+addColor;
//設定一個物件man,用來儲存該筆輸入之資料(身高、體重、BMI、健康狀況、時間)
var man = {
h: hei,
w: wei,
bm: text,
result: function() {
if (man.bm < 18.5) {
return '過輕'
} else if (man.bm >= 18.5 && man.bm < 24) {
return '理想'
} else if (man.bm >= 24 && man.bm < 27) {
return '過重'
} else if (man.bm >= 27 && man.bm < 30) {
return '輕度肥胖'
} else if (man.bm >= 30 && man.bm < 35) {
return '中度肥胖'
} else if (man.bm >= 35) {
return '重度肥胖'
}
},
time: time
}
Person.push(man); //將 物件man 寫入 物件Person (localStorage)內
var Str = JSON.stringify(Person);
localStorage.setItem('Person', Str);
addBMI(Person); //取得當前最新之BMI體態
addDate(Person); //紀錄BMI的函數
addcolor(Person);
}
function addBMI(Person) {
for (var i = 0; i < Person.length; i++) {
var BMItext = Person[i].result()
}
BMI_text.innerHTML = BMItext; //輸出體態
}
function addcolor(Person) {
if (Person.bm < 18.5) {
return 'add-thin'
} else if (Person.bm >= 18.5 && Person.bm < 24) {
return 'add-perfect'
} else if (Person.bm >= 24 && Person.bm < 27) {
return 'add-over-weight'
} else if (Person.bm >= 27 && Person.bm < 35) {
return 'add-heavy'
} else if (Person.bm >= 35) {
return 'add-obese'
} else{
return ''
}
}
function addDate(Person) { //紀錄BMI歷史
var personDate = ""; //空字串,用來記錄personBMI
for (var i = 0; i < Person.length; i++) {
personDate += '<li class='+addcolor(Person[i])+'>' + Person[i].result() + '   BMI:' + Person[i].bm + '  ' + '身高' + Person[i].h + '  ' + '體重' + Person[i].w + '   ' + Person[i].time + '</li>'
}
list.innerHTML = personDate;
}
/*按下btn作用之(監聽)事件*/
btn.addEventListener('click', bmi, false);
/*jQ*/
$(document).ready(function() {
$('.btn').click(function(event) {
$('.btn').hide();
$('.BMI').fadeIn();
});
$('#re').click(function(event) {
$('.BMI').hide();
$('.btn').fadeIn();
});
// $(document).scroll(function(e){
// if($(this).scrollTop()>1){ /* 當畫面離開頂部時*/
// $('.footer').css({'position':''});
// }
// })
});
/*筆記*/
// JavaScript parseInt() 函数 http://www.w3school.com.cn/jsref/jsref_parseInt.asp
// Math.pow(x,y) = 返回 x^y 之值(x的y次方)
// toFixed(#) = 將#位之後的數字四捨五入
// 為HTML空白屬性; 為全形空白 |
/* jshint browser: true */
/* jshint unused: false */
/* global Backbone, $, window, arangoHelper, templateEngine */
(function () {
'use strict';
window.QueryManagementView = Backbone.View.extend({
el: '#content',
id: '#queryManagementContent',
templateActive: templateEngine.createTemplate('queryManagementViewActive.ejs'),
templateSlow: templateEngine.createTemplate('queryManagementViewSlow.ejs'),
table: templateEngine.createTemplate('arangoTable.ejs'),
active: true,
shouldRender: true,
timer: 0,
refreshRate: 2000,
initialize: function () {
var self = this;
this.activeCollection = new window.QueryManagementActive();
this.slowCollection = new window.QueryManagementSlow();
this.convertModelToJSON(true);
self.interval = window.setInterval(function () {
if (window.location.hash === '#queries' && window.VISIBLE && self.shouldRender &&
arangoHelper.getCurrentSub().route === 'queryManagement') {
if (self.active) {
if ($('#arangoQueryManagementTable').is(':visible')) {
self.convertModelToJSON(true);
}
} else {
if ($('#arangoQueryManagementTable').is(':visible')) {
self.convertModelToJSON(false);
}
}
}
}, self.refreshRate);
},
remove: function () {
if (this.interval) {
window.clearInterval(this.interval);
}
this.$el.empty().off(); /* off to unbind the events */
this.stopListening();
this.unbind();
delete this.el;
return this;
},
events: {
'click #deleteSlowQueryHistory': 'deleteSlowQueryHistoryModal',
'click #arangoQueryManagementTable .fa-minus-circle': 'deleteRunningQueryModal'
},
tableDescription: {
id: 'arangoQueryManagementTable',
titles: ['ID', 'Query String', 'Bind parameters', 'User', 'Runtime', 'Started', ''],
rows: [],
unescaped: [false, false, false, false, false, false, true]
},
deleteRunningQueryModal: function (e) {
this.killQueryId = $(e.currentTarget).attr('data-id');
var buttons = [];
var tableContent = [];
tableContent.push(
window.modalView.createReadOnlyEntry(
undefined,
'Running Query',
'Do you want to kill the running query?',
undefined,
undefined,
false,
undefined
)
);
buttons.push(
window.modalView.createDeleteButton('Kill', this.killRunningQuery.bind(this))
);
window.modalView.show(
'modalTable.ejs',
'Kill Running Query',
buttons,
tableContent
);
$('.modal-delete-confirmation strong').html('Really kill?');
},
killRunningQuery: function () {
this.collection.killRunningQuery(this.killQueryId, this.killRunningQueryCallback.bind(this));
window.modalView.hide();
},
killRunningQueryCallback: function () {
this.convertModelToJSON(true);
this.renderActive();
},
deleteSlowQueryHistoryModal: function () {
var buttons = [];
var tableContent = [];
tableContent.push(
window.modalView.createReadOnlyEntry(
undefined,
'Slow Query Log',
'Do you want to delete the slow query log entries?',
undefined,
undefined,
false,
undefined
)
);
buttons.push(
window.modalView.createDeleteButton('Delete', this.deleteSlowQueryHistory.bind(this))
);
window.modalView.show(
'modalTable.ejs',
'Delete Slow Query Log',
buttons,
tableContent
);
},
deleteSlowQueryHistory: function () {
this.collection.deleteSlowQueryHistory(this.slowQueryCallback.bind(this));
window.modalView.hide();
},
slowQueryCallback: function () {
this.convertModelToJSON(false);
this.renderSlow();
},
render: function () {
var options = arangoHelper.getCurrentSub();
if (options.params.active) {
this.active = true;
this.convertModelToJSON(true);
} else {
this.active = false;
this.convertModelToJSON(false);
}
},
addEvents: function () {
var self = this;
$('#queryManagementContent tbody').on('mousedown', function () {
clearTimeout(self.timer);
self.shouldRender = false;
});
$('#queryManagementContent tbody').on('mouseup', function () {
self.timer = window.setTimeout(function () {
self.shouldRender = true;
}, 3000);
});
},
renderActive: function () {
this.$el.html(this.templateActive.render({}));
$(this.id).append(this.table.render({
content: this.tableDescription,
type: {
1: 'pre',
2: 'pre'
}
}));
$('#activequeries').addClass('arango-active-tab');
this.addEvents();
},
renderSlow: function () {
this.$el.html(this.templateSlow.render({}));
$(this.id).append(this.table.render({
content: this.tableDescription,
type: {
1: 'pre',
2: 'pre'
}
}));
$('#slowqueries').addClass('arango-active-tab');
this.addEvents();
},
convertModelToJSON: function (active) {
var self = this;
var rowsArray = [];
if (active === true) {
this.collection = this.activeCollection;
} else {
this.collection = this.slowCollection;
}
this.collection.fetch({
success: function () {
self.collection.each(function (model) {
var button = '';
if (active) {
button = '<i data-id="' + model.get('id') + '" class="fa fa-minus-circle"></i>';
}
rowsArray.push([
model.get('id'),
model.get('query'),
JSON.stringify(model.get('bindVars'), null, 2),
model.get('user'),
model.get('runTime').toFixed(2) + 's',
model.get('started'),
button
]);
});
var message = 'No running queries.';
if (!active) {
message = 'No slow queries.';
}
if (rowsArray.length === 0) {
rowsArray.push([
message,
'',
'',
'',
'',
''
]);
} else {
// sort by query id, descending
rowsArray = rowsArray.sort(function(l, r) {
// normalize both inputs to strings (in case they are numbers)
l = String(l[0]).padStart(20, "0");
r = String(r[0]).padStart(20, "0");
if (l === r) {
return 0;
}
return l < r ? 1 : -1;
});
}
self.tableDescription.rows = rowsArray;
if (active) {
self.renderActive();
} else {
self.renderSlow();
}
}
});
}
});
}());
|
import React from 'react'
function About() {
const [aboutTitle] = React.useState({
mainHeader: "About Me",
text: "'Lorem Ipsum fhvjdvjd jkhvdjrhbgvkd jnfkjdhrgkd\
bfjdhbvjd hbjhdfbvj bvjhdbvkdj bvjhdfbvjdh hjbfxjvhf bjdhgkd\
hbvjhdfbgj bjvhdfbvgkj bvhjkdfbkgjdr bjkbdfkvd "
})
const [title] = React.useState([
{
id: 1,
header: 'Name',
info: 'Nisha Thapa'
},{
id: 2,
header: 'Email',
info: 'Nisha Thapa'
},{
id: 3,
header: 'LinkedIn',
info: 'Nisha Thapa'
},{
id: 4,
header: 'Profile',
info: 'Nisha Thapa'
}
]);
return (
<div className="about">
<div className="common">
<h1 className="main_header">{aboutTitle.mainHeader}</h1>
<p className="main_content">
{aboutTitle.text}
</p>
<div className="commonBorder"></div>
</div>
<div className="row">
<div className="container">
<h1>Hi There</h1>
<div className="about-info">
<p>Lorem Ipsum fhvjdvjd jkhvdjrhbgvkd jnfkjdhrgkd\
bfjdhbvjd hbjhdfbvj bvjhdbvkdj bvjhdfbvjdh hjbfxjvhf bjdhgkd\
hbvjhdfbgj bjvhdfbvgkj </p>
<p>Lorem Ipsum fhvjdvjd jkhvdjrhbgvkd jnfkjdhrgkd\
bfjdhbvjd hbjhdfbvj bvjhdbvkdj bvjhdfbvjdh hjbfxjvhf bjdhgkd\
hbvjhdfbgj bjvhdfbvgkj bvhjkdfbkgjdr </p>
<p>Lorem Ipsum fhvjdvjd jkhvdjrhbgvkd jnfkjdhrgkd\
bfjdhbvjd hbjhdfbvj bvjhdbvkdj bvjhdfbvjdh hjbfxjvhf bjdhgkd\
hbvjhdfbgj bjvhdfbvgkj bvhjkdfbkgjdr bjkbdfkvd</p>
</div>
<div className="contact-info">
<div className='row'>
{title.map(data => (
<div className="col-6 info">
<strong>{data.header}</strong>
<p>{data.info}</p>
</div>
))}
</div>
</div>
</div>
</div>
</div>
)
}
export default About
|
export * from './Home.view';
|
import { findAll, find, render } from '@ember/test-helpers';
import EmberObject from '@ember/object';
import { test } from 'qunit';
import hbs from 'htmlbars-inline-precompile';
import { module } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
module('Integration | Component | slots-picker/selection-single', function (hooks) {
setupRenderingTest(hooks);
test('it renders with no selection', async function (assert) {
assert.expect(1);
await render(hbs`{{slots-picker/selection-single}}`);
assert.notOk(findAll('p').length, 'should not render any message');
});
test('it renders with a selection', async function (assert) {
assert.expect(4);
this.set('baseProps', EmberObject.create({
multiSelected: [
EmberObject.create({
slotPickerLongDayLabel: 'LABEL',
slotPickerStartTimeLabel: 'START',
slotPickerEndTimeLabel: 'END'
})
]
}));
await render(hbs`{{slots-picker/selection-single baseProps=this.baseProps}}`);
assert.ok(findAll('p').length, 'should render a p tag if there is a selection');
assert.ok(find('p').textContent.trim().match(/LABEL/), 'should contain longDayLabel');
assert.ok(find('p').textContent.trim().match(/START/), 'should contain startTimeLabel');
assert.ok(find('p').textContent.trim().match(/END/), 'should contain endTimeLabel');
});
});
|
import React,{Component} from 'react';
import PropTypes from 'prop-types';
import ShelfChanger from './ShelfChanger.js';
class Book extends Component{
render(){
const {book,changeShelf,shelf,books}= this.props;
const noImage = book.imageLinks && book.imageLinks.thumbnail? book.imageLinks.thumbnail : "https://islandpress.org/sites/default/files/400px%20x%20600px-r01BookNotPictured.jpg";
return(
<div>
<div className="book" id={book.id}>
<div className="book-top">
<div className="book-cover" style={{ width: 128, height: 193, backgroundImage: `url(${noImage})` }}></div>
<ShelfChanger book={book} changeShelf ={changeShelf} shelf={shelf} books={books}/>
</div>
<div className="book-title">{book.title}</div>
<div className="book-authors">{book.authors}</div>
</div>
</div>
);
}
};
Book.propTypes = {
changeShelf: PropTypes.func.isRequired,
book: PropTypes.object.isRequired
};
export default Book;
|
// { "framework": "Vue"}
if(typeof app=="undefined"){app=weex}
if(typeof eeuiLog=="undefined"){var eeuiLog={_:function(t,e){var s=e.map(function(e){return e="[object object]"===Object.prototype.toString.call(e).toLowerCase()?JSON.stringify(e):e});if(typeof this.__m==='undefined'){this.__m=app.requireModule('debug')}this.__m.addLog(t,s)},debug:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("debug",e)},log:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("log",e)},info:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("info",e)},warn:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("warn",e)},error:function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];this._("error",e)}}}
/******/ (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, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // 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 = "./src/pages/runPages/runpages.vue?entry=true");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./src/pages/runPages/runpages.vue?entry=true":
/*!****************************************************!*\
!*** ./src/pages/runPages/runpages.vue?entry=true ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(/*! !C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter?id=data-v-f3399b24!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=styles&index=0!./runpages.vue */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-rewriter.js?id=data-v-f3399b24!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=styles&index=0!./src/pages/runPages/runpages.vue")
)
/* script */
__vue_exports__ = __webpack_require__(/*! !C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader!babel-loader!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=script&index=0!./runpages.vue */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\script-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\node_modules\\_babel-loader@8.1.0@babel-loader\\lib\\index.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=script&index=0!./src/pages/runPages/runpages.vue")
/* template */
var __vue_template__ = __webpack_require__(/*! !C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler?id=data-v-f3399b24!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector?type=template&index=0!./runpages.vue */ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\template-compiler.js?id=data-v-f3399b24!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=template&index=0!./src/pages/runPages/runpages.vue")
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {eeuiLog.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "F:\\workspace\\weexZruup\\zruupApp\\src\\pages\\runPages\\runpages.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__._scopeId = "data-v-f3399b24"
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
if (typeof __register_static_styles__ === "function") {
__register_static_styles__(__vue_options__._scopeId, __vue_styles__)
}
module.exports = __vue_exports__
module.exports.el = 'true'
new Vue(module.exports)
/***/ }),
/***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\script-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\node_modules\\_babel-loader@8.1.0@babel-loader\\lib\\index.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=script&index=0!./src/pages/runPages/runpages.vue":
/*!*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/script-loader.js!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/node_modules/_babel-loader@8.1.0@babel-loader/lib!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=script&index=0!./src/pages/runPages/runpages.vue ***!
\*******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var amap = app.requireModule('eeuiAmap');
var eeui = app.requireModule('eeui');
var globalEvent = weex.requireModule('globalEvent');
/* harmony default export */ __webpack_exports__["default"] = ({
data: function data() {
return {
btnShow: false,
runOverList: {}
};
},
methods: {
stop: function stop() {
this.btnShow = true;
},
counti: function counti() {
this.btnShow = false;
},
over: function over() {
var self = this;
eeui.confirm({
title: "温馨提示",
message: "你确定结束吗?",
buttons: ["取消", "确定"]
}, function (result) {
if (result.status == "click" && result.title == "确定") {
eeui.openPage({
url: 'rundetailout.js',
statusBarColor: '#1eb76e',
pageName: '运动详细',
animated: false,
params: {
runOverList: self.runOverList
}
}, function (result) {//......
});
}
});
}
},
created: function created() {
// 添加 字体图标
var self = this;
var domModule = weex.requireModule('dom');
domModule.addRule('fontFace', {
'fontFamily': "iconfont",
'src': "url('http://at.alicdn.com/t/font_1628280_razig2u9kxg.ttf')"
}); // globalEvent.addEventListener("runDataCallback", function (res) {
// self.runOverList=res.install
// // eeuiLog.log("runDataCallback",self.runOverList)
// })
}
});
/***/ }),
/***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-loader.js!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\style-rewriter.js?id=data-v-f3399b24!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=styles&index=0!./src/pages/runPages/runpages.vue":
/*!*********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-loader.js!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/style-rewriter.js?id=data-v-f3399b24!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=styles&index=0!./src/pages/runPages/runpages.vue ***!
\*********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = {
"app": {
"backgroundColor": "#0d2236"
},
"navbarb": {
"width": "750",
"height": "100",
"backgroundColor": "#0d2236"
},
"headtext": {
"fontSize": "30",
"color": "#ffffff"
},
"map": {
"width": 750,
"height": 800,
"position": "relative"
},
"mapborad": {
"width": 690,
"height": 320,
"backgroundColor": "#ffffff",
"position": "absolute",
"top": 150,
"left": 30,
"borderRadius": 10
},
"runNumbox": {
"flexDirection": "row",
"marginLeft": 30,
"marginTop": 20
},
"runNum": {
"fontSize": 100,
"fontWeight": "bold"
},
"runword": {
"fontSize": 32,
"color": "#4f4f4f",
"marginTop": 60,
"marginLeft": 10
},
"propList": {
"flexDirection": "row",
"width": 690,
"marginTop": 50
},
"propitem": {
"width": 230,
"alignItems": "center"
},
"speednum": {
"fontSize": 38,
"fontWeight": "bold",
"marginBottom": 20
},
"runitem": {
"width": 230,
"flexDirection": "row",
"justifyContent": "center",
"alignItems": "center",
"marginBottom": 20
},
"speedTitle": {
"fontSize": 27,
"color": "#4f4f4f"
},
"mapBtn": {
"width": 750,
"flexDirection": "row",
"justifyContent": "center",
"position": "absolute",
"bottom": 80,
"left": 0
},
"IConBtn": {
"width": 178,
"height": 178,
"borderRadius": 100,
"backgroundColor": "#08ce7f",
"justifyContent": "center",
"alignItems": "center"
},
"actbtn": {
"fontSize": 32,
"color": "#ffffff"
},
"GPSinfo": {
"flexDirection": "row",
"position": "absolute",
"top": 30,
"right": 20
},
"GPStext": {
"fontSize": 27
},
"propicon": {
"fontSize": 40,
"color": "#4f4f4f",
"fontFamily": "iconfont",
"marginRight": 10
},
"GPSicon": {
"fontSize": 30,
"fontFamily": "iconfont"
},
"btnicon": {
"fontSize": 70,
"fontFamily": "iconfont",
"color": "#ffffff",
"marginBottom": 5
},
"Iconall": {
"flexDirection": "row"
},
"red": {
"backgroundColor": "rgb(212,29,16)"
}
}
/***/ }),
/***/ "C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\template-compiler.js?id=data-v-f3399b24!C:\\Users\\10844\\AppData\\Roaming\\npm\\node_modules\\eeui-cli\\lib\\loaders\\eeui-loader\\lib\\selector.js?type=template&index=0!./src/pages/runPages/runpages.vue":
/*!*********************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/template-compiler.js?id=data-v-f3399b24!C:/Users/10844/AppData/Roaming/npm/node_modules/eeui-cli/lib/loaders/eeui-loader/lib/selector.js?type=template&index=0!./src/pages/runPages/runpages.vue ***!
\*********************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', {
staticClass: ["app"]
}, [_c('navbar', {
staticClass: ["navbarb"]
}, [_c('navbar-item', {
attrs: {
"type": "title"
}
}, [_c('text', {
staticClass: ["headtext"]
}, [_vm._v("跑步中")])])], 1), _vm._m(0), _c('div', {
staticClass: ["mapBtn"]
}, [(!_vm.btnShow) ? _c('div', {
staticClass: ["IConBtn"],
on: {
"click": _vm.stop
}
}, [_c('text', {
staticClass: ["btnicon"]
}, [_vm._v("")]), _c('text', {
staticClass: ["actbtn"]
}, [_vm._v("暂停")])]) : _vm._e(), (_vm.btnShow) ? _c('div', {
staticClass: ["Iconall"]
}, [_c('div', {
staticClass: ["IConBtn"],
on: {
"click": _vm.counti
}
}, [_c('text', {
staticClass: ["btnicon"]
}, [_vm._v("")]), _c('text', {
staticClass: ["actbtn"]
}, [_vm._v("继续")])]), _c('div', {
staticClass: ["IConBtn", "red"],
staticStyle: {
marginLeft: "20"
},
on: {
"click": _vm.over
}
}, [_c('text', {
staticClass: ["btnicon"],
staticStyle: {
fontSize: "55",
marginBottom: "15"
}
}, [_vm._v("")]), _c('text', {
staticClass: ["actbtn"]
}, [_vm._v("结束")])])]) : _vm._e()])], 1)
},staticRenderFns: [function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', {
staticClass: ["map"]
}, [_c('div', {
staticClass: ["mapborad"]
}, [_c('div', {
staticClass: ["runNumbox"]
}, [_c('text', {
staticClass: ["runNum"]
}, [_vm._v("0.00")]), _c('text', {
staticClass: ["runword"]
}, [_vm._v("公里")])]), _c('div', {
staticClass: ["GPSinfo"]
}, [_c('text', {
staticClass: ["GPStext"]
}, [_vm._v("GPS信号弱")]), _c('text', {
staticClass: ["GPSicon"]
}, [_vm._v("")])]), _c('div', {
staticClass: ["propList"]
}, [_c('div', {
staticClass: ["propitem"]
}, [_c('div', {
staticClass: ["runitem"]
}, [_c('text', {
staticClass: ["propicon"]
}, [_vm._v("")]), _c('text', {
staticClass: ["speedTitle"]
}, [_vm._v("平均配速")])]), _c('text', {
staticClass: ["speednum"]
}, [_vm._v("00`00``")])]), _c('div', {
staticClass: ["propitem"]
}, [_c('div', {
staticClass: ["runitem"]
}, [_c('text', {
staticClass: ["propicon"]
}, [_vm._v("")]), _c('text', {
staticClass: ["speedTitle"]
}, [_vm._v("用时")])]), _c('text', {
staticClass: ["speednum"]
}, [_vm._v("00:00:00")])]), _c('div', {
staticClass: ["propitem"]
}, [_c('div', {
staticClass: ["runitem"]
}, [_c('text', {
staticClass: ["propicon"]
}, [_vm._v("")]), _c('text', {
staticClass: ["speedTitle"]
}, [_vm._v("热量(千卡)")])]), _c('text', {
staticClass: ["speednum"]
}, [_vm._v("5.6")])])])])])
}]}
module.exports.render._withStripped = true
/***/ })
/******/ }); |
function testJS() {
var name = jQuery("#name").val();
jQuery.load("next.html", function() {
jQuery("#here").html(name);
});
}
|
import React from 'react';
import {Card, CardImg, CardImgOverlay,CardTitle} from 'reactstrap';
function RenderMenuItem({ dish, onClick }){
return(
<Card onClick={() => onClick(dish.id)}>
<CardImg width="100%" src={dish.image} alt={dish.name}></CardImg>
<CardImgOverlay>
<CardTitle>{dish.name}</CardTitle>
</CardImgOverlay>
</Card>
);
}
const Menu = (props) => {
const menu = props.dishes.map((dish) => {
return(
<div key={dish.id} className="col-12 col-md-5 m-1">
<RenderMenuItem dish={dish} onClick={props.onClick}/>
</div>
);
});
return (
<div className="container">
<div className="row">
{menu}
</div>
</div>
);
}
{/*
renderDish(dish){
if (dish !=null) {
return(
<div className="col-12 col-md-5 m-1">
<Card>
<CardImg width="100%" src={dish.image} alt={dish.name}></CardImg>
<CardBody>
<CardTitle><b>{dish.name}</b></CardTitle>
<CardText>{dish.description}</CardText>
</CardBody>
</Card>
</div>
);
}
else {
return(
<div></div>
);
}
}
renderComment(dish){
if(dish != null) {
const dishComments = dish.comments.map((comment) => {
return (
<ul class = "list-unstyled">
<li>{comment.comment}</li>
<li>-- {comment.author} {comment.date.substr(0, 10)}</li>
</ul>
);
})
return(
<div>
<h4>Comments</h4>
{dishComments}
</div>
);
} else {
return(
<div></div>
);
}
}
*/}
export default Menu; |
let obj = {
name: 'Saidur',
addr: 'Manikganj',
sayhello: function () {
console.log('Hello');
},
};
// delete obj.addr;
// delete obj.sayhello;
// how to get object length
Object.size = function (obj) {
var size = 0,
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
console.log(Object.size(obj));
|
const router = require("express").Router();
const bcrypt = require("bcrypt");
const User = require("../schemas/user");
const { body, validationResult } = require('express-validator');
router.post("/register", [
body('name').isString().isAlphanumeric().isLength({min: 6, max: 255}).exists(),
body('email').isEmail().isLength({min: 6, max: 255}).exists(),
body('password').isString().isAlphanumeric().isLength({min: 10, max: 1023}).exists(),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty())
return res.status(400).json({ errors: errors.array() });
const registered = await User.findOne({ email: req.body.email });
if (registered)
return res.status(400).json({ error: "That email is already registered" });
const salt = await bcrypt.genSalt(10);
const password = await bcrypt.hash(req.body.password, salt);
const user = new User({
name: req.body.name,
email: req.body.email,
password,
});
try {
const savedUser = await user.save();
res.json({ error: null, data: { userId: savedUser._id } });
} catch (error) {
res.status(400).json({ error });
}
});
module.exports = router;
|
import Vue from 'vue'
import VueRouter from 'vue-router'
// import Discovery from '../views/discovery'
// import Mvs from '../views/mvs'
// import Mv from '../views/mvs/detail'
// import Playlists from '../views/playlists'
// import PlaylistDetail from '../views/playlists/detail'
// import Songs from '../views/songs'
const Discovery = () => import('@/views/discovery')
const Mvs = () => import('@/views/mvs')
const Mv = () => import('@/views/mvs/detail')
const Playlists = () => import('@/views/playlists')
const PlaylistDetail = () => import('@/views/playlists/detail')
const Songs = () => import('@/views/songs')
const Search = () => import('@/views/search')
const SearchSongs = () => import('@/views/search/songs')
const SearchPlaylists = () => import('@/views/search/playlists')
const SearchMvs = () => import('@/views/search/mvs')
// 内容需要居中的页面
export const layoutCenterNames = ['discovery', 'playlists', 'songs', 'mvs']
// 侧边栏菜单的页面
export const menuRoutes = [
{
path: '/discovery',
name: 'discovery',
component: Discovery,
meta: {
title: '发现音乐',
icon: 'music'
}
},
{
path: '/playlists',
name: 'playlists',
component: Playlists,
meta: {
title: '推荐歌单',
icon: 'playlist-menu'
},
children: [
{
path: '/playlists/detail/:id',
name: 'playlistDetail',
component: PlaylistDetail
}
]
},
{
path: '/songs',
name: 'songs',
component: Songs,
meta: {
title: '最新音乐',
icon: 'yinyue'
}
},
{
path: '/mvs',
name: 'mvs',
component: Mvs,
meta: {
title: '最新MV',
icon: 'mv'
}
}
]
// hack router push callback
// 解决重复触发了同一个路由 控制台出现报错的情况 这个错误是 vur-router更新以后新出现的错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)
export default new VueRouter({
mode: 'hash',
routes: [
{
path: '/',
redirect: '/discovery'
},
// {
// path: '/playlist/:id',
// name: 'playlist',
// component: PlaylistDetail
// },
{
path: '/search/:keywords',
name: 'search',
component: Search,
props: true,
children: [
{
path: '/',
redirect: 'songs'
},
{
path: 'songs',
name: 'searchSongs',
component: SearchSongs
},
{
path: 'playlists',
name: 'searchPlaylists',
component: SearchPlaylists
},
{
path: 'mvs',
name: 'searchMvs',
component: SearchMvs
}
]
},
{
path: '/mv/:id', // 这里的:id对应下面的route.params.id
name: 'mv',
component: Mv,
props: (route) => ({ id: +route.params.id })
},
...menuRoutes
]
})
|
var constant = require('../constants.js');
//GET: all regions
exports.get = function (req,res){
var name = req.params.name;
console.log(constant['CourseType']);
if( name in constant){
res.json({
status: 'ok',
messages: 'successed',
data: constant[name]
});
}else{
res.json({
status: 'fail',
messages: 'no constants for ' + name,
data: []
});
}
}
|
//入院病情
var dic_rybq = [
{"value":"1","text":"1 - 有"},
{"value":"2","text":"2 - 临床未确定"},
{"value":"3","text":"3 - 情况不明"},
{"value":"4","text":"4 - 无"}
] |
const express = require('express');
// Define the router using the express router
const userRouter = express.Router();
const userController = require('../controllers/account-controller')
userRouter.get('/', userController.authenticate)
userRouter.get('/email/:email', userController.authenticate);
userRouter.post('/', userController.addUser)
module.exports = userRouter
|
import React from "react";
import { render } from "@testing-library/react";
import ExternalLink from "../src";
const mockUrl = "http://wegalvanize.com";
describe("ExternalLink", () => {
it("should render with text passed as children", () => {
const { getByText } = render(<ExternalLink href={mockUrl}>ExternalLink text</ExternalLink>);
expect(getByText(/ExternalLink text/i)).toBeVisible();
});
it("should render href on a tag", () => {
render(<ExternalLink href={mockUrl}>example text</ExternalLink>);
expect(document.querySelector("a").getAttribute("href")).toBe(mockUrl);
});
});
|
import React from "react";
import PropTypes from "prop-types";
import { Dialog } from "@material-ui/core";
const CustomDialog = ({ open, onClose, children, size }) => {
return (
<Dialog open={open} onClose={onClose} fullWidth maxWidth={size}>
{children}
</Dialog>
);
};
CustomDialog.prototype = {
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired
};
export default CustomDialog;
|
let userStorageName = 'user';
function createUser(){
let name = prompt('Enter Your Name');
localStorage.setItem(userStorageName, name);
return localStorage.getItem(userStorageName);
}
// window.localStorage.removeItem(userStorageName);
// localStorage.clear();
document.addEventListener('DOMContentLoaded', ()=>{
// elms
let joinBtns = document.querySelectorAll('.join-channel');
let msgForm = document.querySelector('#msg-form');
let createChannelForm = document.querySelector('#create-channel');
let result = document.querySelector('#note');
let channelHeader = document.querySelector('#channel-header');
let msgs = document.querySelector('#msgs');
let channelsContainer = document.querySelector('#channels-container');
// get user or create one
let user = localStorage.getItem(userStorageName);
if(!user)
user = createUser();
result.innerHTML = `Welcome ${user}`;
// start socket
let socket = io.connect(location.protocol+'//'+document.domain+':'+location.port);
socket.on('connect', ()=>{
// every join button should emit event
joinBtns.forEach(button=>{
button.onclick = (e)=>{
let channelName = button.dataset.name;
joinBtns.forEach((btn)=>{btn.classList.remove('active')});
button.classList.add('active');
localStorage.setItem('lastChannel', channelName);
socket.emit('joinChannel', {'channelName': channelName, 'username': user});
};
});
createChannelForm.onsubmit = (e)=>{
let channelName = e.target.children.channelName.value;
e.target.children.channelName.value = '';
if (channelName)
socket.emit('createChannel', channelName);
return false;
};
let lastChannel = localStorage.getItem('lastChannel');
if (lastChannel){
document.querySelector(`#${lastChannel}`).click();
}
});
socket.on('reloadChannels', (channels)=>{
console.log(channels);
channelsContainer.innerHTML = '';
for(channel in channels){
info = JSON.stringify( channels[channel] ).replace(/,/g, ',\n');
html = `
<li class="join-channel" id="${ channel }" data-name="${ channel }">
<div class="d-flex bd-highlight">
<div class="user_info">
<span>${ channel }</span>
<span class="info d-none">${ info }</span>
</div>
</div>
</li>
`
channelsContainer.innerHTML += html;
}
let joinBtns = document.querySelectorAll('.join-channel');
joinBtns.forEach(button=>{
button.onclick = (e)=>{
let channelName = button.dataset.name;
socket.emit('joinChannel', {'channelName': channelName, 'username': user});
};
});
});
socket.on('afterJoin', (data)=>{
document.querySelector('#'+data.name+' .info').innerHTML = JSON.stringify(data.info).replace(/,/g, ',\n');
if (data.prevChannelName)
document.querySelector('#'+data.prevChannelName+' .info').innerHTML = JSON.stringify(data.prevChannel).replace(/,/g, ',\n');
channelHeader.innerHTML = `Welcome To ${data.name}`
msgForm.dataset.name = data.name;
result.innerHTML = `${data.username} is now in`
msgs.innerHTML = ''
for(msg of data.info.msgs){
let html = `
<div class="d-flex ${ msg.sender === user? 'justify-content-end' : 'justify-content-start' } mb-4">
<div class="msg_cotainer ${ msg.sender === user? 'msg_cotainer_send' : '' }">
${ msg.msg }
<span class="msg_time">${ msg.sender }</span>
</div>
</div>
`
msgs.innerHTML += (html);
}
msgs.scrollBy(0, msgs.scrollHeight);
});
msgForm.onsubmit = (e)=>{
let channelName = e.target.dataset.name;
let msg = e.target.querySelector('#msg-area').value;
if (channelName && msg){
e.target.querySelector('#msg-area').value = '';
socket.emit('sendMsg', {'msg': msg, 'channelName': channelName, 'senderName': user});
}
return false;
};
socket.on('spreadMsg', (data)=>{
document.querySelector('#'+data.name+' .info').innerHTML = JSON.stringify(data.info).replace(/,/g, ',\n');
let html = `
<div class="d-flex ${ data.sender === user? 'justify-content-end' : 'justify-content-start' } mb-4">
<div class="msg_cotainer ${ data.sender === user? 'msg_cotainer_send' : '' }">
${ data.msg }
<span class="msg_time">${ data.sender }</span>
</div>
</div>
`
msgs.innerHTML += (html);
msgs.scrollBy(0, msgs.scrollHeight);
});
}); |
import React from 'react'
import { positions, gender } from '../dictionary'
import allUser from '../storeMobx/allUser.js'
import TextInput from '../components/TextInput.jsx'
import SelectList from '../components/SelectList.jsx'
import DateInput from '../components/DateInput.jsx'
import RadioInput from '../components/RadioInput.jsx'
import CheckInput from '../components/CheckInput.jsx'
import MultiSelectCheckbox from '../components/MultiSelectCheckbox.jsx'
class AddUser extends React.Component {
constructor(props) {
super(props)
this.state = {
infoUser: {
surname: '',
name: '',
patronymic: '',
position: 0,
dateOfBirth: '',
gender: 1,
dateEmployment: '',
dateOfDismissal: '',
drivingLicence: true,
colleagues: []
}
}
}
createNewId(array) {
let isGoodId = false
let newId
while (!isGoodId) {
newId = Math.round(Math.random() * 1000000)
let count = 0
for (let i = 0; i < array.length; i++) {
if (array[i].id === newId) count++
}
isGoodId = count === 0 ? true : false
}
return newId
};
insertUser = () => {
document.querySelectorAll('.is-invalid').forEach(n => n.classList.remove('is-invalid'))
if (!this.validateFields()) return
allUser.insertUser(this.state.infoUser)
this.props.history.push("/")
}
// Валидация полей
validateFields() {
let isGood = true
isGood &= this.validateName("name")
isGood &= this.validateSurname("surname")
isGood &= this.validatePosition("position")
isGood &= this.validateDateOfBirth("dateOfBirth")
isGood &= this.validateGender("gender")
isGood &= this.validateDateEmployment("dateEmployment")
isGood &= this.validateDateOfDismissal("dateOfDismissal")
return isGood
}
validateName(id) {
if (!Boolean(this.state.infoUser.name)) {
this.setIsInvalid(id)
return false
}
return true
}
validateSurname(id) {
if (!Boolean(this.state.infoUser.surname)) {
this.setIsInvalid(id)
return false
}
return true
}
validatePosition(id) {
if (!Boolean(this.state.infoUser.position)) {
this.setIsInvalid(id)
return false
}
return true
}
validateDateOfBirth(id) {
if (!Boolean(this.state.infoUser.dateOfBirth)) {
this.setIsInvalid(id)
return false
}
return true
}
validateGender(id) {
if (!Boolean(this.state.infoUser.gender)) {
this.setIsInvalid(id)
return false
}
return true
}
validateDateEmployment(id) {
if (!Boolean(this.state.infoUser.dateEmployment)) {
this.setIsInvalid(id)
return false
}
return true
}
validateDateOfDismissal(id) {
if (!Boolean(this.state.infoUser.dateOfDismissal)) {
return true
}
else if (this.state.infoUser.dateOfDismissal < this.state.infoUser.dateEmployment) {
this.setIsInvalid(id)
return false
}
return true
}
setIsInvalid(id) {
document.getElementById(id).classList.add('is-invalid')
}
// Обновление state
updateData = (name, value) => {
this.setState(prevState => ({
infoUser: {
...prevState.infoUser,
[name]: value
}
}))
}
// Генерация уникального ID для пользователя
setInfoUserId() {
this.setState(prevState => ({
infoUser: {
...prevState.infoUser,
id: this.createNewId(allUser.users)
}
}))
}
componentDidMount() {
this.setInfoUserId()
}
render() {
const colleagues = allUser.getUserAsKeyLabel()
return (
<div className="container mt-2">
<div className="h3 mb-3 text-center">Добавление нового пользователя</div>
<TextInput id="name" nameField="Имя*" value={this.state.infoUser.name} updateData={this.updateData} invalid="Введите имя" />
<TextInput id="surname" nameField="Фамилия*" value={this.state.infoUser.surname} updateData={this.updateData} invalid="Введите фимилию" />
<TextInput id="patronymic" nameField="Отчество" value={this.state.infoUser.patronymic} updateData={this.updateData} />
<SelectList id="position" nameField="Должность*" positions={positions} value={this.state.infoUser.position} updateData={this.updateData} invalid="Выберите должность" />
<DateInput id="dateOfBirth" nameField="Дата рождения*" value={this.state.infoUser.dateOfBirth} updateData={this.updateData} invalid="Укажите дату рождения" />
<RadioInput id="gender" nameField="Пол *" gender={gender} value={this.state.infoUser.gender} defaultValue={this.state.infoUser.gender} updateData={this.updateData} invalid="Укажите пол" />
<DateInput id="dateEmployment" nameField="Дата приема на работу*" value={this.state.infoUser.dateEmployment} updateData={this.updateData} invalid="Укажите дату приема на работу" />
<DateInput id="dateOfDismissal" nameField="Дата увольнения" value={this.state.infoUser.dateOfDismissal} updateData={this.updateData} invalid="Дата увольнения не может быть меньше даты приема на работу" />
<CheckInput id="drivingLicence" nameField="Наличие водительских прав" value={this.state.infoUser.drivingLicence} defaultValue={this.state.infoUser.drivingLicence} updateData={this.updateData} />
<MultiSelectCheckbox id="colleagues" nameField="Коллеги" options={colleagues} placeholder="Нет коллег" selectDeselectLabel="Выбрать/убрать всех сотрудников" selected={[]} name="сolleagues" updateData={this.updateData} />
<button type="button" className="btn btn-success" onClick={this.insertUser}>Добавить</button>
<button type="button" className="btn btn-secondary" onClick={() => this.props.history.push("/")}>Назад</button>
</div>
)
}
}
export default AddUser
|
describe('test on demo.test.js', () => {
test('should be equals string', () => {
const message = 'Hola mundo';
const message2 = `Hola mundo`;
expect(message).toBe(message2);
})
})
|
import React, { Component } from 'react';
import { Text, TouchableOpacity, SafeAreaView, View } from 'react-native';
import { connect } from 'react-redux';
import Icon from 'react-native-vector-icons/FontAwesome';
class MovieDetail extends Component {
state = {
fanhao:''
}
render() {
const { fanhao } = this.props
return (
<SafeAreaView style={ {flex: 1} }>
<Text>{'fanhao:'}{fanhao}</Text>
<Icon name ='home' size= {30}/>
<TouchableOpacity onPress={ ()=>this.props.navigation.goBack() }>
<Text>Go Back2</Text>
</TouchableOpacity>
<TouchableOpacity onPress={ ()=>this.props.navigation.goBack('Tab') }>
<Text>Go Tab</Text>
</TouchableOpacity>
</SafeAreaView>
);
}
};
const mapStateToProps = state => ({
fanhao:state.movie.movieId,
count:state.movie.count
});
const mapDispatchToProps = {
};
export default connect(mapStateToProps, mapDispatchToProps)(MovieDetail); |
import React, {Component} from 'react';
import Typography from 'material-ui/Typography';
import Grid from 'material-ui/Grid';
import MenuItems from "../header/menu-items";
class Footer extends Component {
render() {
const footerMobile = (
<div className="footer">
<div className="container padding">
<Grid gutter={0} container align="flex-start" justify="center">
<Grid item xs={8}>
<Typography type="body1">
<a href="mailto:contato@vivala.com.br">contato@vivala.com.br</a>
</Typography>
<Typography type="body1">
Segunda à Sexta <br />9h às 18h
</Typography>
</Grid>
<Grid item xs={4}>
<Typography type="subheading" color="inherit" style={{ textAlign: 'right', fontWeight: 'bold' }}>Vivala <br />© 2020</Typography>
</Grid>
</Grid>
</div>
</div>
);
const footerDesktop = (
<Grid gutter={0} container className="footer">
<div className="container padding-2x">
<MenuItems direction={"row"} showContact={true} />
<Grid container align="center" justify="center" style={{ marginTop: 40 }}>
<Typography type="subheading" color="inherit"><strong>© 2020 Vivalá</strong></Typography>
</Grid>
</div>
</Grid>
);
return window.screen.width < 900 ? footerMobile : footerDesktop;
}
}
export default Footer;
|
function Triangle() {}
Triangle.prototype = {
setElements: function(p0, p1, p2) {
this.p0 = p0;
this.p1 = p1;
this.p2 = p2;
var W = p1.subtract(p0);
var U = p2.subtract(p0);
this.normal = W.cross(U);
//this.normal.toUnitVectorN();
this.p0Norm = this.normal.toUnitVector();
this.p1Norm = this.normal.toUnitVector();
this.p2Norm = this.normal.toUnitVector();
return this;
},
e: function(idx) {
if(idx == 0) return this.p0;
if(idx == 1) return this.p1;
if(idx == 2) return this.p2;
},
// Returns a copy of the triangle
dup: function() {
return Triangle.create(this.p0,this.p1,this.p2);
},
setNormal: function(vecNormal) {
this.normal = vecNormal;
return this;
},
setNormalP0: function(normal){
this.p0Norm = normal;
return this;
},
setNormalP1: function(normal){
this.p1Norm = normal;
return this;
},
setNormalP2: function(normal){
this.p2Norm = normal;
return this;
},
getNormal: function() {
return this.normal;
},
getNormalSmooth: function(u, v) {
var fst = this.p1Norm.multiply(u);
var scd = this.p0Norm.multiply(1.0 - (u + v));
var trd = this.p2Norm.multiply(v);
var res = fst.add(scd.add(trd));
return res;
},
// Moller Trumbore's method
intersect: function(ray){
var eps = 0.000001;
var fFacing = true;
var intersect = false;
// get the two edges
var e1 = this.p1.subtract(this.p0);
var e2 = this.p2.subtract(this.p0);
//Begin calculating determinant
var P = ray.getDirection().cross(e2);
// translated ray origin
//var s = ray.getOrigin().subtract(this.p1)
var det = e1.dot(P);
if(det > - eps && det < eps) {
return [0, 0, 0, intersect, fFacing];
}
var inv_det = 1.0 / det;
//calculate distance from p0 to ray origin
var T = ray.getOrigin().subtract(this.p0);
//Calculate u parameter and test bound
u = T.dot(P) * inv_det;
//The intersection lies outside of the triangle
if(u < 0.0 || u > 1.0){
return [0, 0, 0, intersect, fFacing];
}
//Prepare to test v parameter
var Q = T.cross(e1);
//Calculate V parameter and test bound
var v = ray.getDirection().dot(Q) * inv_det;
//The intersection lies outside of the triangle
if(v < 0.0 || v > 1.0 || (u + v) > 1.0) {
return [0, 0, 0, intersect, fFacing];
}
t = e2.dot(Q) * inv_det;
intersect = true;
return [u, v, t, intersect, fFacing];
},
setDiffuseMaterialColors: function(colorVec) {
this.DiffMatColor = colorVec;
return this;
},
setAmbientMaterialColors: function(colorVec) {
this.AmbientMatColor = colorVec;
return this;
},
setSpecularMaterialColors: function(colorVec) {
this.SpecularMatColor = colorVec;
return this;
},
setSpecularExponent: function(exp) {
this.SpecularExponent = exp;
return this;
},
setRefractionIndex: function(index) {
this.RefractionIndex = index;
return this;
},
getRefractionIndex: function() {
return this.RefractionIndex;
},
getSpecularMaterialColors: function() {
return this.SpecularMatColor;
},
getSpecularExponent: function() {
return this.SpecularExponent;
},
getAmbientMaterialColors: function() {
return this.AmbientMatColor;
},
getDiffuseMaterialColors: function() {
return this.DiffMatColor;
},
};
// Constructor function
Triangle.create = function(p0,p1,p2) {
var T = new Triangle();
return T.setElements(p0, p1, p2);
};
// Utility functions
var $T = Triangle.create;
|
angular.module('angular_post_demo',[]);
app.controller('postfile', function ($scope, $http) {
/*
* This method will be called on click event of button.
* Here we will read the email and password value and call our PHP file.
*/
$scope.sendfile = function () {
document.getElementById("message").textContent = "";
var request = $http({
method: "post",
url: window.location.href + "upload.php",
data: {
file: $scope.fileToUpload
},
headers: { 'Content-Type': 'multipart/form-data' }
});
/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
document.getElementById("message").textContent = "You have login successfully with email";
});
}
});
|
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
function check_img0() {
$("#Img_0").change(function(){
var objUrl = getObjectURL(this.files[0]) ;
if (objUrl) {
$("#proImg_0").attr("src", objUrl).css("display",'inline');
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var formData = new FormData();
formData.append('file', $('#Img_0')[0].files[0]);
$.ajax({
url: '/upload/picture',
type: 'post',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
console.info(res);
$('#proPicture_0').val(res.file);
}).fail(function(res) {});
})
}
function check_img1() {
$("#Img_1").change(function(){
var objUrl = getObjectURL(this.files[0]) ;
if (objUrl) {
$("#proImg_1").attr("src", objUrl).css("display",'inline');
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var formData = new FormData();
formData.append('file', $('#Img_1')[0].files[0]);
$.ajax({
url: '/upload/picture',
type: 'post',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
console.info(res)
$('#proPicture_1').val(res.file);
}).fail(function(res) {});
})
}
function check_img2() {
$("#Img_2").change(function(){
var objUrl = getObjectURL(this.files[0]) ;
if (objUrl) {
$("#proImg_2").attr("src", objUrl).css("display",'inline');
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var formData = new FormData();
formData.append('file', $('#Img_2')[0].files[0]);
$.ajax({
url: '/upload/picture',
type: 'post',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
console.info(res)
$('#proPicture_2').val(res.file);
}).fail(function(res) {});
})
}
$(function () {
var a=1;
$("#addMember").click(function () {
if(a<3) {
$("#productForm0").append(
'<div id="productDiv'+a+'"> <div class="formWrapper"> <h3>产品海报</h3> <br> ' +
'<input type="file" id="Img_'+a+'" name="Img_'+a+'" accept="image/png,image/jpg,image/jpeg,image/gif" onclick="check_img'+a+'()"> <br><br> ' +
'<img src="" id="proImg_'+a+'" width="240" height="120" style="display: none">' +
' <input type="hidden" value="" name="image_'+a+'" id="proPicture_'+a+'"> <h3>产品名称</h3>' +
' <input type="text" placeholder="请输入产品名称" name="proName_'+a+'" id="proName'+a+'"> <h3>产品地址</h3>' +
' <input type="text" placeholder="请输入产品主页URL或产品下载地址" name="link_'+a+'" id="proAddress'+a+'"> ' + '<h3>产品简介</h3> ' +
'<textarea placeholder="请简短描述该产品定位、产品特色、用户群体等" maxlength="1000" name="desc_'+a+'" id="proProfile_'+a+'"></textarea> ' +
'</div> </div> <div class="clear" style="width: 100%;margin-top:30px;border-bottom: 1px solid silver"></div>');
a++;
if(a>2){
$("#addMember").hide();
}
}
});
$("#step4Submit").click(function (){
$("#productForm0").submit();
})
}); |
import { removeToken, getToken } from '../boot/auth'
export default {
state: {
isLogIn: !!getToken()
},
getters: {
getIsLogIn(state) {
return state.isLogIn
}
},
mutations: {
signIn(state) {
state.isLogIn = true
},
signOut(state) {
removeToken()
state.isLogIn = false
}
}
}
|
/**
* Created by py on 01/09/2018.
*/
const Block = require('../model/Block');
const StatusCodes = require('./StatusCodes.js');
module.exports = class BlockController {
constructor(blockchainService){
this.blockchainService = blockchainService;
}
getBlockByHeight(request, response) {
let height = request.params.blockHeight;
let blockPromise = this.blockchainService.getBlock(height);
blockPromise.then(block => {
response.send(block);
}).catch(err => {
response.status(StatusCodes.BAD_REQUEST).json({error: err.message});
});
};
postBlock(request, response) {
let data = request.body.body;
let block = new Block(data);
if(data === undefined) {
let error = new Error(`missing 'body' key in request body.`);
response.status(StatusCodes.BAD_REQUEST).json({error: error.message});
} else {
let newBlockPromise = this.blockchainService.addBlock(block);
newBlockPromise.then(block => {
response.json(block);
}).catch(err => {
response.status(StatusCodes.BAD_REQUEST).json({error: err.message});
});
}
}
}; |
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const User = require('../models/user');
const Plant = require('../models/plant');
const commentSchema = new Schema({
creator: {type: Schema.Types.ObjectId, ref: 'User'},
content: String},
{timestamps: true}
);
const Comment = mongoose.model("Comment", commentSchema);
module.exports = Comment; |
import Home from "./home.vue";
import Login from "./pages/login.vue";
import Vue from "vue";
import VueRouter from "vue-router";
//为了使用router-view 和 router-link
Vue.use(VueRouter);
// 创建路由配置
var routes = [
{
path: "/login",
component: Login
}
];
// 创建路由实例
var router = new VueRouter({
routes
});
new Vue({
el: "#app",
router,
// 指定一个组件渲染根实例,这个组件可以成为最底层的组件
render(creatElement) {
// render函数使用固定的写法,只有App是可变;
return creatElement(Home);
}
});
|
const express = require('express'),
router = express.Router(),
schema = require('../models/book'),
Picture = schema.models.Picture,
cloudinary = require('cloudinary').v2,
fs = require('fs'),
multipart = require('connect-multiparty'),
multipartMiddleware = multipart();
module.exports = function(app) {
app.use('/', router);
};
router.get('/books', (req, res, next) => {
Picture.all().then((photos) => {
console.log(photos);
res.render('book/books', {
title: 'PhotoBook',
photos: photos,
cloudinary: cloudinary
});
});
});
router.get('/books/add', (req, res, next) => {
res.render('book/add-photo', {
title: 'Upload Picture'
});
});
router.post('/books/add', multipartMiddleware, (req, res, next) => {
console.log(req.files);
let photo = new Picture(req.body);
const imageFile = req.files.image.path;
cloudinary.uploader.upload(imageFile, {
tags: 'photobook',
folder: req.body.category + '/',
public_id: req.files.image.originalFilename
}).then((image) => {
console.log('Picture uploaded to Cloudinary');
console.log(image);
photo.image = image;
return photo.save();
}).then((photo) => {
console.log('Successfully saved');
const filePath = req.files.image.path;
fs.unlinkSync(filePath);
}).finally(() => {
res.render('book/posted-photo', {
title: 'Upload with Success',
photo: photo,
upload: photo.image
});
});
}); |
if (typeof module === 'object' && typeof define !== 'function') {
var define = function (factory) {
module.exports = factory(require, exports, module);
};
}
define(function (require, exports, module) {
var isArray = Array.isArray || function (a) { return a instanceof Array; };
var makeIndexer = function (key) {
return function (val) {
return val[key];
};
};
var extend = function (obj1, obj2) {
var key;
for (key in obj2) {
if (!obj2.hasOwnProperty(key)) {
continue;
}
obj1[key] = obj2[key];
}
return obj1;
};
var notInt = /[^\d]/;
var stringify = function (x) {
return x !== null && x !== void 0 ? String(x) : x;
}
var IndexedArray = function (array, indexer) {
// enforce no `new` so that we always return an actual
// array to pass `instanceof Array`
if (this instanceof IndexedArray) {
return IndexedArray(array, indexer);
}
var arr = [];
arr._indexer = typeof indexer === 'function' ? indexer :
makeIndexer(indexer || '_id');
arr._i = {};
arr._index = function (val) {
var i = stringify(arr._indexer(val));
// only allow large numbers
if (i && (notInt.test(i) || i.length > 10)) {
arr._i[i] = arr[i] = val;
}
};
for (var method in IndexedArray.prototype) {
arr[method] = IndexedArray.prototype[method];
}
if (isArray(array)) {
array.forEach(function (ele) {
arr.push(ele);
});
}
return arr;
};
IndexedArray.fromObject = function (obj, indexKey) {
indexKey = indexKey || '_id';
var key, arr = [];
for(key in obj) {
if(!obj.hasOwnProperty(key)) {
continue;
}
var o = {};
o[indexKey] = key;
extend(o, obj[key]);
arr.push(o);
}
return IndexedArray(arr, indexKey);
};
var Ap = Array.prototype;
IndexedArray.prototype = {
push: function (val) {
this._index(val);
return Ap.push.call(this, val);
},
pop: function () {
var popped = Ap.pop.call(this);
var i = this._indexer(popped);
delete this._i[i];
delete this[i];
return popped;
},
shift: function () {
var shifted = Ap.shift.call(this);
var i = this._indexer(shifted);
delete this._i[i];
delete this[i];
return shifted;
},
unshift: function (val) {
this._index(val);
return Ap.unshift.call(this, val);
},
splice: function (from, take) {
var arr = this;
var vals = Ap.slice.call(arguments).splice(2);
vals.forEach(arr._index);
return Ap.splice.apply(this, arguments);
},
toObject: function () {
return this._i;
},
toJSON: function () {
return this._i;
},
concat: function (arr) {
return IndexedArray(Ap.concat.call(this, arr), this._indexer);
},
slice: function (begin, end) {
return IndexedArray(Ap.slice.call(this, begin, end), this._indexer);
},
keys: function () {
var key, k = [];
for(key in this._i) {
k.push(key);
}
return k;
}
};
return IndexedArray;
}); |
import {
GET_CONFIRMED_DATA,
GET_DEATH_DATA,
GET_RECOVERED_DATA
} from '../actions/types';
const initialState = {
loading: true,
confirmedData: [],
deathData: [],
recoveredData: []
};
export default (state = initialState, action) => {
const { type, payload } = action;
switch (type) {
case GET_CONFIRMED_DATA:
return {
...state,
loading: false,
confirmedData: [...payload]
};
case GET_DEATH_DATA:
return {
...state,
loading: false,
deathData: [...payload]
};
case GET_RECOVERED_DATA:
return {
...state,
loading: false,
recoveredData: [...payload]
};
default:
return state;
}
};
|
import likeButton, { initialState } from '../like';
import { LIKE_SUCCESS, DISLIKE_SUCCESS, GET_LIKES } from '../../../constants';
describe('Like reducers', () => {
it('should provide initial state', () => {
expect(likeButton(undefined, {})).toEqual(initialState);
});
it('should set liked state', () => {
expect(
likeButton(initialState, { type: LIKE_SUCCESS, }).liked
).toEqual(true);
});
it('should set disliked state', () => {
expect(
likeButton(initialState, { type: DISLIKE_SUCCESS, }).disliked
).toEqual(true);
});
it('should set get likes state', () => {
expect(
likeButton(initialState, { type: GET_LIKES, payload: {} }).likeCount
).toEqual(undefined);
});
});
|
import React from "react"
import styled from "styled-components"
const Svg = styled.svg`
width: 30%;
margin: 2rem auto;
fill: #0074b8;
`
const Devices = () => (
<Svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path d="M17 6V5h-2V2H3v14h5v4h3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6zm-5.75 14H3a2 2 0 0 1-2-2V2c0-1.1.9-2 2-2h12a2 2 0 0 1 2 2v4a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-5.75zM11 8v8h6V8h-6zm3 11a1 1 0 0 0 0-2 1 1 0 0 0 0 2z" />
</Svg>
)
export default Devices
|
"use strict";
module.exports = function bootStrapSwagger(server) {
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('hapi-swagger');
const Pack = require('./../../package');
const options = {
info: {
'title': Pack.name + ' Documentation',
'version': Pack.version,
}
};
server.register([
Inert,
Vision,
{
'register': HapiSwagger,
'options': options
}], (err) => {
server.start( (err) => {
if (err) {
console.log(err);
} else {
console.log('Server running at:', server.info.uri);
}
});
});
} |
var request = require('request');
var Promise = require('promise');
function WorkItems(repo, username, password) {
this.req = request.defaults({
jar: request.jar(),
followAllRedirects: true,
rejectUnauthorized: false
});
this.repo = repo;
this.username = username;
this.password = password;
}
WorkItems.prototype.fetchOSLC = function(workitemNumber, avoidLogin) {
var self = this;
return new Promise(function(resolve, reject) {
self.req.get(self.repo + "/oslc/workitems/" + workitemNumber + ".json",
function (err, resp, body) {
console.log(err);
if (err) {
reject(err);
return;
}
if (resp.statusCode == 401) {
// login and retry
if (avoidLogin) {
reject("Log in failure when fetching work item.");
return;
}
return self.login().then(function() {
console.log("after login");
self.fetchOSLC(workitemNumber, true).then(resolve, reject);
}, reject);
}
if (resp.statusCode == 200) {
resolve(JSON.parse(body));
}
else {
reject("Couldn't fetch work item. Got a " + resp.statusCode + " during request.");
}
}
);
});
};
WorkItems.prototype.login = function() {
var self = this;
return new Promise(function(resolve, reject) {
self.req.get(self.repo + "/authenticated/identity", function(err, resp, body) {
if (err) {
return reject(err);
}
if (resp.statusCode != 401) {
console.log("/auth/id");
return reject("Error during login. Unexpected status code " + resp.statusCode + ".");
}
self.req.post(self.repo + "/authenticated/j_security_check", {
form: {
j_username: self.username,
j_password: self.password
}
}, function(err, resp, body) {
if (resp.statusCode != 404 && resp.statusCode != 500) {
console.log("/auth/j_sec");
return reject("Unexpected status code after login " + resp.statusCode + ".");
}
resolve(self);
});
});
});
};
WorkItems.prototype.queryForCategories = function(paId, perCategoryCallback) {
var self = this;
return new Promise(function(resolve, reject) {
var uri = self.repo + "/oslc/categories?oslc_cm.query=";
uri += encodeURIComponent("rtc_cm:projectArea=\"" + paId + "\"");
console.log(uri);
var catsHandled = 0;
var resultGatherer;
resultGatherer = function(err, resp, body) {
if (err) {
return reject(err);
}
if (resp.statusCode != 200) {
console.log("status code " + resp.statusCode);
return reject("Error during login. Unexpected status code " + resp.statusCode + ".");
}
var answer = JSON.parse(body);
answer["oslc_cm:results"].forEach(perCategoryCallback);
catsHandled += answer["oslc_cm:results"].length;
console.log("Handled " + catsHandled + " of " + answer["oslc_cm:totalCount"]);
if (answer["oslc_cm:next"]) {
self.req.get(answer["oslc_cm:next"], {headers: {
'accept': 'application/json'
}}, resultGatherer);
}
else {
resolve();
}
};
self.req.get(uri, {headers: {
'accept': 'application/json'
}}, resultGatherer);
});
}
/**
* Fire the callback once for each workitem. Returns a promise that is resolved
* when all of the work items have been queried
*/
WorkItems.prototype.queryForWorkItems = function(paId, queryString, perWorkitemCallback, properties) {
var self = this;
return new Promise(function(resolve, reject) {
var uri = self.repo + "/oslc/contexts/" + paId + "/workitems?oslc_cm.query=";
uri += encodeURIComponent(queryString);
if (properties) {
uri += "&oslc_cm.properties=" + encodeURIComponent(properties.join());
}
var wisHandled = 0;
var resultGatherer;
resultGatherer = function(err, resp, body) {
if (err) {
return reject(err);
}
if (resp.statusCode != 200) {
console.log("status code " + resp.statusCode);
return reject("Error during login. Unexpected status code " + resp.statusCode + ".");
}
var answer = JSON.parse(body);
answer["oslc_cm:results"].forEach(perWorkitemCallback);
wisHandled += answer["oslc_cm:results"].length;
console.log("Handled " + wisHandled + " of " + answer["oslc_cm:totalCount"]);
if (answer["oslc_cm:next"]) {
self.req.get(answer["oslc_cm:next"], {headers: {
'accept': 'application/json'
}}, resultGatherer);
}
else {
resolve();
}
};
self.req.get(uri, {headers: {
'accept': 'application/json'
}}, resultGatherer);
});
}
module.exports = WorkItems;
|
import expensesReducer from "../../reducers/expenses";
import { expenses } from "../fixtures/expenses";
test("Should set default state", () => {
const state = expensesReducer(undefined, { type: "@@INIT" });
expect(state).toEqual([]);
});
test("Should add expense to the state", () => {
const expense = {
description: "Rent",
amount: 1200,
id: "4"
};
const state = expensesReducer(expenses, { type: "ADD_EXPENSE", expense });
expect(state).toEqual([...expenses, expense]);
});
test("Should remove expense by id", () => {
const state = expensesReducer(expenses, {
type: "REMOVE_EXPENSE",
id: "1"
});
expect(state).toEqual([expenses[0], expenses[2]]);
});
test("Should not remove expenses if id not found", () => {
const state = expensesReducer(expenses, {
type: "REMOVE_EXPENSE",
id: "-1"
});
expect(state).toEqual(expenses);
});
test("Should edit expense specific expense", () => {
const state = expensesReducer(expenses, {
type: "EDIT_EXPENSE",
id: "1",
update: {
amount: 2200
}
});
expect(state).toEqual([
expenses[0],
{ ...expenses[1], amount: 2200 },
expenses[2]
]);
});
test("Should not edit expense if expense not found", () => {
const state = expensesReducer(expenses, {
type: "EDIT_EXPENSE",
id: "-1",
update: {
amount: 2200
}
});
expect(state).toEqual([...expenses]);
});
test("Should set expenses", () => {
const expense = {
description: "Rent",
amount: 1200,
id: "4"
};
const state = expensesReducer(expenses, {
type: "SET_EXPENSES",
expenses: [expense]
});
expect(state).toEqual([expense]);
});
|
../../../../../shared/src/App/assets/fixtures.js |
// MW de autorización
exports.loginRequired = function(req, res, next) {
if (req.session.user) {
next();
} else {
res.redirect('/login');
}
};
// GET /login
exports.new = function(req, res) {
res.render('sessions/new');
};
// POST /login
exports.create = function(req, res) {
var userController = require('./user_controller');
userController.autenticar(req.body.login, req.body.password, function(err, user) {
if (!err) {
// Creamos req.session.user y guardamos id+username
req.session.user = { id: user.id, username: user.username };
req.session.lasttime = Date.now();
if (req.session.redir) {
res.redirect(req.session.redir);
} else {
res.redirect('/');
}
} else {
res.render('sessions/new', { errors: [ err ] });
}
});
};
// DELETE /logout
exports.destroy = function(req, res) {
// Destruimos req.session.user
delete req.session.user;
delete req.session.lasttime;
res.redirect(req.session.redir);
};
|
var enableEXA = true,
dev = Device,
client = Flow.client,
clientIP = client.ipaddr,
clientIPString = clientIP.toString(),
server = Flow.server,
serverIP = server.ipaddr,
serverIPString = serverIP.toString(),
dscpBytes = {1:Flow.dscpBytes1, 2:Flow.dscpBytes2},
l7proto = Flow.l7proto,
ip = (client.device.hasTrigger ? serverIP : clientIP),
ipString = ip.toString(),
dscpCatalog = {},
dscpIndex = {
0:'Best Effort',
8:'CS1',
10:'AF11',
12:'AF12',
14:'AF13',
16:'CS2',
18:'AF21',
20:'AF22',
22:'AF23',
24:'CS3',
26:'AF31',
28:'AF32',
30:'AF33',
32:'CS4',
34:'AF41',
36:'AF42',
38:'AF43',
40:'CS5',
46:'EF',
48:'CS6',
56:'CS7'
};
// Analyze [dscpBytes1] and [dscpBytes2]
for (_which in dscpBytes)
{
// Loop through the [index] looking for any occurrences in this [dscpArray]
for (_i in dscpIndex)
{
// Is this [dscpIndex] value (_i) present in this [dscpArray] ??
if (typeof dscpBytes[_which][_i] !== 'number') {continue}
// MATCH: add it to the [dscpCatalog]
if (dscpIndex[_i] in dscpCatalog) {dscpCatalog[dscpIndex[_i]] += dscpBytes[_which][_i]}
else {dscpCatalog[dscpIndex[_i]] = dscpBytes[_which][_i]}
}
}
// Commit the metrics from [catalog]
for (_code in dscpCatalog)
{
// Save a local copy for readbility
var _bytes = dscpCatalog[_code],
_prefix = 'dscp_bytes_' + _code;
// Safety Net to prevent empty commits
if (! _bytes) {continue}
// Safe to commit the DEVICE metrics
dev.metricAddCount('dscp_bytes', _bytes);
dev.metricAddDetailCount('dscp_bytes_code', _code, _bytes);
dev.metricAddDetailCount('dscp_bytes_l7proto', l7proto, _bytes);
// The following metrics are for THIS [code] only
dev.metricAddCount(_prefix, _bytes);
dev.metricAddDetailCount(_prefix + '_l7proto', l7proto, _bytes);
dev.metricAddDetailCount(_prefix + '_ip', ip, _bytes);
dev.metricAddDetailCount(_prefix + '_ip-l7proto', ipString + ':' + l7proto, _bytes);
// Safe to commit the NETWORK metrics
Network.metricAddCount('dscp_bytes', _bytes);
Network.metricAddDetailCount('dscp_bytes_code', _code, _bytes);
Network.metricAddDetailCount('dscp_bytes_l7proto', l7proto, _bytes);
// The following metrics are for THIS [code] only
Network.metricAddCount(_prefix, _bytes);
Network.metricAddDetailCount(_prefix + '_l7proto', l7proto, _bytes);
Network.metricAddDetailCount(_prefix + '_clientIP', clientIP, _bytes);
Network.metricAddDetailCount(_prefix + '_serverIP', serverIP, _bytes);
Network.metricAddDetailCount(_prefix + '_clientIP-l7proto', clientIPString + ':' + l7proto, _bytes);
Network.metricAddDetailCount(_prefix + '_serverIP-l7proto', serverIPString + ':' + l7proto, _bytes);
// Send [record] to EXA?
if (enableEXA !== false)
{
commitRecord('dscp', {
code: _code,
l2bytes: _bytes,
l7proto: l7proto,
clientIP: clientIP,
serverIP: serverIP
});
}
}
|
var express = require('express');
var router = express.Router();
const { Op } = require("sequelize");
const models = require("../../../../models");
const errors = require("../../../errors");
const ResponseTemplate = require("../../../ResponseTemplate");
const SequelizeUtil = require("../../../../util/SequelizeUtil");
const meRouter = require('./me');
const patientRouter = require('./patient/patient');
const appointmentRouter = require('./appointment/appointment');
const messageRouter = require('./message/message');
const drugsRouter = require('./drugs');
router.use(doctorAuthorizationFilter);
router.use('/me', meRouter);
router.use('/patient', patientRouter);
router.use('/appointment', appointmentRouter);
router.use('/message', messageRouter);
router.use('/drugs', drugsRouter);
function doctorAuthorizationFilter(req, res, next) {
const principal = req.principal;
if (principal.role !== models.UserRoles.physician.id) {
throw new errors.AccessForbidden();
}
next();
}
module.exports = router;
|
const carrinho = [{
nome: 'Carrinho C1',
itens: [{
nome: 'Borracha',
preco: 3.45,
fragil: true
}, {
nome: 'Caderno',
preco: 13.90,
fragil: false
}]
}, {
nome: 'Carrinho C2',
itens: [{
nome: 'Kit de lapis',
presco: 41.22,
fragil: true
}, {
nome: 'Caneta',
preco: 7.50,
fragil: false
}]
}]
const getPrecoItem = item => item.preco
const getPrecoCarrinho = carrinho => carrinho.itens.map(getPrecoItem)
const precos = carrinho.map(soPreco)
console.log(precos)
|
/// <reference types="cypress" />
///<reference types="cypress-iframe" />
import { createCart } from "../../support/page_objects/umbraco/createCart"
// import { shoppingCartReviewPage } from "../../support/page_objects/umbraco/checkout"
import { umbracoShoppingCart } from "../../support/page_objects/umbraco/umbracoShoppingCart"
// import { PartialRefundPage, VerifyPartialRefundItems } from "../../support/page_objects/admin/partialRefund"
// import { VerifyPartialRefund } from "../../support/page_objects/admin/partialRefund"
// import { admin } from "../../support/page_objects/admin/adminFunctions"
describe('Create a cart using a Post statement', () => {
const buyerCookieName = "BuyerEmail6"
var buyerData = require('../../fixtures/buyer/umbraco/buyer')
var passwordData = require('../../fixtures/password/standardPassword')
it('test if ', () => {
//cy.visit('https://store.tcgplayer-qa.com/login/revalidate?returnUrl=/shoppingcart/review?sf=6d9fccfa')
//createCart.createCartVistShoppingCartPage(buyerData.buyerEmail6)
cy.setCookie(Cypress.env("oauthCookieName"), Cypress.env("oauthCookieValueBuyerEmail6"), { httpOnly: true })
cy.visit('https://cart.tcgplayer-stg.com/shoppingcart?sf=F417072D&ck=751c41ddcbff4672b045b542f9fa7569')
//cy.setCookie('BuyerRevalidationKey', '', { httpOnly: true }) //set a blank cookie that expires 20 years into the future. Needs to be at the end of the cart test prior to going to review page
cy.get('#btnCheckout1').click()
cy.wait(20000)//Need this wait because takes awhile for the page to load
//If we get logon page
cy.get('body').then((body) => {
//console.log(body.find('ul:contains(Email)'))
console.log(body.find('h2:contains(Confirm your account)'))
// if (body.find('form').length > 0) {
// cy.get('#Email').type(buyerData.buyerEmail6)
// cy.get('#Password').type(passwordData.password)
// cy.get('.GreenButtonNoArrow').click()
// }
})
})
})
|
import ThemeProvider from '../ThemeProvider'
/**
* @description Provides Kiwi theme to component
* @param {Function} h Vue render function
* @param {Vue.Component} Component - Vue component
*/
export const provideTheme = (h, Component) => {
return h(ThemeProvider, {}, [h(Component)])
}
|
export { default as account } from './account';
export { default as token } from './token';
export * from './account';
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsApiAlt = {
name: 'api_alt',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M14 12l-2 2-2-2 2-2 2 2zm-2-6l2.12 2.12 2.5-2.5L12 1 7.38 5.62l2.5 2.5L12 6zm-6 6l2.12-2.12-2.5-2.5L1 12l4.62 4.62 2.5-2.5L6 12zm12 0l-2.12 2.12 2.5 2.5L23 12l-4.62-4.62-2.5 2.5L18 12zm-6 6l-2.12-2.12-2.5 2.5L12 23l4.62-4.62-2.5-2.5L12 18z"/></svg>`
};
|
import React, { Component } from 'react';
import { Image, View, Text, TouchableOpacity, CameraRoll, ToastAndroid } from 'react-native';
import PhotoView from 'react-native-photo-view';
import { captureRef, ViewShot } from 'react-native-view-shot';
const Platform = require('react-native').Platform;
const ImagePicker = require('react-native-image-picker');
class ControlCenter extends Component {
static navigationOptions = {
headerTitleStyle: { alignSelf: 'center', color: '#FFFFFF' },
title: 'Frapho',
headerStyle: { backgroundColor: '#0B4239' },
};
constructor(props) {
super(props);
this.state = { image_frame: props.navigation.state.params.image, name: props.navigation.state.params.name_image, image: null, isSave: false, link_uri: null };
(console.log(props.navigation.state.params.name_image));
this.chooseImage = this.chooseImage.bind(this);
this.snapshot = this.snapshot.bind(this);
}
componentDidMount() {
const input = this.refs.viewShot;
console.log(input);
}
snapshot(refname) {
console.log(this.refs[refname]);
captureRef(this.refs[refname], { format: 'jpg', quality: 1.0 })
.then(
//uri => console.log('Image saved to', uri),
uri => CameraRoll.saveToCameraRoll(uri, 'photo'),
//uri => this.setState({ link_uri: uri }),
//console.log(this.state.link_uri),
error => console.error('Oops, snapshot failed', error)
);
ToastAndroid.show('Save Image successfully !', ToastAndroid.SHORT);
}
chooseImage() {
ImagePicker.showImagePicker({ noData: true }, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
//If it is iOS, remove 'file://' prefix
let source = { uri: response.uri.replace('file://', ''), isStatic: true };
//If android, don't need to remove the 'file://'' prefix
if (Platform.OS === 'android') {
source = { uri: response.uri, isStatic: true };
}
this.setState({ image: source.uri, isSave: true });
console.log(this.state.image);
}
});
}
renderIf(condition, content) {
if (condition === true)
return content;
else
return null;
}
render() {
return (
<View style={{ backgroundColor: '#e9ebee', height: '100%' }}>
<Text style={styles.TitleStyle}>{this.state.name}</Text>
<View style={styles.imageStyleContainer}>
<View ref='viewShot' collapsable={false}>
{
this.state.image_frame.map((item) => {
const frame_url_compare = item.substring(0, 14);
console.log(frame_url_compare);
if ( frame_url_compare !== 'https://vgy.me')
{
item = 'https://frapho.com/img/frame/' + item;
}
else item = item;
console.log(item);
return (<Image
style={styles.imageStyle}
source={{ uri: item }}
/>);
})
}
<PhotoView minimumZoomScale={0.5} maximumZoomScale={3} androidScaleType="center" style={styles.imageEditableStyle} source={{ uri: this.state.image }} />
</View>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={this.chooseImage}>
<Text style={styles.buttonText}>Choose...</Text>
</TouchableOpacity>
{this.renderIf(this.state.isSave,
<TouchableOpacity
style={styles.button}
onPress={() => this.snapshot('viewShot')}
>
<Text style={styles.buttonText}>Save</Text>
</TouchableOpacity>
)}
</View>
</View>
);
}
}
const styles = {
imageStyleContainer: {
justifyContent: 'center',
alignItems: 'center',
marginLeft: 10,
marginRight: 10,
marginTop: 10,
},
imageStyle: {
// marginBottom: 15,
// marginTop: 10,
height: 300,
width: 300,
},
TitleStyle: {
fontSize: 15,
fontWeight: 'bold',
fontFamily: 'Cochin',
textAlign: 'center',
color: '#333',
paddingTop: 10
},
button: {
backgroundColor: '#E34517',
width: 140,
height: 40,
borderRadius: 10,
alignItems: 'center',
justifyContent: 'center',
margin: 10
},
buttonText: {
color: 'white'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
padding: 10
},
imageEditableStyle: {
height: 300,
width: 300,
position: 'absolute',
top: 10,
//left: 30.7,
zIndex: -1
}
};
export default ControlCenter;
|
import {createStore,combineReducers} from 'redux'
import Employee from '../actions/employee'
import SalaryEmployee from '../actions/salaryemployee'
const store = createStore(
combineReducers(
{
EP:Employee,SL:SalaryEmployee
}
)
)
store.subscribe(()=>{
console.log('update : ',store.getState());
});
export default store
|
const { User, UserData, Photo, Like, Conversation, Message } = require('../models');
const { validationResult } = require('express-validator');
const resize = require('../services/resize');
exports.user = async function(req, res){
if(req.user){
const data = req.user.toJSON();
const user = data["UserDatum"];
const photo = await Photo.getPhoto(user.id);
let json = {
user,
photo
}
res.json( json );
}
else{
res.status(400).send('invalid auth token');
}
}
exports.setUser = async function(req, res){
if(!req.user){
res.status(400).send('invalid auth token');
}
if(!req.body.bio && !req.body.date && !req.body.gender && !req.body.interest && !req.body.name){
res.status(400).send('Missing data');
}
if(req.user){
const json = req.user.toJSON();
let userData = UserData.updateInfo(req.body, json["UserDatumId"]);
res.send(userData);
}
else{
res.status(400).send('Error missing id');
}
}
exports.photo = async function(req, res){
if(!req.user){
res.status(400).send('Invalid token');
}
try{
resize(req.file.path);
const json = req.user.toJSON();
const photo = await Photo.updatePhoto(req.file.path, json["UserDatumId"]);
res.json({"url": (photo.toJSON().url)});
}
catch(err){
res.status(400).send(err);
}
}
exports.getUsers = async function(req, res){
if(!req.user){
res.status(400).send('Invalid token');
}
try{
const json = req.user.toJSON();
console.log(json);
const data = await UserData.findRandom(req.user["UserDatum"].dataValues);
res.send( data );
}
catch(err){
res.status(400).send(err);
}
}
exports.like = async function(req, res){
if(!req.user){
res.status(400).send('Invalid token');
}
try{
const json = req.user.toJSON();
const like = await Like.iLike(json["UserDatumId"], req.body.liked, req.body.like);
res.send(like);
}
catch(err){
console.log(err);
res.status(400).send(err);
}
}
exports.getMessages = async function(req, res){
if(!req.user){
res.status(400).send('Invalid token');
}
if(!req.body.id){
res.status(400).send('Error retrieving message try later');
}
try{
const conversation = await Message.getMessages(req.body.id, req.user["UserDatumId"]);
res.send(conversation);
}
catch(err){
console.log(err);
res.status(400).send(err);
}
}
exports.sendMessage = async function(req, res){
if(!req.user){
res.status(400).send('Invalid token');
}
if(!req.body.id || !req.body.message){
res.status(400).send('Error retrieving message try later');
}
try{
const message = Message.writeMessage(req.body.id, req.user["UserDatumId"], req.body.message);
res.send(message);
}
catch(err){
res.status(400).send(err);
}
} |
import ExpoPixi from 'expo-pixi';
export default async context => {
//http://pixijs.io/examples/#/basics/basic.js
const app = ExpoPixi.application({
context,
});
const bunny = await ExpoPixi.spriteAsync(require('../../assets/pixi/bunny.png'));
bunny.width = bunny.height = 200;
// center the sprite's anchor point
bunny.anchor.set(0.5);
// move the sprite to the center of the screen
bunny.x = app.renderer.width / 2;
bunny.y = app.renderer.height / 2;
app.stage.addChild(bunny);
// Listen for animate update
app.ticker.add(delta => {
// just for fun, let's rotate mr rabbit a little
// delta is 1 if running at 100% performance
// creates frame-independent tranformation
bunny.rotation += 0.1 * delta;
});
};
|
import styled from 'styled-components';
export const HomeWrapper =styled.div`
width:960px;
overflow:hidden;
margin:0 auto;
`;
export const HomeLeft =styled.div`
float:left;
width:625px;
margin-left:15px;
padding-top:30px;
.banner-img{
width:625px;
height:270px;
}
`;
export const HomeRight =styled.div`
float:right;
width:280px;
`;
export const TopicWrapper=styled.div`
padding:20px 0 10px 0;
overflow:hidden;
margin-left:-18px;
border-bottom:1px solid #dcdcdc;
`;
export const TopicItem=styled.div`
float:left;
margin-left:18px;
margin-bottom:18px;
background:#f7f7f7;
height:32px;
line-height:32px;
font-size:14px;
color:#000;
border:1px solid #dcdcdc;
border-radius:4px;
padding-right:10px;
.topic-pic{
display:block;
float:left;
width:32px;
height:32px;
margin-right:10px;
}
`;
export const ListItem=styled.div`
overflow:hidden;
padding:20px 0;
border-bottom:1px solid #dcdcdc;
.pic{
display:block;
width:125px;
height:100px;
float:right;
border-radius:10px;
}
`;
export const ImgInfo=styled.div`
width:500px;
float:left;
.title{
line-height:27px;
font-size:18px;
font-weight:bold;
color:#333;
}
.desc{
font-size:13px;
line-height:24px;
color:#999;
`;
export const RecommendWrapper=styled.div`
margin:26px 0;
width:280px;
`;
export const RecommendItem=styled.div`
width:280px;
height:50px;
background:url(${props=>props.imgUrl});
background-size:contain;
margin-bottom:6px;
`;
export const WriterWrapper=styled.div`
width:280px;
height:300px;
margin:0 0 20px;
position:relative;
`;
export const WriterTitle=styled.div`
margin-top:20px;
margin-bottom:15px;
line-height:20px;
font-size:14px;
color:#969696;
`;
export const WriterSwitch=styled.span`
float:right;
font-size:14px;
cursor:pointer;
`;
export const WriterItem=styled.div`
overflow:hidden;
margin:0 0 15px;
.pic{
display:block;
float:left;
width:48px;
height:48px;
}
`;
export const WriterInfo=styled.div`
float:left;
margin-left:15px;
.title{
display:block;
font-size:14px;
padding-top:10px;
color:#333;
cursor:pointer;
text-decoration:none;
}
.desc{
margin-top:5px;
font-size:12px;
color:#969696;
`;
export const WriterFollow=styled.a`
display:block;
float:right;
color:#42c02e;
font-size:14px;
margin-top:5px;
cursor:pointer;
`;
export const WriterAll=styled.a`
position:absolute;
left:0;
width:278px;
height:34px;
font-size:13px;
padding:7px 7px 7px 12px;
color:#787878;
background:#f7f7f7;
border:1px solid #dcdcdc;
border-radius:4px;
text-align:center;
box-sizing:border-box;
cursor:pointer;
text-decoration:none;
`;
export const LoadMore=styled.div`
width:100%;
height:40px;
margin:30px 0;
line-height:40px;
text-align:center;
background:#a5a5a5;
border-radius:20px;
color:#fff;
cursor:pointer;
`;
export const BackTop=styled.div`
position:fixed;
right:100px;
bottom:100px;
width:60px;
height;60px;
line-height:60px;
text-align:center;
border:1px solid #ccc;
font-size:14px;
`; |
const graphql = require("graphql");
const moment = require("moment");
// const _ = require("lodash");
const Book = require("../model/book");
const Author = require("../model/author");
// const Player = require("../model/player");
const Team = require("../model/team");
const Match = require("../model/match");
const User = require("../model/user");
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLBoolean,
GraphQLList,
GraphQLNonNull
} = graphql;
const AuthorType = new GraphQLObjectType({
name: "Author",
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
age: { type: GraphQLInt },
books: {
type: new GraphQLList(BookType),
resolve(parent, args) {
// return _.filter(books, { authorId: parent.id });
return Book.find({ authorId: parent.id });
}
}
})
});
const BookType = new GraphQLObjectType({
name: "Book",
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
genre: { type: GraphQLString },
author: {
type: AuthorType,
resolve(parent, args) {
// return _.find(authors, { id: parent.authorId });
return Author.findById(parent.authorId);
}
}
})
});
const UserType = new GraphQLObjectType({
name: "User",
fields: () => ({
id: { type: GraphQLID },
googleId: { type: GraphQLString },
token: { type: GraphQLString },
name: { type: GraphQLString },
username: { type: GraphQLString },
email: { type: GraphQLString },
photoURL: { type: GraphQLString },
avatar: { type: GraphQLString },
team: {
type: TeamType,
resolve(parent, args) {
return Team.findById(parent.teamId);
}
}
})
});
// const PlayerType = new GraphQLObjectType({
// name: "Player",
// fields: () => ({
// id: { type: GraphQLID },
// username: { type: GraphQLString },
// avatar: { type: GraphQLString },
// team: {
// type: TeamType,
// resolve(parent, args) {
// return Team.findById(parent.teamId);
// }
// },
// user: {
// type: UserType,
// resolve(parent, args) {
// return User.findById(parent.userId);
// }
// }
// })
// });
const TeamType = new GraphQLObjectType({
name: "Team",
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
short_name: { type: GraphQLString },
avatar: { type: GraphQLString },
public: { type: GraphQLBoolean },
full: { type: GraphQLBoolean },
players: {
type: new GraphQLList(UserType),
resolve(parent, args) {
return User.find({ teamId: parent.id });
}
},
matches: {
type: new GraphQLList(MatchType),
resolve(parent, args) {
return Match.find({
$or: [{ teamId1: parent.id }, { teamId2: parent.id }]
});
}
}
})
});
const MatchType = new GraphQLObjectType({
name: "Match",
fields: () => ({
id: { type: GraphQLID },
date: { type: GraphQLString },
teams: {
type: new GraphQLList(TeamType),
resolve(parent, args) {
// return _.filter(books, { authorId: parent.id });
return Team.find({
_id: {
$in: [parent.teamId1, parent.teamId2]
}
});
}
}
})
});
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
//return _.find(books, { id: args.id });
return Book.findById(args.id);
}
},
author: {
type: AuthorType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
//return _.find(authors, { id: args.id });
return Author.findById(args.id);
}
},
books: {
type: new GraphQLList(BookType),
resolve(parent, args) {
//return books;
return Book.find({});
}
},
authors: {
type: new GraphQLList(AuthorType),
resolve(parent, args) {
//return authors;
return Author.find({});
}
},
user: {
type: UserType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
return User.findById(args.id);
}
},
users: {
type: GraphQLList(UserType),
resolve(parent, args) {
return User.find({});
}
},
// player: {
// type: PlayerType,
// args: { id: { type: GraphQLID } },
// resolve(parent, args) {
// return Player.findById(args.id);
// }
// },
// players: {
// type: new GraphQLList(PlayerType),
// resolve(parent, args) {
// return Player.find({});
// }
// },
team: {
type: TeamType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
return Team.findById(args.id);
}
},
teams: {
type: new GraphQLList(TeamType),
resolve(parent, args) {
return Team.find({});
}
},
match: {
type: MatchType,
args: { id: { type: GraphQLID } },
resolve(parent, args) {
return Match.findById(args.id);
}
},
matches: {
type: new GraphQLList(MatchType),
resolve(parent, args) {
return Match.find({});
}
},
dayMatches: {
type: new GraphQLList(MatchType),
args: { date: { type: GraphQLString } },
resolve(parent, args) {
let date = new Date(args.date);
const start = moment(date).startOf("day");
const end = moment(start).endOf("day");
// Find any match between the start of the given date and the end.
return Match.find({
date: {
$gte: start.toDate(),
$lte: end.toDate()
}
});
}
}
}
});
const Mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
addAuthor: {
type: AuthorType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
age: { type: new GraphQLNonNull(GraphQLInt) }
},
resolve(parent, args) {
let author = new Author({
name: args.name,
age: args.age
});
return author.save();
}
},
addBook: {
type: BookType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
genre: { type: new GraphQLNonNull(GraphQLString) },
authorId: { type: new GraphQLNonNull(GraphQLID) }
},
resolve(parent, args) {
let book = new Book({
name: args.name,
genre: args.genre,
authorId: args.authorId
});
return book.save();
}
},
// createPlayer: {
// type: PlayerType,
// args: {
// username: { type: new GraphQLNonNull(GraphQLString) },
// avatar: { type: GraphQLString },
// teamId: { type: GraphQLID },
// userId: { type: new GraphQLNonNull(GraphQLID) }
// },
// resolve(parent, args) {
// let player = new Player({
// username: args.username,
// avatar: args.avatar,
// teamId: args.teamId,
// userId: args.userId
// });
// return player.save();
// }
// },
createTeam: {
type: TeamType,
args: {
userId: { type: new GraphQLNonNull(GraphQLID) },
name: { type: new GraphQLNonNull(GraphQLString) },
short_name: { type: new GraphQLNonNull(GraphQLString) },
avatar: { type: new GraphQLNonNull(GraphQLString) },
private: { type: new GraphQLNonNull(GraphQLBoolean) }
},
resolve(parent, args) {
let team = new Team({
name: args.name,
short_name: args.short_name,
avatar: args.avatar,
public: args.public,
full: false
});
return team.save().then(team => {
let player = User.findByIdAndUpdate(
args.userId,
{
$set: { teamId: team.id }
},
{ new: true }
);
return team;
});
}
},
addTeamToPlayer: {
type: UserType,
args: {
userId: { type: new GraphQLNonNull(GraphQLID) },
teamId: { type: new GraphQLNonNull(GraphQLID) }
},
resolve(parent, args) {
let player = User.findByIdAndUpdate(
args.userId,
{
$set: { teamId: args.teamId }
},
{ new: true }
);
Team.findByIdAndUpdate(args.teamId, {
$set: { full: true }
});
return player;
}
},
modifyInfo: {
type: UserType,
args: {
userId: { type: new GraphQLNonNull(GraphQLID) },
username: { type: GraphQLString },
avatar: { type: GraphQLString }
},
resolve(parent, args) {
let user = User.findByIdAndUpdate(
args.userId,
{
$set: {
username: args.username,
avatar: args.avatar
}
},
{ new: true }
);
return user;
}
},
createMatch: {
type: MatchType,
args: {
date: { type: new GraphQLNonNull(GraphQLString) },
teamId1: { type: new GraphQLNonNull(GraphQLID) },
teamId2: { type: new GraphQLNonNull(GraphQLID) }
},
resolve(parent, args) {
let match = new Match({
date: new Date(args.date).toISOString(),
teamId1: args.teamId1,
teamId2: args.teamId2
});
return match.save();
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
});
|
const router = require("express").Router();
const itiControlller = require("../../controllers/iticontroller");
// Matches with "/api/itinerary"
router.route("/")
.get(itiControlller.findAll)
.post(itiControlller.create);
// Matches with "/api/itinerary/:id"
router
.route("/:id")
.get(itiControlller.findById)
.put(itiControlller.update)
.delete(itiControlller.remove)
router
.route("/pass/:id")
.get(itiControlller.findByPass)
module.exports = router; |
import React from 'react';
export const Check = props => (
<svg {...props} xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18">
<path
fill="none"
fillRule="evenodd"
stroke="#62BB46"
strokeWidth="2.2"
d="M3.57 8.51l4.453 4.428L15.962 5"
/>
</svg>
);
export const Exclamation = props => (
<svg {...props} xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18">
<path
fill="#D94848"
fillRule="nonzero"
d="M9 2C5.15 2 2 5.15 2 9s3.15 7 7 7 7-3.15 7-7-3.15-7-7-7zm0 12.25c-2.888 0-5.25-2.363-5.25-5.25 0-2.888 2.362-5.25 5.25-5.25 2.887 0 5.25 2.362 5.25 5.25 0 2.887-2.363 5.25-5.25 5.25zM8.125 5.5v4.375h1.75V5.5h-1.75zm.875 7a.875.875 0 1 0 0-1.75.875.875 0 0 0 0 1.75z"
/>
</svg>
);
|
/**
The beating heart of every project.
- Initializes all the other modules
- Provides base utility functions that don't fit in other modules
@author laifrank2002
@date 2019-12-02
*/
var Engine = (
function()
{
return {
/**
Initializes all the other modules
@author laifrank2002
@date 2019-12-02
*/
initialize: function()
{
Engine.log("Initializing Engine...");
StateManager.initialize();
// Adding tests
TestArrayUtilities();
TestDOMElement();
TestInventory();
TestKeyCollection();
TestPersonManager();
TestRandom();
},
/**
Logs a message if logging is enabled.
Quick way to switch between production and development
(other than removing all the Engine.logs using ctrl-f replace)
@param message the message to be logged (can be non-string)
@author laifrank2002
@date 2019-12-02
*/
log: function(message)
{
console.log(message);
},
}
}
)();
|
/*
Class Tree: Position, StrictTransform, Transform
COMPLETE: yes
Wishlist: fake private vars should be made private by either pointers or keys
Rework: added super position
*/
class Position {
constructor(x, y, lockx = false, locky=false) {
this._x = x;
this._y = y;
this.lockX = lockx;
this.lockY = locky;
}
get x(){ return this._x;} // private implementation for locking mechanisms
set x(a){ if(this.lockX){this._x = a;}}
get y(){ return this._y;}
set y(a){ if(this.lockY){this._y = a;}}
get pos() { return [this.x, this.y]; }
set pos(pos) {
this.x = pos[0];
this.y = pos[1];
}
get position() { return [this.x, this.y]; }
set position(pos) {
this.x = pos[0];
this.y = pos[1];
}
};
class StrictTransform extends Position {
constructor(x, y, vx, vy, lockVx = false, lockVy = false) {
super(x, y);
this._vx = vx;
this._vy = vy;
this.lockVx = lockVx;
this.lockVy = lockVy;
}
get vx (){ return this._vx;}
set vx(a){ if(this.lockVx){this._vx = a;}}
get vy(){ return this._vy;}
set vy(a){ if(this.lockVy){this._vy = a;}}
get v() { return [this.vx, this.vy]; }
set v(v) {
this.vx = v[0];
this.vy = v[1];
}
get vector() { return this.v(); }
set vector(v) { this.v = v; }
update() {
this.x += this.vx;
this.y += this.vy;
}
};
class Transform extends StrictTransform {
constructor(x = 0, y = 0, vx = 0, vy = 0, theta = 0, av = 0) {
super(x, y, vx, vy);
this._angle = theta; // in radians counterclockwise from --> (rotated across the z-axis)
this.lockA = false;
this._angularVelocity = av;
this.lockAv = false;
}
get lockAngle(){return this.lockA; }
set lockAngle(a){this.lockA = a;}
get angle(){ return this._angle;} // private implementation for locking mechanisms
set angle(a){ if(this.lockA){this._angle = a;}}
get lockAnglularVelocity(){return this.lockAv; }
set lockAnglularVelocity(a){this.lockAv = a;}
get angularVelocity(){ return this._angularVelocity;} // private implementation for locking mechanisms
set angularVelocity(a){ if(this.lockAv){this._angularVelocity = a;}}
update() {
super.update();
this.theta += omega;
}
get av() {
return this.angularVelocity;
}
set av(x) {
this.angularVelocity = x;
}
get theta() {
return this.angle;
}
set theta(t) {
this.angle = t;
}
get angleInDeg(){
return f.toDeg(this.theta);
};
set angleInDeg(t){
this.theta = f.toRad(t);
};
get omega() {
return this.angularVelocity;
}
set omega(x) {
this.angularVelocity = x;
}
};
class SuperTransform extends Transform{ // allows for temporary (next variables)
constructor(x = 0, y = 0, vx = 0, vy = 0, theta = 0, av = 0) {
super(x, y, vx, vy, theta,av);
this.nx=x;
this.ny=y;
this.nvx=vx
this.nvy=vy;
this.nangle=theta;
this.nav=av;
}
get updateChain(){
return [[0.5, this.update]];
}
update(){
super.update();
this.x=this.nx;
this.y=this.ny;
this.vx= this.nvx;
this.vy = this.nvy;
this.angle=this.nangle;
this.av=this.nav;
}
get nPos() { return [this.nx, this.ny]; }
set nPos(pos) {
this.nx = pos[0];
this.ny = pos[1];
}
get nposition() { return [this.nx, this.ny]; }
set nposition(pos) {
this.nx = pos[0];
this.ny = pos[1];
}
get nextpos() { return [this.nx, this.ny]; }
set nextpos(pos) {
this.nx = pos[0];
this.ny = pos[1];
}
get nextposition() { return [this.nx, this.ny]; }
set nextposition(pos) {
this.nx = pos[0];
this.ny = pos[1];
}
get nv() { return [this.nvx, this.nvy]; }
set nv(v) {
this.nvx = v[0];
this.nvy = v[1];
}
get nvector() { return this.nv(); }
set nvector(v) { this.nv(v); }
get nangularVelocity(){ return this.nav;} // private implementation for locking mechanisms
set nangularVelocity(a){ this.nav=a;}
get ntheta() {
return this.nangle;
}
set ntheta(t) {
this.nangle = t;
}
get nangleInDeg(){
return f.toDeg(this.ntheta);
};
set nangleInDeg(t){
this.ntheta = f.toRad(t);
};
get nomega() {
return this.nav;
}
set nomega(x) {
this.nav = x;
}
reset(){
this.nx=this.x;
this.ny=this.y;
this.nvx=this.vx
this.nvy=this.vy;
this.nangle=this.angle;
this.nav=this.av;
}
} |
const ObjectID = require('mongodb').ObjectID;
const readonly = require('../../hooks/readonly');
module.exports = {
before: {
all: [readonly()],
find: [
context => {
const { app, params } = context;
const { query = {} } = params;
if (query.contract) {
return app.service('tokens').find({
query: {
address: query.contract
}
}).then(tokens => {
if (tokens.data.length === 0) {
return context;
}
query.contract = new ObjectID(tokens.data[0]._id);
context.params.query = query;
return context;
});
}
return Promise.resolve(context);
}
],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
|
$.validator.methods.email = function( value, element ) {
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return this.optional( element ) || emailReg.test( value );
};
jQuery.validator.setDefaults({
success: 'valid'
});
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Caratteri numerici non ammessi");
jQuery.validator.addMethod("username_unique", function(value) {
var isSuccess = false;
$.ajax({ url: "/utenti/check_username",
type: "GET",
data: "username=" + value,
async: false,
dataType:"html",
success: function(msg) { isSuccess = msg === "True" }
});
return isSuccess;
}, "Username non disponibile");
jQuery.validator.addMethod("date",function(value,element){
var reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
return this.optional(element) || reg.test(value);
},"Formato data non corretto");
jQuery.validator.addMethod("username",function(value,element){
var reg=/^[a-zA-Z0-9_\-]+$/;
return this.optional(element) || reg.test(value);
},"Formato username non corretto");
jQuery.validator.addMethod("password_char",function(value,element){
var reg=/^[A-Za-z0-9èòàùì_\-!?&]+$/;
return this.optional(element) || reg.test(value);
},"Formato password non corretto");
jQuery.validator.addMethod("indirizzo",function(value,element){
var reg=/^^[A-Za-z/, 0-9]+$/;
return this.optional(element) || reg.test(value);
},"Formato indirizzo non corretto");
$( '#user-form' ).validate({
rules: {
'username':{
required: true,
minlength: 3,
maxlength: 30,
username_unique: true,
username:true
},
'email':{
required: true,
email: true,
minlength: 5,
maxlength: 50
},
'password':{
required: true,
minlength: 4,
maxlength: 20,
password_char:true
},
'conferma_password':{
equalTo: '#password',
minlength: 4,
maxlength: 20,
password_char:true
},
'first_name': {
required: true,
lettersonly: true,
maxlength: 30
},
'last_name':{
required: true,
lettersonly: true,
maxlength: 30
},
'indirizzo': {
required: true,
minlength: 3,
maxlength: 50,
indirizzo:true
},
'citta':{
required: true,
lettersonly: true,
minlength: 3,
maxlength: 50
},
'telefono':{
required: true,
number: true,
minlength: 3,
maxlength: 30
},
'data_nascita':{
required: true,
date: true,
},
'posti_macchina':{
number:true,
min:0,
max:8
}
},
messages:
{
'username':{
required: "Il campo username è obbligatorio",
minlength: "Scegli un username di almeno 3 lettere",
maxlength: "Limite di 30 caratteri superato",
username:"L'username può contenere solo lettere, numeri, - e _"
},
'email':{
required: "Il campo email è obbligatorio",
email: "Inserisci un valido indirizzo email",
minlength: "Limite minimo di 5 carattere",
maxlength: "Limite di 50 caratteri superato"
},
'password':{
required: "Il campo password è obbligatorio",
minlength: "Inserisci una password di almeno 4 caratteri",
maxlength: "Limite di 20 caratteri superato",
password_char:"La password può contenere lettere, numeri e i seguenti caratteri speciali: '-' '!' '_' '&' '?'"
},
'conferma_password':{
equalTo: "Le due password non coincidono",
minlength: "Inserisci una password di almeno 4 caratteri",
maxlength: "Limite di 20 caratteri superato",
password_char:"La password può contenere lettere, numeri e i seguenti caratteri speciali: '-' '!' '_' '&' '?'"
},
'first_name': {
required: "Il campo nome è obbligatorio",
notNumber: "Caratteri numerici non consentiti",
maxlength: "Limite di 30 caratteri superato"
},
'last_name':{
required: "Il campo cognome è obbligatorio",
maxlength: "Limite di 30 caratteri superato"
},
'indirizzo': {
required: "Il campo indirizzo è obbligatorio",
minlength: "Limite minimo di 3 caratteri",
maxlength: "Limite di 50 caratteri superato",
indirizzo:"Inserire la via e il numero civico, separati da '/' o ','."
},
'citta':{
required: "Il campo citta è obbligatorio",
minlength: "Limite minimo di 3 caratteri",
maxlength: "Limite di 50 caratteri superato"
},
'telefono':{
required: "Il campo telefono è obbligatorio",
number: "Inserisci un numero valido",
minlength: "Limite minimo di 3 caratteri",
maxlength: "Limite di 30 caratteri superato"
},
'data_nascita':{
required: "Il campo data nascita è obbligatorio",
date: "Inserisci una data in formato dd/mm/YYYY"
},
'posti_macchina':{
number: "Inserisci un numero valido",
min: "Devi inserire un numero maggiore o uguale a 0",
max:"Devi inserire un numero minore o uguale a 8"
}
}
});
|
import { USER_REQUEST, USER_SUCCESS } from 'actions/user'
import { List, Map } from 'immutable'
const initialState = Map({
store: List([]),
loading: false
})
export default function (state = initialState, action = {}) {
switch (action.type) {
case USER_REQUEST:
return state.set('loading', true)
case USER_SUCCESS:
const notLoadingState = state.set('loading', false)
return notLoadingState.updateIn(['store'], (store) => {
return store.push(action.response)
})
default:
return state
}
}
|
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: "production",
plugins:[
new HtmlWebpackPlugin({
template: path.resolve(__dirname, `./index.html`), // 指定产的HTML模板
filename: `index.html`, // 产出的HTML文件名
// title: `${page}`,
chunks: ["manifest", "vendor", "common", `index`], // 在产出的HTML文件里引入哪些代码块
hash: true, // 会在引入的js里加入查询字符串避免缓存,
minify: {
removeComments: true,
collapseWhitespace: true
},
// date: new Date().toLocaleDateString(),
inject: "body",
chunksSortMode: "manual"
}),
]
}; |
import ZoomToolBar from "./ui/zoomToolBar";
import BorderSettingsDialog from "./ui/borderSettingDialog";
import paper from "paper";
import * as Registry from "../core/registry";
import * as Colors from "./colors";
import Device from "../core/device";
import ChannelTool from "./tools/channelTool";
import SelectTool from "./tools/selectTool";
import InsertTextTool from "./tools/insertTextTool";
import SimpleQueue from "../utils/simpleQueue";
import MouseSelectTool from "./tools/mouseSelectTool";
import ResolutionToolBar from "./ui/resolutionToolBar";
import RightPanel from "./ui/rightPanel";
import DXFObject from "../core/dxfObject";
import EdgeFeature from "../core/edgeFeature";
import ChangeAllDialog from "./ui/changeAllDialog";
import LayerToolBar from "./ui/layerToolBar";
import * as HTMLUtils from "../utils/htmlUtils";
import MouseAndKeyboardHandler from "./mouseAndKeyboardHandler";
import ComponentToolBar from "./ui/componentToolBar";
import DesignHistory from "./designHistory";
import MoveTool from "./tools/moveTool";
import ComponentPositionTool from "./tools/componentPositionTool";
import MultilayerPositionTool from "./tools/multilayerPositionTool";
import CellPositionTool from "./tools/cellPositionTool";
import ValveInsertionTool from "./tools/valveInsertionTool";
import PositionTool from "./tools/positionTool";
import ConnectionTool from "./tools/connectionTool";
import GenerateArrayTool from "./tools/generateArrayTool";
import CustomComponentManager from "./customComponentManager";
import EditDeviceDialog from "./ui/editDeviceDialog";
import ManufacturingPanel from "./ui/manufacturingPanel";
import CustomComponentPositionTool from "./tools/customComponentPositionTool";
import CustomComponent from "../core/customComponent";
import { setButtonColor } from "../utils/htmlUtils";
import ExportPanel from "./ui/exportPanel";
import HelpDialog from "./ui/helpDialog";
import PaperView from "./paperView";
import AdaptiveGrid from "./grid/adaptiveGrid";
import TaguchiDesigner from "./ui/taguchiDesigner";
import RightClickMenu from "./ui/rightClickMenu";
import IntroDialog from "./ui/introDialog";
import DAFDPlugin from "../plugin/dafdPlugin";
import { Examples } from "../index";
import Feature from "../core/feature";
import Layer from "../core/layer";
import Component from "../core/component";
import DAMPFabricationDialog from "./ui/dampFabricationDialog";
import ControlCellPositionTool from "./tools/controlCellPositionTool";
/**
* View manager class
*/
import { MultiplyOperation } from "three";
export default class ViewManager {
/**
* Default ViewManger Constructor
*/
constructor() {
this.threeD;
this.view = new PaperView("c", this);
this.__grid = new AdaptiveGrid(this);
Registry.currentGrid = this.__grid;
this.tools = {};
this.rightMouseTool = new SelectTool();
this.customComponentManager = new CustomComponentManager(this);
this.rightPanel = new RightPanel(this);
this.changeAllDialog = new ChangeAllDialog();
this.resolutionToolBar = new ResolutionToolBar();
this.borderDialog = new BorderSettingsDialog();
this.layerToolBar = new LayerToolBar();
this.messageBox = document.querySelector(".mdl-js-snackbar");
this.editDeviceDialog = new EditDeviceDialog(this);
this.helpDialog = new HelpDialog();
this.taguchiDesigner = new TaguchiDesigner(this);
this.rightClickMenu = new RightClickMenu();
this.__currentDevice = null;
this._introDialog = new IntroDialog();
this._dampFabricateDialog = new DAMPFabricationDialog();
let reference = this;
this.updateQueue = new SimpleQueue(function() {
reference.view.refresh();
}, 20);
this.saveQueue = new SimpleQueue(function() {
reference.saveToStorage();
});
this.undoStack = new DesignHistory();
this.pasteboard = [];
this.mouseAndKeyboardHandler = new MouseAndKeyboardHandler(this);
this.view.setResizeFunction(function() {
reference.updateGrid();
reference.updateAlignmentMarks();
reference.view.updateRatsNest();
reference.view.updateComponentPortsRender();
reference.updateDevice(Registry.currentDevice);
});
let func = function(event) {
reference.adjustZoom(event.deltaY, reference.getEventPosition(event));
};
this.manufacturingPanel = new ManufacturingPanel(this);
this.exportPanel = new ExportPanel(this);
this.view.setMouseWheelFunction(func);
this.minZoom = 0.0001;
this.maxZoom = 5;
this.setupTools();
//TODO: Figure out how remove UpdateQueue as dependency mechanism
this.__grid.setColor(Colors.BLUE_500);
//Removed from Page Setup
this.threeD = false;
this.renderer = Registry.threeRenderer;
this.__button2D = document.getElementById("button_2D");
this.__canvasBlock = document.getElementById("canvas_block");
this.__renderBlock = document.getElementById("renderContainer");
this.setupDragAndDropLoad("#c");
this.setupDragAndDropLoad("#renderContainer");
this.switchTo2D();
}
/**
* Returns the current device the ViewManager is displaying. Right now I'm using this to replace the
* Registry.currentDevice dependency, however this might change as the modularity requirements change.
*
* @return {Device}
* @memberof ViewManager
*/
get currentDevice() {
return this.__currentDevice;
}
/**
* Initiates the copy operation on the selected feature
* @returns {void}
* @memberof ViewManager
*/
initiateCopy() {
let selectedFeatures = this.view.getSelectedFeatures();
if (selectedFeatures.length > 0) {
this.pasteboard[0] = selectedFeatures[0];
}
}
/**
* Initiating the zoom toolbar
* @memberof ViewManager
* @returns {void}
*/
setupToolBars() {
//Initiating the zoom toolbar
this.zoomToolBar = new ZoomToolBar(0.0001, 5);
this.componentToolBar = new ComponentToolBar(this);
this.resetToDefaultTool();
}
/**
* Adds a device to the view manager
* @param {Device} device Device to be added
* @param {Boolean} refresh Default true
* @memberof ViewManager
* @returns {void}
*/
addDevice(device, refresh = true) {
this.view.addDevice(device);
this.__addAllDeviceLayers(device, false);
this.refresh(refresh);
}
/**
* Adds all the layers in the device
* @param {Device} device Selected device
* @param {boolean} refresh Whether to refresh or not. true by default
* @memberof ViewManager
* @returns {void}
* @private
*/
__addAllDeviceLayers(device, refresh = true) {
for (let i = 0; i < device.layers.length; i++) {
let layer = device.layers[i];
this.addLayer(layer, i, false);
}
}
/**
* Removes all layers in the device
* @param {Device} device Selected device
* @param {boolean} refresh Whether to refresh or not. true by default
* @memberof ViewManager
* @returns {void}
*/
__removeAllDeviceLayers(device, refresh = true) {
for (let i = 0; i < device.layers.length; i++) {
let layer = device.layers[i];
this.removeLayer(layer, i, false);
}
}
/**
* Removes the device from the view
* @param {Device} device Selected device to remove
* @param {Boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
removeDevice(device, refresh = true) {
this.view.removeDevice(device);
this.__removeAllDeviceLayers(device, false);
this.refresh(refresh);
}
/**
* Updates the device in the view
* @param {Device} device Selected device to update
* @param {boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
updateDevice(device, refresh = true) {
this.view.updateDevice(device);
this.refresh(refresh);
}
/**
* Adds a feature to the view
* @param {Feature} feature Feature to add
* @param {Boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
addFeature(feature, refresh = true) {
if (this.__isFeatureInCurrentDevice(feature)) {
this.view.addFeature(feature);
this.refresh(refresh);
}
}
/**
* Updates a feature from the view
* @param {Feature} feature Feature to update
* @param {boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
updateFeature(feature, refresh = true) {
if (this.__isFeatureInCurrentDevice(feature)) {
this.view.updateFeature(feature);
this.refresh(refresh);
}
}
/**
* Removes feature from the view
* @param {Feature} feature Feature to remove
* @param {boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
removeFeature(feature, refresh = true) {
if (this.__isFeatureInCurrentDevice(feature)) {
this.view.removeFeature(feature);
this.refresh(refresh);
}
}
/**
* Adds layer to the view
* @param {Layer} layer Layer to add
* @param {Number} index Index of the layer
* @param {Boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
addLayer(layer, index, refresh = true) {
if (this.__isLayerInCurrentDevice(layer)) {
this.view.addLayer(layer, index, false);
this.__addAllLayerFeatures(layer, false);
this.refresh(refresh);
}
}
/**
* Create a new set of layers (flow, control and cell) for the upcoming level.
* @returns {void}
* @memberof ViewManager
*/
createNewLayerBlock() {
let newlayers = Registry.currentDevice.createNewLayerBlock();
newlayers[0].color = "indigo";
newlayers[1].color = "red";
//Find all the edge features
let edgefeatures = [];
let devicefeatures = Registry.currentDevice.layers[0].features;
let feature;
for (let i in devicefeatures) {
feature = devicefeatures[i];
if (feature.fabType === "EDGE") {
edgefeatures.push(feature);
}
}
//Add the Edge Features from layer '0'
// to all other layers
for (let i in newlayers) {
for (let j in edgefeatures) {
newlayers[i].addFeature(edgefeatures[j], false);
}
}
//Added the new layers
for (let i in newlayers) {
let layertoadd = newlayers[i];
let index = this.view.paperLayers.length;
this.addLayer(layertoadd, index, true);
}
}
/**
* Deletes the layers at the level index, we have 3-set of layers so it deletes everything at
* that level
* @param {number} levelindex Integer only
* @returns {void}
* @memberof ViewManager
*/
deleteLayerBlock(levelindex) {
//Delete the levels in the device model
Registry.currentDevice.deleteLayer(levelindex * 3);
Registry.currentDevice.deleteLayer(levelindex * 3 + 1);
Registry.currentDevice.deleteLayer(levelindex * 3 + 2);
//Delete the levels in the render model
this.view.removeLayer(levelindex * 3);
this.view.removeLayer(levelindex * 3 + 1);
this.view.removeLayer(levelindex * 3 + 2);
this.updateActiveLayer();
this.refresh();
}
/**
* Removes layer from the view
* @param {Layer} layer Layer to be removed from the view
* @param {Number} index Index of the layer to remove
* @param {Boolean} refresh Default to true
* @returns {view}
* @memberof ViewManager
*/
removeLayer(layer, index, refresh = true) {
if (this.__isLayerInCurrentDevice(layer)) {
this.view.removeLayer(layer, index);
this.__removeAllLayerFeatures(layer);
this.refresh(refresh);
}
}
/**
* Converts the layers to SVG format
* @returns {}
* @memberof ViewManager
*/
layersToSVGStrings() {
return this.view.layersToSVGStrings();
}
/**
* Adds all the features of the layer
* @param {Layer} layer Selected layer
* @param {Boolean} refresh Default to true
* @returns {void}
* @memberof ViewManager
* @private
*/
__addAllLayerFeatures(layer, refresh = true) {
for (let key in layer.features) {
let feature = layer.features[key];
this.addFeature(feature, false);
this.refresh(refresh);
}
}
/**
* Updates all the feature of the layer
* @param {Layer} layer Selected layer
* @param {boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
__updateAllLayerFeatures(layer, refresh = true) {
for (let key in layer.features) {
let feature = layer.features[key];
this.updateFeature(feature, false);
this.refresh(refresh);
}
}
/**
* Removes all feature of the layer
* @param {Layer} layer Selected layer
* @param {Boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
__removeAllLayerFeatures(layer, refresh = true) {
for (let key in layer.features) {
let feature = layer.features[key];
this.removeFeature(feature, false);
this.refresh(refresh);
}
}
/**
* Updates layer
* @param {Layer} layer Selected layer to be updated
* @param {boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
updateLayer(layer, refresh = true) {
if (this.__isLayerInCurrentDevice(layer)) {
this.view.updateLayer(layer);
this.refresh(refresh);
}
}
/**
* Updates the active layer
* @param {Boolean} refresh Default to true
* @returns {void}
* @memberof ViewManager
*/
updateActiveLayer(refresh = true) {
this.view.setActiveLayer(Registry.currentDevice.layers.indexOf(Registry.currentLayer));
this.refresh(refresh);
}
/**
* Removes the grid
* @param {Boolean} refresh Default to true
* @returns {void}
* @memberof ViewManager
*/
removeGrid(refresh = true) {
if (this.__hasCurrentGrid()) {
this.view.removeGrid();
this.refresh(refresh);
}
}
/**
* Update grid
* @param {Boolean} refresh Default to true
* @returns {void}
* @memberof ViewManager
*/
updateGrid(refresh = true) {
if (this.__hasCurrentGrid()) {
this.view.updateGrid(Registry.currentGrid);
this.refresh(refresh);
}
}
/**
* Update the alignment marks of the view
* @returns {void}
* @memberof ViewManager
*/
updateAlignmentMarks() {
this.view.updateAlignmentMarks();
}
/**
* Clear the view
* @returns {void}
* @memberof ViewManager
*/
clear() {
this.view.clear();
}
/**
* Sets a specific value of zoom
* @param {Number} zoom Zoom value
* @param {boolean} refresh Whether it will refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
setZoom(zoom, refresh = true) {
if (zoom > this.maxZoom) zoom = this.maxZoom;
else if (zoom < this.minZoom) zoom = this.minZoom;
this.view.setZoom(zoom);
this.updateGrid(false);
this.updateAlignmentMarks();
this.view.updateRatsNest();
this.view.updateComponentPortsRender();
this.updateDevice(Registry.currentDevice, false);
this.__updateViewTarget(false);
this.zoomToolBar.setZoom(zoom);
this.refresh(refresh);
}
/**
* Automatically generates a rectangular border for the device
* @returns {void}
* @memberof ViewManager
*/
generateBorder() {
let borderfeature = new EdgeFeature(null, null);
//Get the bounds for the border feature and then update the device dimensions
let xspan = Registry.currentDevice.getXSpan();
let yspan = Registry.currentDevice.getYSpan();
borderfeature.generateRectEdge(xspan, yspan);
//Adding the feature to all the layers
for (let i in Registry.currentDevice.layers) {
let layer = Registry.currentDevice.layers[i];
layer.addFeature(borderfeature);
}
}
/**
* Accepts a DXF object and then converts it into a feature, an edgeFeature in particular
* @param dxfobject
* @returns {void}
* @memberof ViewManager
*/
importBorder(dxfobject) {
let customborderfeature = new EdgeFeature(null, null);
for (let i in dxfobject.entities) {
let foo = new DXFObject(dxfobject.entities[i]);
customborderfeature.addDXFObject(foo);
}
//Adding the feature to all the layers
for (let i in Registry.currentDevice.layers) {
let layer = Registry.currentDevice.layers[i];
layer.addFeature(customborderfeature);
}
//Get the bounds for the border feature and then update the device dimensions
let bounds = this.view.getRenderedFeature(customborderfeature.getID()).bounds;
Registry.currentDevice.setXSpan(bounds.width);
Registry.currentDevice.setYSpan(bounds.height);
//Refresh the view
Registry.viewManager.view.initializeView();
Registry.viewManager.view.refresh();
}
/**
* Deletes the border
* @returns {void}
* @memberof ViewManager
*/
deleteBorder() {
/*
1. Find all the features that are EDGE type
2. Delete all these features
*/
console.log("Deleting border...");
let features = Registry.currentDevice.getAllFeaturesFromDevice();
console.log("All features", features);
let edgefeatures = [];
for (let i in features) {
//Check if the feature is EDGE or not
if ("EDGE" === features[i].fabType) {
edgefeatures.push(features[i]);
}
}
//Delete all the features
for (let i in edgefeatures) {
Registry.currentDevice.removeFeatureByID(edgefeatures[i].getID());
}
console.log("Edgefeatures", edgefeatures);
}
/**
* Removes the target view
* @memberof ViewManager
* @returns {void}
*/
removeTarget() {
this.view.removeTarget();
}
/**
* Update the target view
* @param {string} featureType
* @param {string} featureSet
* @param {Array<number>} position Array with X and Y coordinates
* @param {boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
updateTarget(featureType, featureSet, position, refresh = true) {
this.view.addTarget(featureType, featureSet, position);
this.view.updateAlignmentMarks();
this.view.updateRatsNest();
this.refresh(refresh);
}
/**
* Update the view target
* @param {Boolean} refresh Default to true
* @returns {void}
* @memberof ViewManager
*/
__updateViewTarget(refresh = true) {
this.view.updateTarget();
this.updateAlignmentMarks();
this.view.updateRatsNest();
this.view.updateComponentPortsRender();
this.refresh(refresh);
}
/**
* Adjust the zoom value in a certain point
* @param {Number} delta Value of zoom
* @param {Array<number>} point Coordinates to zoom in
* @param {Boolean} refresh Default to true
* @returns {void}
* @memberof ViewManager
*/
adjustZoom(delta, point, refresh = true) {
let belowMin = this.view.getZoom() >= this.maxZoom && delta < 0;
let aboveMax = this.view.getZoom() <= this.minZoom && delta > 0;
if (!aboveMax && !belowMin) {
this.view.adjustZoom(delta, point);
this.updateGrid(false);
//this.updateAlignmentMarks();
this.view.updateRatsNest();
this.view.updateComponentPortsRender();
this.updateDevice(Registry.currentDevice, false);
this.__updateViewTarget(false);
} else {
//console.log("Too big or too small!");
}
this.refresh(refresh);
}
/**
* Sets the center value
* @param {Array<number>} center Center coordinates
* @param {Boolean} refresh Default to true
* @returns {void}
* @memberof ViewManager
*/
setCenter(center, refresh = true) {
this.view.setCenter(center);
this.updateGrid(false);
//this.updateAlighmentMarks();
this.updateDevice(Registry.currentDevice, false);
this.refresh(refresh);
}
/**
* Moves center by a certain value
* @param {number} delta
* @param {boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
moveCenter(delta, refresh = true) {
this.view.moveCenter(delta);
this.updateGrid(false);
// this.updateAlignmentMarks();
this.view.updateRatsNest();
this.view.updateComponentPortsRender();
this.updateDevice(Registry.currentDevice, false);
this.refresh(refresh);
}
/**
* Save the device to JSON format
* @returns {void}
* @memberof ViewManager
*/
saveToStorage() {
if (Registry.currentDevice) {
try {
localStorage.setItem("currentDevice", JSON.stringify(Registry.currentDevice.toJSON()));
} catch (err) {
// can't save, so.. don't?
}
}
}
/**
* Refresh the view
* @param {boolean} refresh Whether to refresh or not. true by default
* @returns {void}
* @memberof ViewManager
*/
refresh(refresh = true) {
this.updateQueue.run();
//Update the toolbar
let spacing = Registry.currentGrid.getSpacing();
this.resolutionToolBar.updateResolutionLabelAndSlider(spacing);
}
/**
* Gets the coordinates of the project
* @param {*} event
* @returns {Array<number>} Returns the X and Y coordinates
* @memberof ViewManager
*/
getEventPosition(event) {
return this.view.getProjectPosition(event.clientX, event.clientY);
}
/**
* Checks if it has current grid
* @returns {Boolean}
* @memberof ViewManager
*/
__hasCurrentGrid() {
if (Registry.currentGrid) return true;
else return false;
}
/**
* Checks if layer is in the current device
* @param {Layer} layer Layer to check if it's on the current device
* @returns {Boolean}
* @memberof ViewManager
*/
__isLayerInCurrentDevice(layer) {
if (Registry.currentDevice && layer.device === Registry.currentDevice) return true;
else return false;
}
/**
* Checks if feature is in the current device
* @param {Object} feature Feature to check if it's on the current device
* @returns {Boolean}
* @memberof ViewManager
*/
__isFeatureInCurrentDevice(feature) {
if (Registry.currentDevice && this.__isLayerInCurrentDevice(feature.layer)) return true;
else return false;
}
/**
* Loads a device from a JSON format
* @param {JSON} json
* @returns {void}
* @memberof ViewManager
*/
loadDeviceFromJSON(json) {
let device;
Registry.viewManager.clear();
//Check and see the version number if its 0 or none is present,
// its going the be the legacy format, else it'll be a new format
let version = json.version;
if (null === version || undefined === version) {
console.log("Loading Legacy Format...");
device = Device.fromJSON(json);
Registry.currentDevice = device;
this.__currentDevice = device;
} else {
console.log("Version Number: " + version);
switch (version) {
case 1:
this.loadCustomComponents(json);
device = Device.fromInterchangeV1(json);
Registry.currentDevice = device;
this.__currentDevice = device;
break;
case 1.1:
this.loadCustomComponents(json);
device = Device.fromInterchangeV1_1(json);
Registry.currentDevice = device;
this.__currentDevice = device;
break;
case 1.2:
this.loadCustomComponents(json);
device = Device.fromInterchangeV1_2(json);
Registry.currentDevice = device;
this.__currentDevice = device;
break;
default:
alert("Version '" + version + "' is not supported by 3DuF !");
}
}
//Common Code for rendering stuff
// console.log("Feature Layers", Registry.currentDevice.layers);
Registry.currentLayer = Registry.currentDevice.layers[0];
Registry.currentTextLayer = Registry.currentDevice.textLayers[0];
//TODO: Need to replace the need for this function, right now without this, the active layer system gets broken
Registry.viewManager.addDevice(Registry.currentDevice);
//In case of MINT exported json, generate layouts for rats nests
this.__initializeRatsNest();
this.view.initializeView();
this.updateGrid();
this.updateDevice(Registry.currentDevice);
this.refresh(true);
Registry.currentLayer = Registry.currentDevice.layers[0];
this.layerToolBar.setActiveLayer("0");
Registry.viewManager.updateActiveLayer();
}
/**
* Removes the features of the current device by searching on it's ID
* @param {*} paperElements
* @returns {void}
* @memberof ViewManager
*/
removeFeaturesByPaperElements(paperElements) {
if (paperElements.length > 0) {
for (let i = 0; i < paperElements.length; i++) {
let paperFeature = paperElements[i];
Registry.currentDevice.removeFeatureByID(paperFeature.featureID);
}
this.currentSelection = [];
}
}
/**
* Updates the component parameters of a specific component
* @param {string} componentname
* @param {Array} params
* @returns {void}
* @memberof ViewManager
*/
updateComponentParameters(componentname, params) {
let component = this.__currentDevice.getComponentByName(componentname);
for (let key in params) {
component.updateParameter(key, params[key]);
}
}
/**
* Returns a Point, coordinate list that is the closes grid coordinate
* @param {Array<number>} point Array with the X and Y coordinates
* @return {void|Array<number>}
* @memberof ViewManager
*/
snapToGrid(point) {
if (Registry.currentGrid) return Registry.currentGrid.getClosestGridPoint(point);
else return point;
}
/**
* Gets the features of a specific type ?
* @param {string} typeString
* @param {string} setString
* @param {Array} features Array with features
* @returns {Array} Returns array with the features of a specific type
* @memberof ViewManager
*/
getFeaturesOfType(typeString, setString, features) {
let output = [];
for (let i = 0; i < features.length; i++) {
let feature = features[i];
if (feature.getType() === typeString && feature.getSet() === setString) {
output.push(feature);
}
}
return output;
}
/**
* Updates all feature parameters
* @param {string} valueString
* @param {*} value
* @param {Array} features Array of features
* @returns {void}
* @memberof ViewManager
*/
adjustAllFeatureParams(valueString, value, features) {
for (let i = 0; i < features.length; i++) {
let feature = features[i];
feature.updateParameter(valueString, value);
}
}
/**
* Adjust all parameters of the same type
* @param {string} typeString
* @param {string} setString
* @param {string} valueString
* @param {*} value
* @returns {void}
* @memberof ViewManager
*/
adjustParams(typeString, setString, valueString, value) {
let selectedFeatures = this.view.getSelectedFeatures();
if (selectedFeatures.length > 0) {
let correctType = this.getFeaturesOfType(typeString, setString, selectedFeatures);
if (correctType.length > 0) {
this.adjustAllFeatureParams(valueString, value, correctType);
}
//Check if any components are selected
//TODO: modify parameters window to not have chain of updates
//Cycle through all components and connections and change the parameters
for (let i in this.view.selectedComponents) {
this.view.selectedComponents[i].updateParameter(valueString, value);
}
for (let i in this.view.selectedConnections) {
this.view.selectedConnections[i].updateParameter(valueString, value);
}
} else {
this.updateDefault(typeString, setString, valueString, value);
}
}
/**
* Center all the components and connections on the canvas
* @returns {void}
* @memberof ViewManager
*/
centerAll() {
const components = this.currentDevice.getComponents();
const connections = this.currentDevice.getConnections();
if (components.length > 0) {
// Find the center of the design
let leftBound = 0,
rightBound = 0,
upperBound = 0,
lowerBound = 0;
[leftBound, upperBound] = components[0].getParams().getValue("position");
[rightBound, lowerBound] = components[0].getParams().getValue("position");
components.forEach(component => {
const position = component.getParams().getValue("position");
leftBound = Math.min(leftBound, position[0]);
rightBound = Math.max(rightBound, position[0]);
upperBound = Math.min(upperBound, position[1]);
lowerBound = Math.max(lowerBound, position[1]);
});
connections.forEach(connection => {
const position = connection.getParams().getValue("start");
leftBound = Math.min(leftBound, position[0]);
rightBound = Math.max(rightBound, position[0]);
upperBound = Math.min(upperBound, position[1]);
lowerBound = Math.max(lowerBound, position[1]);
});
const centerX = (leftBound + rightBound) / 2;
const centerY = (upperBound + lowerBound) / 2;
// Calculate the change of position
const changeX = this.currentDevice.getXSpan() / 2 - centerX;
const changeY = this.currentDevice.getYSpan() / 2 - centerY;
// Move every component to its center
components.forEach(component => {
const position = component.getParams().getValue("position");
component.updateComponentPosition([position[0] + changeX, position[1] + changeY]);
});
// Move every connection to its center
connections.forEach(connection => {
connection.updateConnectionPosition(changeX, changeY);
});
}
}
/**
* Updates the default feature parameter
* @param {string} typeString
* @param {string} setString
* @param {string} valueString
* @param value
* @returns {void}
* @memberof ViewManager
*/
updateDefault(typeString, setString, valueString, value) {
Registry.featureDefaults[setString][typeString][valueString] = value;
}
/**
* Updates the defaults in the feature
* @param {Feature} feature Feature object
* @returns {void}
* @memberof ViewManager
*/
updateDefaultsFromFeature(feature) {
let heritable = feature.getHeritableParams();
for (let key in heritable) {
this.updateDefault(feature.getType(), feature.getSet(), key, feature.getValue(key));
}
}
/**
* Reverts the feature to default
* @param {string} valueString
* @param {Feature} feature
* @returns {void}
* @memberof ViewManager
*/
revertFieldToDefault(valueString, feature) {
feature.updateParameter(valueString, Registry.featureDefaults[feature.getSet()][feature.getType()][valueString]);
}
/**
* Reverts the feature to params to defaults
* @param {Feature} feature
* @returns {void}
* @memberof ViewManager
*/
revertFeatureToDefaults(feature) {
let heritable = feature.getHeritableParams();
for (let key in heritable) {
this.revertFieldToDefault(key, feature);
}
}
/**
* Reverts features to defaults
* @param {Array} features Features to revert to default
* @returns {void}
* @memberof ViewManager
*/
revertFeaturesToDefaults(features) {
for (let feature in features) {
this.revertFeatureToDefaults(feature);
}
}
/**
* Checks if the point intersects with any other feature
* @param {Array<number>} point Array with the X and Y coordinates
* @return PaperJS rendered Feature
* @memberof ViewManager
*/
hitFeature(point) {
return this.view.hitFeature(point);
}
/**
* Checks if the element intersects with any other feature
* @param element
* @return {*|Array}
* @memberof ViewManager
*/
hitFeaturesWithViewElement(element) {
return this.view.hitFeaturesWithViewElement(element);
}
/**
* Activates the given tool
* @param {string} toolString
* @param rightClickToolString
* @returns {void}
* @memberof ViewManager
*/
activateTool(toolString, rightClickToolString = "SelectTool") {
if (this.tools[toolString] === null) {
throw new Error("Could not find tool with the matching string");
}
//Cleanup job when activating new tool
this.view.clearSelectedItems();
this.mouseAndKeyboardHandler.leftMouseTool = this.tools[toolString];
this.mouseAndKeyboardHandler.rightMouseTool = this.tools[rightClickToolString];
this.mouseAndKeyboardHandler.updateViewMouseEvents();
}
/**
* Switches to 2D
* @returns {void}
* @memberof ViewManager
*/
switchTo2D() {
if (this.threeD) {
this.threeD = false;
let center = this.renderer.getCameraCenterInMicrometers();
let zoom = this.renderer.getZoom();
let newCenterX = center[0];
if (newCenterX < 0) {
newCenterX = 0;
} else if (newCenterX > Registry.currentDevice.params.getValue("width")) {
newCenterX = Registry.currentDevice.params.getValue("width");
}
let newCenterY = paper.view.center.y - center[1];
if (newCenterY < 0) {
newCenterY = 0;
} else if (newCenterY > Registry.currentDevice.params.getValue("height")) {
newCenterY = Registry.currentDevice.params.getValue("height");
}
HTMLUtils.setButtonColor(this.__button2D, Colors.getDefaultLayerColor(Registry.currentLayer), activeText);
HTMLUtils.setButtonColor(this.__button3D, inactiveBackground, inactiveText);
Registry.viewManager.setCenter(new paper.Point(newCenterX, newCenterY));
Registry.viewManager.setZoom(zoom);
HTMLUtils.addClass(this.__renderBlock, "hidden-block");
HTMLUtils.removeClass(this.__canvasBlock, "hidden-block");
HTMLUtils.removeClass(this.__renderBlock, "shown-block");
HTMLUtils.addClass(this.__canvasBlock, "shown-block");
}
}
/**
* Switches to 3D
* @returns {void}
* @memberof ViewManager
*/
switchTo3D() {
if (!this.threeD) {
this.threeD = true;
setButtonColor(this.__button3D, Colors.getDefaultLayerColor(Registry.currentLayer), activeText);
setButtonColor(this.__button2D, inactiveBackground, inactiveText);
this.renderer.loadJSON(Registry.currentDevice.toJSON());
let cameraCenter = this.view.getViewCenterInMillimeters();
let height = Registry.currentDevice.params.getValue("height") / 1000;
let pixels = this.view.getDeviceHeightInPixels();
this.renderer.setupCamera(cameraCenter[0], cameraCenter[1], height, pixels, paper.view.zoom);
this.renderer.showMockup();
HTMLUtils.removeClass(this.__renderBlock, "hidden-block");
HTMLUtils.addClass(this.__canvasBlock, "hidden-block");
HTMLUtils.addClass(this.__renderBlock, "shown-block");
HTMLUtils.removeClass(this.__canvasBlock, "shown-block");
}
}
/**
* Loads a device from a JSON format when the user drags and drops it on the grid
* @param selector
* @returns {void}
* @memberof ViewManager
*/
setupDragAndDropLoad(selector) {
let dnd = new HTMLUtils.DnDFileController(selector, function(files) {
let f = files[0];
let reader = new FileReader();
reader.onloadend = function(e) {
let result = this.result;
// try {
result = JSON.parse(result);
Registry.viewManager.loadDeviceFromJSON(result);
Registry.viewManager.switchTo2D();
// } catch (error) {
// console.error(error.message);
// alert("Unable to parse the design file, please ensure that the file is not corrupted:\n" + error.message);
// }
};
try {
reader.readAsText(f);
} catch (err) {
console.log("unable to load JSON: " + f);
}
});
}
/**
* Closes the params window
* @returns {void}
* @memberof ViewManager
*/
killParamsWindow() {
let paramsWindow = document.getElementById("parameter_menu");
if (paramsWindow) paramsWindow.parentElement.removeChild(paramsWindow);
}
/**
* This method saves the current device to the design history
* @memberof ViewManager
* @returns {void}
*/
saveDeviceState() {
console.log("Saving to statck");
let save = JSON.stringify(Registry.currentDevice.toInterchangeV1());
this.undoStack.pushDesign(save);
}
/**
* Undoes the recent update
* @returns {void}
* @memberof ViewManager
*/
undo() {
let previousdesign = this.undoStack.popDesign();
console.log(previousdesign);
if (previousdesign) {
let result = JSON.parse(previousdesign);
this.loadDeviceFromJSON(result);
}
}
/**
* Resets the tool to the default tool
* @returns {void}
* @memberof ViewManager
*/
resetToDefaultTool() {
this.cleanupActiveTools();
this.activateTool("MouseSelectTool");
this.componentToolBar.setActiveButton("SelectButton");
}
/**
* Runs cleanup method on the activated tools
* @returns {void}
* @memberof ViewManager
*/
cleanupActiveTools() {
if (this.mouseAndKeyboardHandler.leftMouseTool) {
this.mouseAndKeyboardHandler.leftMouseTool.cleanup();
}
if (this.mouseAndKeyboardHandler.rightMouseTool) {
this.mouseAndKeyboardHandler.rightMouseTool.cleanup();
}
}
/**
* Updates the renders for all the connection in the blah
* @returns {void}
* @memberof ViewManager
*/
updatesConnectionRender(connection, angle = 0) {
//First Redraw all the segements without valves or insertions
connection.regenerateSegments();
//Get all the valves for a connection
let valves = Registry.currentDevice.getValvesForConnection(connection);
//Cycle through each of the valves
valves.forEach(valve => {
let is3D = Registry.currentDevice.getIsValve3D(valve);
if (is3D) {
let boundingbox = valve.getBoundingRectangle();
connection.insertFeatureGap(boundingbox, angle);
}
});
// for (let j in valves) {
// let valve = valves[j];
// let is3D = Registry.currentDevice.getIsValve3D(valve);
// if (is3D) {
// let boundingbox = valve.getBoundingRectangle();
// connection.insertFeatureGap(boundingbox);
// }
// }
}
/**
* Shows in the UI a message
* @param {string} message Messsage to display
* @returns {void}
* @memberof ViewManager
*/
showUIMessage(message) {
this.messageBox.MaterialSnackbar.showSnackbar({
message: message
});
}
/**
* Sets up all the tools to be used by the user
* @returns {void}
* @memberof ViewManager
*/
setupTools() {
this.tools["MouseSelectTool"] = new MouseSelectTool(this.view);
this.tools["InsertTextTool"] = new InsertTextTool();
this.tools["Chamber"] = new ComponentPositionTool("Chamber", "Basic");
this.tools["Valve"] = new ValveInsertionTool("Valve", "Basic");
this.tools["Channel"] = new ChannelTool("Channel", "Basic");
this.tools["Connection"] = new ConnectionTool("Connection", "Basic");
this.tools["RoundedChannel"] = new ChannelTool("RoundedChannel", "Basic");
this.tools["Node"] = new ComponentPositionTool("Node", "Basic");
this.tools["CircleValve"] = new ValveInsertionTool("CircleValve", "Basic");
this.tools["RectValve"] = new ComponentPositionTool("RectValve", "Basic");
this.tools["Valve3D"] = new ValveInsertionTool("Valve3D", "Basic", true);
this.tools["Port"] = new ComponentPositionTool("Port", "Basic");
this.tools["Anode"] = new ComponentPositionTool("Anode", "Basic"); //Ck
this.tools["Cathode"] = new ComponentPositionTool("Cathode", "Basic"); //Ck
this.tools["Via"] = new ComponentPositionTool("Via", "Basic");
this.tools["DiamondReactionChamber"] = new ComponentPositionTool("DiamondReactionChamber", "Basic");
this.tools["thermoCycler"] = new ComponentPositionTool("thermoCycler", "Basic");
this.tools["BetterMixer"] = new ComponentPositionTool("BetterMixer", "Basic");
this.tools["CurvedMixer"] = new ComponentPositionTool("CurvedMixer", "Basic");
this.tools["Mixer"] = new ComponentPositionTool("Mixer", "Basic");
this.tools["GradientGenerator"] = new ComponentPositionTool("GradientGenerator", "Basic");
this.tools["Tree"] = new ComponentPositionTool("Tree", "Basic");
this.tools["YTree"] = new ComponentPositionTool("YTree", "Basic");
this.tools["Mux"] = new MultilayerPositionTool("Mux", "Basic");
this.tools["Transposer"] = new MultilayerPositionTool("Transposer", "Basic");
this.tools["RotaryMixer"] = new MultilayerPositionTool("RotaryMixer", "Basic");
this.tools["CellTrapL"] = new CellPositionTool("CellTrapL", "Basic");
this.tools["Gelchannel"] = new CellPositionTool("Gelchannel", "Basic"); //ck
this.tools["DropletGen"] = new ComponentPositionTool("DropletGen", "Basic");
this.tools["Transition"] = new PositionTool("Transition", "Basic");
this.tools["AlignmentMarks"] = new MultilayerPositionTool("AlignmentMarks", "Basic");
this.tools["Pump"] = new MultilayerPositionTool("Pump", "Basic");
this.tools["Pump3D"] = new MultilayerPositionTool("Pump3D", "Basic");
this.tools["LLChamber"] = new MultilayerPositionTool("LLChamber", "Basic");
this.tools["3DMixer"] = new MultilayerPositionTool("3DMixer", "Basic");
//All the new tools
this.tools["MoveTool"] = new MoveTool();
this.tools["GenerateArrayTool"] = new GenerateArrayTool();
//new
this.tools["Filter"] = new ComponentPositionTool("Filter", "Basic");
this.tools["CellTrapS"] = new CellPositionTool("CellTrapS", "Basic");
this.tools["3DMux"] = new MultilayerPositionTool("3DMux", "Basic");
this.tools["ChemostatRing"] = new MultilayerPositionTool("ChemostatRing", "Basic");
this.tools["Incubation"] = new ComponentPositionTool("Incubation", "Basic");
this.tools["Merger"] = new ComponentPositionTool("Merger", "Basic");
this.tools["PicoInjection"] = new ComponentPositionTool("PicoInjection", "Basic");
this.tools["Sorter"] = new ComponentPositionTool("Sorter", "Basic");
this.tools["Splitter"] = new ComponentPositionTool("Splitter", "Basic");
this.tools["CapacitanceSensor"] = new ComponentPositionTool("CapacitanceSensor", "Basic");
this.tools["DropletGenT"] = new ComponentPositionTool("DropletGenT", "Basic");
this.tools["DropletGenFlow"] = new ComponentPositionTool("DropletGenFlow", "Basic");
this.tools["LogicArray"] = new ControlCellPositionTool("LogicArray", "Basic");
}
/**
* Adds a custom component tool
* @param {string} identifier
* @returns {void}
* @memberof ViewManager
*/
addCustomComponentTool(identifier) {
let customcomponent = this.customComponentManager.getCustomComponent(identifier);
this.tools[identifier] = new CustomComponentPositionTool(customcomponent, "Custom");
Registry.featureDefaults["Custom"][identifier] = CustomComponent.defaultParameterDefinitions().defaults;
}
/**
* Initialize the default placement for components
* @returns {void}
* @memberof ViewManager
*/
__initializeRatsNest() {
//Step 1 generate features for all the components with some basic layout
let components = this.currentDevice.getComponents();
let xpos = 10000;
let ypos = 10000;
for (let i in components) {
let component = components[i];
let currentposition = component.getPosition();
//TODO: Refine this logic, it sucks
if (currentposition[0] === 0 && currentposition === 0) {
if (!component.placed) {
this.__generateDefaultPlacementForComponent(component, xpos * (parseInt(i) + 1), ypos * (Math.floor(parseInt(i) / 5) + 1));
}
} else {
if (!component.placed) {
this.__generateDefaultPlacementForComponent(component, currentposition[0], currentposition[1]);
}
}
}
//TODO: Step 2 generate rats nest renders for all the components
this.view.updateRatsNest();
this.view.updateComponentPortsRender();
}
/**
* Generates the default placement for components
* @param {Component} component
* @param {number} xpos Default X coordinate
* @param {number} ypos Default Y coordinate
* @returns {void}
* @memberof ViewManager
*/
__generateDefaultPlacementForComponent(component, xpos, ypos) {
let params_to_copy = component.getParams().toJSON();
params_to_copy["position"] = [xpos, ypos];
//Get default params and overwrite them with json params, this can account for inconsistencies
let newFeature = Device.makeFeature(component.getType(), "Basic", params_to_copy);
component.addFeatureID(newFeature.getID());
Registry.currentLayer.addFeature(newFeature);
//Set the component position
component.updateComponentPosition([xpos, ypos]);
}
/**
* Generates a JSON format file to export it
* @returns {void}
* @memberof ViewManager
*/
generateExportJSON() {
let json = this.currentDevice.toInterchangeV1_1();
json.customComponents = this.customComponentManager.toJSON();
return json;
}
/**
* This method attempts to load any custom components that are stored in the custom components property
* @param json
*/
loadCustomComponents(json) {
if (Object.prototype.hasOwnProperty.call(json, "customComponents")) {
this.customComponentManager.loadFromJSON(json["customComponents"]);
}
}
/**
* Activates DAFD plugin
* @param {*} params
* @returns {void}
* @memberof ViewManager
*/
activateDAFDPlugin(params = null) {
this.loadDeviceFromJSON(JSON.parse(Examples.dafdtemplate));
if (null === params) {
params = {
orificeSize: 750,
orificeLength: 200,
oilInputWidth: 800,
waterInputWidth: 900,
outputWidth: 900,
outputLength: 500,
height: 100
};
}
DAFDPlugin.fixLayout(params);
}
/**
* This is the method we need to call to fix the valvemaps
* @memberof ViewManager
*/
createValveMapFromSelection() {
//TODO: Run through the current selection and generate the valve map for every
//vavle that is in the Selection
let selection = this.tools["MouseSelectTool"].currentSelection;
let valves = [];
let connection = null;
//TODO: run though the items
for (let render_element of selection) {
//Check if render_element is associated with a VALVE/VALVE3D
let component = this.currentDevice.getComponentForFeatureID(render_element.featureID);
if (component !== null) {
console.log("Component Type:", component.getType());
let type = component.getType();
if (type === "Valve3D" || type === "Valve") {
valves.push(component);
}
}
connection = this.currentDevice.getConnectionForFeatureID(render_element.featureID);
}
//Add to the valvemap
for (let valve of valves) {
let valve_type = false;
if (valve.getType() === "Valve3D") {
valve_type = true;
}
console.log("Adding Valve: ", valve);
this.currentDevice.insertValve(valve, connection, valve_type);
}
}
}
|
import React from "react"
import { StateProvider } from "./context/StateProvider"
import reducer, { initialState } from "./reducer";
import Player from "./components/Player"
import { Helmet } from "react-helmet";
const Layout = (props) => {
return (
<StateProvider initialState={initialState} reducer={reducer}>
<Helmet>
<title>Muzik</title>
<link href="https://i.scdn.co" rel="preconnect" />
<link href="https://fonts.googleapis.com/css2?family=Ultra&display=swap" rel="stylesheet" />
<script src="init-player.js"></script>
</Helmet>
<Player {...props} />
</StateProvider>
)
}
export default Layout |
import { paint } from '@kuba/h'
import component from './component'
@paint(component)
class PageNotFound {
}
export default PageNotFound
|
'use strict';
angular.module('ttsApp')
.controller('MainCtrl', ['$scope', '$location', '$anchorScroll', function ($scope, $anchorScroll, $location) {
//DROPDOWN
$scope.dropdownLinks = [
{"title": "Youth Code Camps", "url": "/youthcode"},
{"title": "College Cram Session", "url": "/college-cram"}
];
//DATA
$scope.masks = [
{
'image': 'assets/img/step1.png',
'title': 'Connect',
'content': "We provide access to networking opportunities, educational events, cutting edge companies, and local entrepreneurs. Our supportive, non-intimidating, and collaborative community is filled with passionate, like-minded students on their way to doing great things. Along the way, you'll get the mentoring you need from local professionals in relevant fields and the Tech Talent South staff."
},
{
'image': 'assets/img/step2.png',
'title': 'Plan',
'content': "Have a great idea for the next big thing? Haven't known how to start? This is when the sketching begins. The design process never begins in front of the computer. Tech Talent South will teach you how to map out and execute a plan, taking your idea all the way from inception to launch."
},
{
'image': 'assets/img/step3.png',
'title': 'Execute',
'content': "We teach you all the languages and skills you'll need to turn your idea into a reality. From domain modeling to database management, we'll show you the back-end of web application development. And, of course, it has to look pretty. We'll show you the tricks of front-end design in order to create a great user experience."
},
{
'image': 'assets/img/step4.png',
'title': 'Launch',
'content': "Ship your MVP (minimum viable product) to the web, get feedback, refine and iterate. Get additional web application users on board, practice your pitch, and start your business...the sky is the limit!"
}
];
$scope.affiliates = [
{
'name': 'Technology Association of Georgia',
'img': 'assets/img/tag-ed-logo.jpg',
'link': 'http://www.tagonline.org/'
},
{
'name': 'Mojo Coworking',
'img': 'assets/img/mojo.png',
'link': 'http://mojocoworking.com/'
},
{
'name': 'Industry Coworking',
'img': 'assets/img/industry_charlotte.png',
'link': 'http://industrycharlotte.com/'
},
{
'name': 'AB Tech Center for Professional Studies',
'img': 'assets/img/ab-tech.png',
'link': 'http://www.abtech.edu/'
},
{
'name': 'Hands on Tech Atlanta',
'img': 'assets/img/HOT-ATL.png',
'link': 'http://www.handsonatlanta.org/HOC__Affiliate_Home_Page'
}
];
}]) |
export const emptyReducerReturnValue = {
id: "news-null",
title: undefined,
author: undefined,
url: undefined,
time: undefined,
source: "News",
};
export const getArticlePreReducerStub = {
source: {
id: "google-news",
name: "",
},
title:
"Anambra gubernatorial primary: Secondus chairs PDP Appeal Panel - Vanguard",
url: "https://news.google.com/__i/rss/rd/articles/CBMiZWh0dHBzOi8vd3d3LnZhbmd1YXJkbmdyLmNvbS8yMDIxLzA2L2FuYW1icmEtZ3ViZXJuYXRvcmlhbC1wcmltYXJ5LXNlY29uZHVzLWNoYWlycy1wZHAtYXBwZWFsLXBhbmVsLTIv0gFraHR0cHM6Ly93d3cudmFuZ3VhcmRuZ3IuY29tLzIwMjEvMDYvYW5hbWJyYS1ndWJlcm5hdG9yaWFsLXByaW1hcnktc2Vjb25kdXMtY2hhaXJzLXBkcC1hcHBlYWwtcGFuZWwtMi8_YW1wPTE?oc=5",
author: null,
publishedAt: "2021-06-29T05:16:00Z",
};
export const getArticlePostReducerStub = {
id: "news-google-news",
title:
"Anambra gubernatorial primary: Secondus chairs PDP Appeal Panel - Vanguard",
author: null,
url: "https://news.google.com/__i/rss/rd/articles/CBMiZWh0dHBzOi8vd3d3LnZhbmd1YXJkbmdyLmNvbS8yMDIxLzA2L2FuYW1icmEtZ3ViZXJuYXRvcmlhbC1wcmltYXJ5LXNlY29uZHVzLWNoYWlycy1wZHAtYXBwZWFsLXBhbmVsLTIv0gFraHR0cHM6Ly93d3cudmFuZ3VhcmRuZ3IuY29tLzIwMjEvMDYvYW5hbWJyYS1ndWJlcm5hdG9yaWFsLXByaW1hcnktc2Vjb25kdXMtY2hhaXJzLXBkcC1hcHBlYWwtcGFuZWwtMi8_YW1wPTE?oc=5",
time: "2021-06-29T05:16:00Z",
source: "News",
};
|
import React, { useState } from "react";
import classes from "./Carousel.module.css";
import { useEffect } from "react";
const Carousel = ({ imgs = [] }) => {
const [viewImg, setViewImg] = useState(0);
const [start, setStart] = useState(0);
useEffect(() => setViewImg(0), [imgs]);
const next = () => {
if (viewImg === imgs.length - 1) {
setViewImg(0);
} else setViewImg(viewImg + 1);
};
const prev = () => {
if (viewImg === 0) {
setViewImg(imgs.length - 1);
} else setViewImg(viewImg - 1);
};
const touchEndHandler = (eve) => {
const swipeLength = start - eve.changedTouches[0].clientX;
if (imgs < 1 || swipeLength ** 2 < 2000) return;
if (swipeLength < -50) prev();
if (swipeLength > 50) next();
};
const touchStartHandler = (eve) => {
setStart(eve.touches[0].clientX);
};
const imgsMap = imgs.map((img, i) => (
<img
onTouchStart={touchStartHandler}
onTouchEnd={touchEndHandler}
alt="Carousel"
src={img}
className={`${classes.img} ${i === viewImg ? classes.selectImg : ""}`}
onClick={next}
key={i}
/>
));
const gabsMap = [];
for (let i = 0; i < imgs.length; i++)
gabsMap.push(
<span
key={i}
onClick={() => setViewImg(i)}
className={`${classes.dote} ${viewImg === i && classes.select}`}
>
_
</span>
);
return (
<div className={classes.carousel}>
<div>{imgsMap}</div>
<div className={classes.dotes}>{gabsMap}</div>
</div>
);
};
export default Carousel;
|
var express = require('express');
var body_parser = require('body-parser');
var nodemailer = require('nodemailer');
var app = express();
// *Sensitive data removed.
var transporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "", // *Email
pass: "" // *Pass
}
});
var mailOptions = {
from: '', // *From
to: '', // *To
subject: '',
text: '',
}
var port = process.env.PORT || 8080;
app.use(express.static("files"));
app.use(body_parser.urlencoded({ extended: false }));
app.post('/submit', function(req, res){
mailOptions.subject = req.body.name;
mailOptions.text = [ req.body.email, req.body.message ].join('\n\n');
transporter.sendMail(mailOptions, (error, info) => {
if (error){
return console.log(error);
}
})
res.redirect("/sent.html");
});
app.listen(port);
|
import React from 'react'
import {connect} from 'react-redux'
import Notebooks from '../components/Notebooks'
const mapStateToProps = state => ({
allNotebooks: state.notebook.allNotebooks
})
export default connect(mapStateToProps)(Notebooks)
|
{
"greetings": {
"cheers": "Santé",
"hello": "Bonjour",
"bye": "Au Revoir"
},
"menu": {
"file": {
"_root": "Dossier",
"new": "Nouveau",
"open": "Ouvrir",
"save": "Sauver",
"exit": "Quitter"
},
"edit": {
"_root": "Modifier",
"cut": "Cut",
"copy": "Copie",
"paste": "Coller",
"find": "Trouver",
"replace": "Remplacer"
},
"format": {
"_root": "Format",
"bold": "Audacieux",
"italic": "Italique",
"underline": "Souligner"
}
}
} |
const Manager = require("./lib/Manager");
const Engineer = require("./lib/Engineer");
const Intern = require("./lib/Intern");
const inquirer = require("inquirer");
const path = require("path");
const fs = require("fs");
const OUTPUT_DIR = path.resolve(__dirname, "output");
const outputPath = path.join(OUTPUT_DIR, "team.html");
const render = require("./lib/htmlRenderer");
// Set Global Variables
let employeeArray = [];
let employeeID = 1;
let employeeInfo = {};
// Array of questions that node will prompt
let questions = [
{
type: "input",
message: "Employee's name?",
name: "name",
},
{
type: "input",
message: "Employee's email?",
name: "email",
},
{
// this one is important. This is where we will later use a switch statement to ask different questions.
message: "Employee role question",
name: "specificQuestion",
},
{
type: "list",
message: "Employee's role in the company?",
name: "role",
choices: ["Engineer", "Intern", "no more employees to add"],
},
];
// Function that starts inquirer
let newEmployeeQuestion = (specificQuestion, role) => {
questions[2].message = specificQuestion;
inquirer.prompt(questions).then((response) => {
employeeInfo = {};
employeeInfo.name = response.name;
employeeInfo.email = response.email;
employeeInfo.specificQuestion = response.specificQuestion;
employeeInfo.role = role;
employeeInfo.id = employeeID;
storeEmployees(employeeInfo, response.role);
});
};
// When choosing in node, using an if else statement to make sure it goes through each possible variable.
let storeEmployees = (employee, nextEmployee) => {
if (employee.role === "Manager") {
var newEmployee = new Manager(
employee.name,
employee.id,
employee.email,
employee.specificQuestion
);
} else if (employee.role === "Engineer") {
var newEmployee = new Engineer(
employee.name,
employee.id,
employee.email,
employee.specificQuestion
);
} else {
var newEmployee = new Intern(
employee.name,
employee.id,
employee.email,
employee.specificQuestion
);
}
// push the array to the new Employee variable
employeeArray.push(newEmployee);
// Add one to the ID
employeeID++;
// this is going through and picking what to say dependent on what the user chose
switch (nextEmployee) {
case "Manager":
newEmployeeQuestion("Employee's office number?", "Manager");
break;
case "Engineer":
newEmployeeQuestion("Employee's github?", "Engineer");
break;
case "Intern":
newEmployeeQuestion("What school did the employee attend?", "Intern");
break;
case "no more employees to add":
// When done inputing your data, this render method will start making the HTML
let htmlRender = render(employeeArray);
writeHTML(htmlRender);
default:
return;
}
};
// Finishing by creating the HTML file
let writeHTML = (htmlRender) => {
fs.writeFile(outputPath, htmlRender, (err) => {
if (err) {
console.log(err)
}
else {
console.log("Creating your file")
}
});
}
// Starting everything off as Manager
newEmployeeQuestion("Employee's office number? ", "Manager")
|
let data = [];
let great = [];
let bad = [];
let good = [];
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function btnEnter() {
let obj = new Object({
'Surname': document.form.surname.value,
'Итех': +document.form.one.value,
'МОДС': +document.form.two.value,
'АК': +document.form.three.value,
'СКБД': +document.form.four.value,
'КСх': +document.form.five.value,
});
data.push(obj);
}
function btnRandom(a=2, b=6) {
document.form.one.value = getRandomInt(a, b);
document.form.two.value = getRandomInt(a, b);
document.form.three.value = getRandomInt(a, b);
document.form.four.value = getRandomInt(a, b);
document.form.five.value = getRandomInt(a, b);
}
function getBestStudents() {
for (let obj of data) {
let sum = 0;
if (obj['level'] === undefined) {
for (let key in obj) {
if (Number.isInteger(obj[key])) sum += obj[key];
}
if (sum == 25) {
obj['level'] = 'great';
great.push(obj['Surname']);
}
}
}
}
function getWorstStudents() {
outer: for (let obj of data) {
if (obj['level'] === undefined) {
for (let key in obj) {
if (obj[key] === 1 || obj[key] == 2) {
obj['level'] = 'bad';
bad.push(obj['Surname']);
continue outer;
}
}
}
}
}
function getOtherStudents() {
outer: for (let obj of data) {
if (obj['level'] === undefined) {
for (let key in obj) {
if (obj[key] == 3) {
obj['level'] = 'with 3';
continue outer;
}
}
obj['level'] = 'good';
good.push(obj['Surname']);
}
}
}
function btngetResult() {
document.getElementById('output-table' ).style.display = 'table';
getBestStudents();
getWorstStudents();
getOtherStudents();
$('#great').replaceWith(`<tr id="great" class="under input" ><td>Отличники</td><td class="input">${great.length}</td><td>${great.join(', ')}</td></tr>`);
$('#good').replaceWith(`<tr id="good" class="input"><td>Хорошисты</td><td class="input">${good.length}</td><td>${good.join(', ')}</td></tr>`);
$('#bad').replaceWith(`<tr id="bad" class="input"><td>Неуспевающие</td><td class="input">${bad.length}</td><td>${bad.join(', ')}</td></tr>`);
}
console.log(String(document.location.href))
let notificen = new Notification("HELLO");
let data2 = new Date().getMonth();
console.log(data2+1);
function Person(){
this.name = "Oleg"
this.lastName = "Drozd"
}
function Student() {
this.university = "NURE"
}
Student.prototype = new Person();
console.log(new Student()); |
import { assert } from 'chai';
import {
operatorCalc
} from '../src/operator';
import { vectorArray, VectorArray } from '../src/array';
describe('standard Array test.', () => {
it('should create x y z values', () => {
const pos = vectorArray(5, 6, 7);
assert.equal(pos[0], 5);
assert.equal(pos[1], 6);
assert.equal(pos[2], 7);
});
it('should create x y z values via array', () => {
const pos = vectorArray([5, 6, 7]);
assert.equal(pos[0], 5);
assert.equal(pos[1], 6);
assert.equal(pos[2], 7);
});
it('should be calculated by assigned statement', () => {
const pos = vectorArray(5, 6);
const dir = vectorArray(3, 0);
const scale = operatorCalc(() => dir * pos);
assert.equal(scale[0], 15);
assert.equal(scale[1], 0);
});
it('should work with mixed 4d and 3d array', () => {
const pos = vectorArray(5, 6, 7, 8);
const dir = vectorArray(3, 0, 2);
const scale = operatorCalc(() => dir * pos);
assert.equal(scale[0], 15);
assert.equal(scale[1], 0);
assert.equal(scale[2], 14);
assert.equal(scale[3], 0);
});
it('calling of calc should automatically detect assigned Vector types', () => {
const pos = vectorArray(2, 2, 2);
const vec = operatorCalc(() => 2 * pos + 3);
assert.instanceOf(vec, Array);
assert.equal(vec[0], 7);
assert.equal(vec[1], 7);
assert.equal(vec[2], 7);
});
});
|
var searchData=
[
['outoffile',['outOfFile',['../classpersistencia_1_1input_1_1Input.html#a3f0fc057e91430b81f5f2c92f91b8ed7',1,'persistencia::input::Input']]],
['output',['Output',['../classpersistencia_1_1output_1_1Output.html#acbb70ea9eabb2a6d0b2d7bd2f3c9009a',1,'persistencia::output::Output']]]
];
|
// Program for Azure Resources
// Chris Joakim, Microsoft, 2019/04/04
const fs = require("fs");
const util = require("util");
const msRestAzure = require('ms-rest-azure');
const resourceManagement = require("azure-arm-resource");
// Application code is in the lib/ directory
const App = require('./lib/app.js').App;
const Resource = require('./lib/resource.js').Resource;
const Requirement = require('./lib/requirement.js').Requirement;
// main() entry-point logic
if (process.argv.length < 3) {
console.log("Invalid program args; please specify a runtime function as follows:");
console.log("node main.js verify_application designs/app1.json data/resource-list.json");
console.log("node main.js list_subscription_resources");
console.log("");
process.exit();
}
else {
cli_function = process.argv[2];
switch(cli_function) {
case 'verify_application':
var app_file = process.argv[3];
var res_file = process.argv[4];
verify_application(app_file, res_file);
break;
case 'list_subscription_resources':
list_subscription_resources();
break;
default:
console.log("error, unknown cli function: " + cli_function);
}
}
// top level functions called from main
function verify_application(app_file, res_file) {
console.log('verify_application: ' + app_file + ' from resources ' + res_file);
var app = new App(app_file, res_file);
app.verify();
}
function list_subscription_resources() {
var subscr_id = process.env.AZURE_SUBSCRIPTION_ID;
console.log("list_subscription_resources; subscription: " + subscr_id);
// Interactive Login at https://microsoft.com/devicelogin with given code
msRestAzure.interactiveLogin(function(err, credentials) {
console.log('credentials: ' + credentials);
var client = new resourceManagement.ResourceManagementClient(credentials, subscr_id);
client.resources.list(function(err, result) {
if (err) console.log(err);
var jstr = JSON.stringify(result, null, 2);
console.log(jstr);
var outfile = 'tmp/subscr_' + subscr_id + '.json';
fs.writeFileSync(outfile, jstr);
console.log('file written: ' + outfile);
});
});
}
function list_resource_group_resources(rg) {
var subscr_id = process.env.AZURE_SUBSCRIPTION_ID;
console.log("list_resource_group_resources; subscription: " + subscr_id + " rg: " + rg);
msRestAzure.interactiveLogin().then((credentials) => {
let client = new SearchManagement(credentials, subscr_id);
return client.services.listByResourceGroup(rg);
}).then((services) => {
console.log('List of services:');
console.dir(services, {depth: null, colors: true});
}).catch((err) => {
console.log('An error ocurred');
console.dir(err, {depth: null, colors: true});
});
}
|
import React, { Fragment } from "react";
import { Row, Col, Form, Input, Button, Divider } from "antd";
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import "../assets/form.css";
import useAuth from "../auth/useAuth";
import { useHistory } from "react-router-dom";
export const LoginForm = () => {
const { login } = useAuth();
const history = useHistory();
const onFinish = (user) => {
console.log("Success:", user);
login(user)
};
const onFinishFailed = (errorInfo) => {
console.log("Failed:", errorInfo);
};
const handleRedirect = () => {
history.push('/register')
}
return (
<Fragment>
<Row className="register">
<Col xs={{ span: 24, order: 2 }} sm={{ span: 16, order: 1 }} md={{ span: 16, order: 1 }} lg={{ span: 14, order: 1 }}>
<img className="logo" src="https://res.cloudinary.com/dutj1bbos/image/upload/v1626812972/b5af65dd9465486da0042f6d44dbc3f5_jz0v5f.png" alt="img"></img>
<div className="container-form">
<Form className="form" name="basic"
labelCol={{ span: 12, }}
wrapperCol={{ span: 24, }}
layout={"vertical"}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<h2 className="title-form">Sign in to your Linkvauls account</h2>
<Form.Item name="Email"
rules={[
{
required: true,
message: "Please input your Email!",
},
]}
>
<Input placeholder="Email" prefix={<UserOutlined className="site-form-item-icon" />} size="large" />
</Form.Item>
<Form.Item name="password"
rules={[
{
required: true,
message: "Please input your password!",
},
]}
>
<Input.Password placeholder="Password" prefix={<LockOutlined className="site-form-item-icon" />} size="large" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" size="large">
Sign In
</Button>
</Form.Item>
<Divider><p onClick={handleRedirect}>Register</p></Divider>
</Form>
</div>
</Col>
<Col xs={{ span: 24, order: 1 }} sm={{ span: 8, order: 2 }} md={{ span: 8, order: 2 }} lg={{ span: 10, order: 2 }}>
<img className="img" src="https://res.cloudinary.com/dutj1bbos/image/upload/v1626813243/diego-ph-fIq0tET6llw-unsplash_urevgj.jpg" alt="img"></img>
</Col>
</Row>
</Fragment>
);
};
|
/*
* @lc app=leetcode.cn id=559 lang=javascript
*
* [559] N 叉树的最大深度
*/
// @lc code=start
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number}
*/
var maxDepth = function(root) {
let stack = [];
if (root !== null) {
stack.push(root);
}
let res = 0;
while (stack.length > 0) {
let len = stack.length;
for (let i = 0; i < len; i++) {
const node = stack.shift();
for (let i = 0; i < node.children.length; i++) {
stack.push(node.children[i]);
}
}
res++;
}
return res;
};
// @lc code=end
|
// others/my.js
var app = getApp()
Page({
data: {
inputShowed: false,
inputVal: "",
xinList:[],
},
onLoad: function(options) {
this.setData({
search: this.search.bind(this)
})
this.setData({
xinList: app.globalData.star,
});
console.log(this.data.xinList)
console.log(app.globalData)
},
search: function (value) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve([{ text: '搜索结果', value: 1 }, { text: '搜索结果2', value: 2 }])
}, 200)
})
},
selectResult: function (e) {
console.log('select result', e.detail)
},
slideButtonTap(e) {
var that = this
console.log('slide button tap', e)
if(e.detail.index == 1){
wx.showModal({
title: '提示',
content: '确认使这颗星星坠落吗?',
success(res) {
if (res.confirm) {
console.log('用户点击确定')
app.globalData.nums = app.globalData.nums - 1
const db = wx.cloud.database()
app.globalData.star.splice(e.detail.data, 1)
console.log(app.globalData)
db.collection('pumpkin').doc(app.globalData._id).update({
data: {
nums: app.globalData.nums,
star: app.globalData.star
},
success: res => {
console.log('[数据库] [更新记录] 成功:', res)
wx.showToast({
title: '删除成功',
})
},
fail: err => {
icon: 'none',
console.error('[数据库] [更新记录] 失败:', err)
}
})
that.onLoad()
} else if (res.cancel) {
console.log('用户点击取消')
}
}
})
}
},
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.