text
stringlengths 7
3.69M
|
|---|
// Evolutility-UI-React :: /views/one/Edit.js
// View to add or update one record at a time.
// https://github.com/evoluteur/evolutility-ui-react
// (c) 2017 Olivier Giulieri
import React from 'react'
import { withRouter } from 'react-router'
import Modal from 'react-modal'
import {i18n_actions, i18n_validation, i18n_errors} from '../../i18n/i18n'
import dico from '../../utils/dico'
import validation from '../../utils/validation'
import Alert from '../../widgets/Alert'
import oneRead from './one-read'
import oneUpsert from './one-upsert'
import Field from '../../widgets/Field'
import Panel from '../../widgets/Panel'
import List from '../many/List'
export default withRouter(React.createClass({
viewId: 'edit',
propTypes: {
params: React.PropTypes.shape({
entity: React.PropTypes.string.isRequired,
id: React.PropTypes.string
}).isRequired
},
mixins: [oneRead(), oneUpsert()],
getDataDelta: function() {
return this.delta || null
},
clickSave(evt) {
const fields = this.model.fields, v = this.validate(fields, this.state.data);
if (v.valid) {
this.upsertOne()
}
else {
//alert(v.messages.join('\n'))
this.setState({
invalid: !v.valid
});
}
},
fieldChange(evt) {
const fid = evt.target.id, newData = JSON.parse(JSON.stringify(this.state.data||{}));
let v = evt.target.value;
if (evt.target.type === 'checkbox') {
v = evt.target.checked;
}
newData[fid] = v;
this.setDeltaField(fid, v);
this.setState({data: newData});
},
/*
fieldClick(i, props) {
//debugger
},
fieldLeave(i, props) {
//debugger
},
*/
setDeltaField(fid, value) {
if (!this.delta) {
this.delta = {};
}
this.delta[fid] = value;
this._dirty = true;
},
isDirty() {
return this._dirty;
},
render() {
const urlParts = window.location.pathname.split('/'),
isNew = urlParts.length > 2 ? urlParts[3] == '0' : false, {id = 0, entity = null} = this.props.params,
ep = '/' + entity + '/',
m = this.model,
data = this.state.data || {},
cbs = {
//click: this.fieldClick,
change: this.fieldChange,
//leave: this.fieldLeave,
dropFile: this.uploadFileOne
}, title = dico.dataTitle(m, data, isNew)
const fnField = (f) => {
if ((f.type === 'lov' || f.type === 'list') && !f.list) {
// - fetch list values
this.getLOV(f.id);
}
return (
<Field key={f.id} ref={f.id} meta={f} value={data[f.id]} data={data} callbacks={cbs} entity={entity} />
)
};
this.isNew = isNew;
if (!m) {
return <Alert title="Error" message={i18n_errors.badEntity.replace('{0}', entity)} />
}
else {
return (
<div className="evolutility">
<h2 className="evo-page-title">{title}</h2>
<div className="evo-one-edit">
{this.state.error ? (<Alert title="Error" message={this.state.error.message} />)
:
(<div className="evol-pnls">
{(m && m.groups) ? (
m.groups.map(function(g, idx) {
const groupFields = dico.fieldId2Field(g.fields, m.fieldsH);
return (
<Panel key={g.id || ('g' + idx)} title = {g.label || gtitle || ''} width = {g.width}>
<div className="evol-fset">
{groupFields.map(fnField)}
</div>
</Panel>
)
})
) : (
<Panel title={title} key="pAllFields">
<div className="evol-fset">
{m.fields.map(fnField)}
</div>
</Panel>
)}
{m.collecs ? (
m.collecs.map((c, idx) => {
return (
<Panel title={c.title} key={'collec_' + c.id}>
<List key={'collec' + idx}
params={this.props.params}
paramsCollec={c}
style={{width: '100%'}}
location={this.props.location}
/>
</Panel>
)
})
) : null}
<Panel key="formButtons">
<div className="evol-buttons">
<button className="btn btn-info" onClick={this.clickSave}><i className="glyphicon glyphicon-ok"></i> {i18n_actions.save}</button>
<button className="btn btn-default" onClick={this.navigateBack}><i className="glyphicon glyphicon-remove"></i> {i18n_actions.cancel}</button>
<span className="">{this.state.invalid ? i18n_validation.incomplete : null}</span>
{this.state.error ? i18n_validation.incomplete : null}
</div>
</Panel>
</div>
)}
</div>
</div>
)
}
},
validate: function (fields, data) {
let messages = [], invalids = {}, cMsg;
fields.forEach((f) => {
cMsg = validation.validateField(f, data[f.id]);
if (cMsg) {
messages.push(cMsg);
invalids[f.id] = true;
this.refs[f.id].setState({
invalid: true,
message: cMsg
});
}
else if (this.refs[f.id].state.invalid === true) {
this.refs[f.id].setState({
invalid: false,
message: null
});
}
});
return {
valid: messages.length < 1,
messages: messages,
invalids: invalids
};
},
clearValidation() {
this.model.fields.forEach((f) => {
this.refs[f.id].setState({
invalid: false,
message: null
});
});
}
}))
|
import React, { Component, PropTypes } from 'react'
import { Field, reduxForm } from 'redux-form'
import { connect } from 'react-redux'
import { createCustomer, customerStatusReset } from '../../actions'
require('../../styles/customers/form.scss')
class CustomerForm extends Component {
constructor (props) {
super(props)
this.handleFormSubmit = this.handleFormSubmit.bind(this)
}
componentWillMount () {
this.props.customerStatusReset()
}
handleFormSubmit (formProps) {
this.props.onFormSubmit(formProps)
}
render () {
return (
<form
className='photo-invoice-form'
onSubmit={this.props.handleSubmit(this.handleFormSubmit)}>
<fieldset>
<label>Customer/Company Name<sup>*</sup></label>
<Field className='text-input' name='customerName' component='input' type='input' />
</fieldset>
<fieldset>
<label>Email</label>
<Field className='text-input' name='email' component='input' type='input' />
</fieldset>
<fieldset>
<label>First Name of Contact</label>
<Field className='text-input' name='contactFirstName' component='input' type='input' />
</fieldset>
<fieldset>
<label>Last Name of Contact</label>
<Field className='text-input' name='contactLastName' component='input' type='input' />
</fieldset>
{
this.props.saveStatus === 'loading'
? <button className='btn-primary clearfix save-customer' action='submit'><span className='fa fa-spin fa-spinner' /></button>
: <button className='btn-primary clearfix save-customer' action='submit'>Save Customer</button>
}
</form>
)
}
}
const mapStateToProps = state => {
return {
initialValues: state.customers.customer,
saveStatus: state.customers.saveStatus
}
}
const form = reduxForm({
form: 'customerForm',
enableReinitialize: true
})
CustomerForm.propTypes = {
// component declaration
onFormSubmit: PropTypes.func,
onCreateSuccess: PropTypes.func,
// redux form
handleSubmit: PropTypes.func,
// mapStateToProps
saveStatus: PropTypes.string,
// action creators
createCustomer: PropTypes.func,
customerStatusReset: PropTypes.func
}
export default connect(mapStateToProps, { createCustomer, customerStatusReset })(form(CustomerForm))
|
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mongoose = require('mongoose');
Error.stackTraceLimit = Infinity;
mongoose.connect('mongodb://localhost/example');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(callback) {
var ballPosition = { lat: -37.814278, lng: 144.963257 }; /*(Elizabeth and Bourke, roughly centre of field)*/
var goalOne = {lat: -37.817219, lng: 144.952797 }; /*(Top of Southern Cross Station Staircase, Western goal)*/
var goalTwo = {lat: -37.811226, lng: 144.973603 }; /*(Top of Parliament House Staircase, Eastern goal)*/
var fieldOfPlay = [
{lat: -37.813226, lng: 144.951359}, /*(La Trobe and Spencer, Northwest corner)*/
{lat: -37.807569, lng: 144.970618}, /*(La Trobe and Victoria, Northeast corner 1)*/
{lat: -37.807861, lng: 144.971444}, /*(Spring and Victoria, Northeast corner 2)*/
{lat: -37.815274, lng: 144.974877}, /*(Spring and Flinders, Southeast corner)*/
{lat: -37.820973, lng: 144.955040} /*(Spencer and Flinders, Southwest corner)*/
];
var idIncrement;
var playerSchema = mongoose.schema({
hasPossession: Boolean,
latitude: Number,
longitude: Number,
name: String
})
var Player = mongoose.model('Player', playerSchema)
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
var thisPlayer = new Player({
hasPossession: false,
latitude: 0,
longitude: 0,
})
socket.emit('player id created', thisPlayer.get('_id'));
socket.on('player position update', function(lat, lng){
Tank.update({ latitude: lat }, { longitude: lng }, callback);
});
socket.on('disconnect', function() {
// TODO remove this player from database
})
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
// send list of all users and their locations to every connected user, every second
setInterval(function() {
Player.find(function(err, player_data) {
io.emit('all players update', {players: player_data})
})
}, 1000);
});
|
const {FastCommentsCoreExampleUsage} = require('./../example/FastCommentsIntegrationCoreExample');
(async function testStepTwoSetTenantId() {
const myApp = new FastCommentsCoreExampleUsage();
// This promise resolves once the app says setup is done, and the user has successfully confirmed the integration (by keeping the above page open).
await myApp.waitForTenantId();
process.exit(0);
})().catch((e) => {
console.error(e);
process.exit(1);
});
|
import map from './map';
export const actionTypes = {
USER_REFRESH_MAP: 'USER_REFRESH_MAP'
};
export const actions = {
...map.actions,
userRefreshMap() {
return { type: actionTypes.USER_REFRESH_MAP };
}
};
|
// Nonon.pokemon/base.js
//
//$ PackConfig
{ "sprites" : [ "base.png" ] }
//$!
module.exports = {
id: "Nonon.pokemon",
sprite: "base.png",
sprite_format: "hg_pokecol-32",
name: "Nonon",
infodex: "game.black.pokemon.nonon",
sprite_creator: "Carlotta4th",
};
|
var ChatScreen = require("./ChatScreen");
function ChatPlugin(testbed, plugin) {
var self = this;
this.testbed = testbed;
this.plugin = plugin;
this.plugins = {};
this.plugin.on("unloaded", function() {
self.onSelfUnloaded();
});
this.plugin.getControl().on("valuesChanged", function() {
self.onControlValuesChanged();
});
this.onControlValuesChanged();
this.screen = new ChatScreen(testbed);
}
/**
* Handler for own unload.
*/
ChatPlugin.prototype.onSelfUnloaded = function() {
};
/**
* Handler for changed control values.
*/
ChatPlugin.prototype.onControlValuesChanged = function() {
};
module.exports = ChatPlugin;
|
/**
* @module edition.collection.js
* @main Collection
* @class Collection
*/
window.Collection = window.Collection || {}
$.extend(Collection,{
})
/* ---------------------------------------------------------------------
PROPRIÉTÉS COMPLEXES
---------------------------------------------------------------------*/
Object.defineProperties(Collection,{
/**
* Destruction de la collection courante
* Notes
* -----
* * Par mesure de prudence, il n'est possible de détruire que la collection
* test, pas la "current".
* * L'application est rechargée en fin de processus pour tout ré-initialiser.
*
* @method destroy
*
*/
"destroy":{
get:function(){
if(!MODE_TEST) return F.error("On ne peut détruire la collection qu'en mode test.")
Ajax.send({script:'collection/destroy',collection:'test'},
$.proxy(this.after_destroy, this))
}
},
"after_destroy":{
value:function(rajax){
if(rajax.ok)
{
// On attend une seconde avant de recharger
setTimeout(function(){location.reload()}, 1000)
}
else F.error(rajax.message)
}
}
})
|
import {
ApolloClient,
createHttpLink,
InMemoryCache,
} from "@apollo/client/core";
import { E_SERVER_ERROR_CONNECTING } from "@common/string";
const SERVER = process.env.VUE_APP_SERVER_URL || "http://localhost:4000";
/* Config apolloClient */
export const apolloClient = new ApolloClient({
link: createHttpLink({ uri: `${SERVER}/graphql` }),
cache: new InMemoryCache(),
defaultOptions: {
query: { fetchPolicy: "no-cache", errorPolicy: "all" },
watchQuery: { fetchPolicy: "no-cache", errorPolicy: "ignore" },
},
});
export const onError = (err) => {
console.log(E_SERVER_ERROR_CONNECTING);
if (process.env.NODE_ENV !== "development") return;
// server error
console.error(`Server${err}`);
// graphql error
if (!err.networkError) return;
const error = err.networkError.result.errors[0];
console.error(`GraphQLError: ${error.message}`);
};
export const executeQuery = (query, variables = {}) => {
return apolloClient
.query({ query, variables })
.then((res) => res.data)
.catch((err) => onError(err));
};
export const executeMutation = (mutation, variables = {}) => {
return apolloClient
.mutate({ mutation, variables })
.then((res) => res.data)
.catch((err) => onError(err));
};
|
alert("selamat datang");
var lagi = true;
while (lagi === true) {
const nama = prompt('masukkan nama anda')
alert('hallo '+nama)
lagi = confirm("mau coba lagi?")
}
alert("terimakasih telah menggunakan ")
// const nilai = [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8];
// console.log(nilai[1].length);
|
var scene = new THREE.Scene();
var aspect = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
var controls = new THREE.OrbitControls(camera);
var axis = new THREE.AxisHelper(1000);
var light = new THREE.DirectionalLight(0xb4e7f2, 1.5);
light.position.set(1,1,1);
light.target.position.set(0,0,0);
scene.add(axis);
scene.add(light);
scene.add(light.target);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
camera.position.set(100, 50, 200);
var loader = new THREE.FontLoader();
loader.load('helvetiker_regular.typeface.json', function(font){
var textGeometry = new THREE.TextGeometry("Hello Three.js!", {
font: font,
size: 20,
height: 5,
curveSegments: 12
});
var materials = [
new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, overdraw: 0.5 } ),
new THREE.MeshBasicMaterial( { color: 0x000000, overdraw: 0.5 } )
];
var textMesh = new THREE.Mesh(textGeometry, materials);
scene.add(textMesh);
});
var render = function () {
requestAnimationFrame(render);
controls.update();
renderer.setClearColor(0xaabbcc, 1.0);
renderer.render(scene, camera);
};
render();
|
var vmInfoTemplate = require("./vm-info");
module.exports = function(vmInfos){
var infos = "";
vmInfos.map((info) => {
infos += vmItem(vmInfoTemplate(info));
});
return `<ul>${infos}</ul>`
}
function vmItem(content){
return `<li class="box">${content}</li>`
}
|
var restify = require('restify');
var http = require("http"),
url = require("url"),
path = require("path"),
pug = require("pug"),
fs = require('fs');
var mysql = require('mysql');
var pool = mysql.createPool({
host: 'localhost',
port: 3306,
user: 'root',
password: 'qwerty',
database: 'todos'
});
var port = process.env.port || 1337;
var homepage = pug.compileFile(path.join(__dirname, 'index.pug'));
var server = restify.createServer({
name: 'myApp'
});
server.use(restify.bodyParser({ mapParams: true }));
server.use((req, res, next) => {
if (req.body) {
req.body = JSON.parse(req.body || '{}')
}
next();
});
server.use(function(req, res, next) {
console.log(req.method + ' ' + req.url);
next();
})
server.get('/', function (req, res) {
pool.getConnection(function (err, connection) {
connection.query('SELECT * FROM items', function (err, rows) {
if (err) console.log(err);
res.end(homepage({todos: rows}));
})
connection.release();
})
})
server.post('/addItem', function (req, res) {
pool.getConnection(function (err, connection) {
connection.query(`INSERT INTO items (name, description, completed) VALUES (
${pool.escape(req.body.name)},
${pool.escape(req.body.description)},
false
)`, function (err) {
if(err) {
console.log(err.stack);
}
connection.query('SELECT * FROM items', function (err, rows) {
res.end(JSON.stringify(rows));
connection.release();
})
})
})
})
server.put('/update/:itemID', function (req, res) {
pool.getConnection(function (err, connection) {
let updates = [];
if(req.body.name) {
updates.push('name=' + pool.escape(req.body.name));
}
if(req.body.description) {
updates.push('description=' + pool.escape(req.body.description));
}
connection.query(`UPDATE items SET ${updates.join(',')} WHERE id=${pool.escape(req.params.itemID)}`, function (err) {
if(err) {
console.log(err.stack);
}
connection.query('SELECT * FROM items', function (err, rows) {
res.end(JSON.stringify(rows));
connection.release();
})
})
})
})
server.del('/delete/:itemID', function (req, res) {
pool.getConnection(function (err, connection) {
connection.query(`DELETE FROM items WHERE id=${pool.escape(req.params.itemID)}`, function (err) {
if(err) {
console.log(err.stack);
}
connection.query('SELECT * FROM items', function (err, rows) {
res.end(JSON.stringify(rows));
connection.release();
})
})
})
})
server.listen(port, function () {
console.log('server running on port ' + port);
});
|
import React from "react";
import { FcCheckmark } from "react-icons/fc";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";
import { InviteTable } from "../components/tables/InviteTable";
const Congurational = (props) => {
let code = props.location.state.code
// let code ="12kl"
return (
<div className="success-box">
<div className="success-icon">
<FcCheckmark />
</div>
<div className="h2 three">Congratulations!</div>
<div>
<p>
Your game has been created. Your game code <span style={{color:"#ff8252"}}> {code}</span> ,Let's invite your friends to play together.
</p>
</div>
<div>
<InviteTable/>
</div>
<div>
<Button
as={Link}
to="/"
block
variant="three"
className="rounded-pill w-64 py-3 d-flex justify-content-center align-items-center text-capitalize"
>
<span>Back to Dashboard</span>
</Button>
</div>
</div>
);
};
export default Congurational;
|
const Bar = require('../models/Bar')
const Attendee = require('../models/Attendee')
class YelpConvertor {
createResponseObj(data, user) {
let responseObj = data.businesses.map( el => {
return {
name: el.name,
barId: el.id,
imgUrl: el.image_url,
counter: 0,
isGoing: false
}
})
responseObj = responseObj.map( el => {
let counter = 0
let isGoing = false
let currentBar;
return Bar.findOne({ barId: el.barId })
.then( bar => {
currentBar = bar
// only lookup attendance if there's already an entry for that bar
if (currentBar)
return Attendee.find({ bar: currentBar._id })
return null
})
.then( attendees => {
counter = attendees ? attendees.length : 0
// only query wether user attends bar if user is logged in
if (attendees && user)
return Attendee.findOne({ bar: currentBar._id, user: user._id })
return null
})
.then( attendee => {
isGoing = attendee ? true : false
el.counter = counter
el.isGoing = isGoing
return el
})
.catch( err => console.log('error querying data for responseObj:', err))
})
return Promise.all(responseObj)
}
createBarInfoObject(data) {
let responseObj = {
name: data.name,
imgUrl: data.image_url,
location: {
street: data.location.address1,
zipCode: data.location.zip_code,
city: data.location.city,
},
phone: data.phone,
attendees: []
}
return Bar.findOne({ barId: data.id })
.then( bar => {
if (!bar)
return null
return Attendee.find({ bar: bar._id })
.populate('user')
})
.then( attendees => {
if (!attendees || attendees.length === 0)
return responseObj
responseObj.attendees = attendees.map( el => {
let name = el.user.twitter.username || el.user.facebook.username
let imgUrl = el.user.twitter.profilePic || el.user.facebook.profilePic
return {
name,
imgUrl
}
})
return responseObj
})
.catch( err => console.log(err))
}
}
module.exports = YelpConvertor
|
const Client = require('./models/Client');
const Provider = require('./models/Provider');
const models = {
Client: Client.model,
Provider: Provider.model
};
const schemas = {
Client: Client.schema,
Provider: Provider.schema
};
module.exports = {models, schemas};
|
const Users = require('./users');
const Todos = require('./todos');
const Journal = require('./journal');
const Tags = require('./tags');
const Lists = require('./lists');
module.exports = {
Users,
Todos,
Journal,
Tags,
Lists
}
|
const strings = `jplenqtlagxhivmwmscfukzodp
jbrehqtlagxhivmeyscfuvzodp
jbreaqtlagxzivmwysofukzodp
jxrgnqtlagxhivmwyscfukwodp
jbrenqtwagjhivmwysxfukzodp
jbrenqplagxhivmwyscfuazoip
jbrenqtlagxhivzwyscfldzodp
jbrefqtlagxhizmwyfcfukzodp
jbrenqtlagxhevmwfsafukzodp
jbrunqtlagxrivmsyscfukzodp
jbrenqtlaguhivmwyhlfukzodp
jbrcnstsagxhivmwyscfukzodp
jbrenqtlagozivmwyscbukzodp
jbrenqwlagxhivswysrfukzodp
jbrenstlagxhuvmiyscfukzodp
jbranqtlhgxhivmwysnfukzodp
jbrenqtvagxhinmxyscfukzodp
jbrenqtlagdhivmwyscfukxody
jbrenqtlagelavmwyscfukzodp
jbrenqtlagxhtvmwyhcfukzbdp
jbrenqwlagxhivmwyscfutzopp
jbrenqtlavxhibmtyscfukzodp
jbronqtlagxnivmwyscfuzzodp
jbredqtlagxhppmwyscfukzodp
jbrcnqtlogxhivmwysxfukzodp
jbremqtlagehivswyscfukzodp
jbrenqolagxhivmcyscfukzokp
jbrehqtlacxhgvmwyscfukzodp
fbrlnqtlagxhivmwyscbukzodp
zbrfnqtlagxhivrwyscfukzodp
jbregqtlagxnivmwyscfhkzodp
jbrenqtllgxnivmwystfukzodp
jurenqtlagxhivmwyscfulzoup
jbrenitdagxhivmwyxcfukzodp
jbrenqtlagxqivmwyscvuszodp
jbqenqwlagxhivmwyscfckzodp
jbrenqtlagxhivmwxscqupzodp
jbrenqtlagxhivmwysciuqiodp
jbrjnjtlagxhivmwyscfukzode
jbrenqtlagxhuvmwqscfukzods
jbrenqtlagxhuvmuyscfukzudp
ibrenqtlagxhivmwyscfuktokp
jbsenqtlagxhivcwyscfuksodp
jbrfnntlagxhivmwnscfukzodp
jzrenqulagxhivmwyscfukzodx
jbrenqtqygxhivmwyscfukzwdp
jbrenqtlagxfixmwyscfukzcdp
jbrenqaoagxhivmwyshfukzodp
jbrenqtlazxhivmworcfukzodp
jbrenqtlagxhicowyscfukrodp
jbrqnqtlagxhivzwyzcfukzodp
jbrenqtlalxhuvxwyscfukzodp
jbrenqtlqgxhhviwyscfukzodp
jbrenqtuggxhivmoyscfukzodp
jbrenqtlagxpivmwyscfukkodw
zbrenqhlagxhivmwyscdukzodp
jbrenutlagxxivmwyscfukzoqp
obrenqtlagxhivmwxscfuszodp
jbrenqtlagxhlvmwyscfuixodp
rbrenqtlagdhixmwyscfukzodp
jbrenqtlagxhivmwescfyszodp
jbrfnqtlagxhivmwyscaukzhdp
jbrenqtiagxhivmbyscfuxzodp
cbrrnqtuagxhivmwyscfukzodp
jbkenqtlagxhigmwysufukzodp
jbjewqtlagxhivmwyscfuqzodp
jbrznqtlagxvivmwyscfukzovp
jbrenttlacxhivmwyscfhkzodp
jblenqtlagxhivmwylcfukaodp
jbrenqtlagxhivmqysiftkzodp
jbrenqtlagwhikmwyscfukqodp
jbrenqtlegxhivmwvsckukzodp
jbrenqwzagxhiamwyscfukzodp
jbrenqtlagxhivcwyscfgkzodc
jbrenqtlagxxhvmwxscfukzodp
jbrenqtlngxhivmwyscfukoowp
jbreomtlagxhivmwpscfukzodp
jfrenqtlagxhivmwyscnumzodp
jbrenqtlagphipmwyscfukfodp
jvrenqtlagxhivmwyscfmkzodw
jbrenqtlaxxoiemwyscfukzodp
jbrenqtlagxhivmwyscemkzpdp
jbrenyjldgxhivmwyscfukzodp
jbrenqtlagxhivfvyspfukzodp
kbrenctlakxhivmwyscfukzodp
jbrmhqtlagxhivmwyscfuizodp
jbjenqtlagxlivmbyscfukzodp
jbrenqtlaaxhivmmyshfukzodp
jbronqtlagxhirmvyscfukzodp
jbcrnqtlagxwivmwyscfukzodp
jxrenszlagxhivmwyscfukzodp
jbpenqtlagxhivmwyscfukkody
jbrewqtlawxhivmwyscfukzhdp
jbrenqylagxhivmwlxcfukzodp
jbrenqtlagxxivtwywcfukzodp
jbrenqtlagxhcvgayscfukzodp
jbrenitlagxhivmwiscfukzohp
jbrenutlagxhivmwyscbukvodp
nbrenqtlagxhivmwysnfujzodp
jbrenqtlagxhivmwyqcfupzoop
jbrenqtrarxhijmwyscfukzodp
jbrenqtlagxhivmwysdfukzovy
jbrrnqtlagxhivmwyvcfukzocp
jbrenqtlagxhivmwyscfuvzzhp
jbhenitlagxhivmwysufukzodp
jbrenqtlagxhivmwyscfuwzoqx
kbrenqtlagxhivmwysqfdkzodp
jbrenqtlagxhivmwyxmfukzodx
jbcenatlagxxivmwyscfukzodp
jbrenhtlagvhdvmwyscfukzodp
jxrenqtlafxhivfwyscfukzodp
jbreaztlpgxhivmwyscfukzodp
tqrenqtlagxfivmwyscfukzodp
jbrenqgllgxhwvmwyscfukzodp
jbrejjtlagxhivmgyscfukzodp
jbrenqtlagxhivmwyscvukzoqv
jbrvnqtlagxsibmwyscfukzodp
jbrenqttagxhuvmwyscfukvodp
jbrenqteagxhivmwcscfukqodp
jbrenqtsabxhivmwyspfukzodp
jbbenqtlagxhivmwyscjukztdp
jnrenqtlagxhiimwydcfukzodp
jbrenqtlagxhfvmwyscxukzodu
jbrenqtluyxhiomwyscfukzodp
jbrenqvlagxhivmwyscuukzolp
ebrenqtlagxnivmwysrfukzodp
jbreeqtlatxhigmwyscfukzodp
jbrenqtvxgxhivmwyscfukzedp
jbrmnqtlagxhivmwywcfuklodp
jbreeqtvagxhivmwyscfukzody
jbrenptlagxhivmxyscfumzodp
jbrenqtlagxhivmwysgfukzfsp
jurenqtlagjhivmwkscfukzodp
jbrenntlagxhivmwtscffkzodp
jbrenqglagxhivmwyocfokzodp
wbrenqtlagxhivmwhscfukiodp
jbrenqtligxhivmqascfukzodp
jbrenqtlagxhivmwxscfukpojp
jurenqtlagxhivmmyscfbkzodp
jbrenqtmagxhivmwyscfrbzodp
jcrenqtlagxhivmwysefukzodm
jbrenqtlagxhicmwywcfukzodl
jbvanqtlagfhivmwyscfukzodp
jbmenqjlagxhivmwyscfdkzodp
jbrenqtlagohivvwysctukzodp
jbrenqtdagxdivmwyscfckzodp
kbrefqtlagxhivmwyscfuazodp
jbrwnqtoagxhivmwyswfukzodp
jjhenqtlagxhivmwyscfukzorp
jbgsnqtlagxhivkwyscfukzodp
jbrynqtlagxhivmsyspfukzodp
jbrenftlmkxhivmwyscfukzodp
nbrenqtxagxhmvmwyscfukzodp
jbrunqtlagxhijmwysmfukzodp
jbrenqtlagmaivmwyscfukzowp
jbrerqtlagxhihmwyscfukzudp
jbrenqtlagahivmwysckukzokp
kbrenqtlagxhirmwyscfupzodp
jbrrnqtlagxhivmwyecfukzodz
jbrenqtlavxhivmwyscfusiodp
jnrenqtlagxhivmwyhcfukzodw
jbretqtlagfhivmwyscfukzrdp
jbreoqtnagxhivmwyscfukzopp
jbrenbtllgxhivmwsscfukzodp
jbrenqtlmgxhivmwyscfuwzedp
jbnenqtlagxhivbwyscfukzokp
jbrenqslagxhivmvyscfukzndp
jbrenqtlagxzivmwuscfukztdp
gbrenqtlagxhyvmwyscfukjodp
jbrenqteagxhivmwyscfuszedp
jbrenqtlaglhivmwysafukkodp
jbrenqtlagxhcvmwascfukzogp
jbrenqtlagxhsvmkcscfukzodp
jbrenqslbgxhivmwyscfufzodp
cbrenqtlagxhivkwtscfukzodp
jbrenqtltgxhivmzyscfukzodj
jbrgnqtlagihivmwyycfukzodp
vbrenqauagxhivmwyscfukzodp
jbrqnqtlagjhivmwyscfqkzodp
jbrenqtlakxhivmwyscfukvobp
jcrenqelagxhivmwtscfukzodp
jbrrnqtlagxhlvmwyscfukzodw
jbrenqtlagxhivmwkscaumzodp
jbrenqdlagxhivmiescfukzodp
jhrenqtlagxhqvmwyscmukzodp
jbrenqtlaghhivmwyscfukkoyp
jowenqtlagxyivmwyscfukzodp
jbrenitaagxhivmwyscfqkzodp
jbrenqtlagxhivmwyscfnkbudp
jbyenqtlagxhivmiyscfukzhdp
jbrenitlagxhibjwyscfukzodp
jbrenqtlavxhjvmwpscfukzodp
jbrenqyaagxhivmwyscflkzodp
jbrenqylagxhivmwyicfupzodp
jbrenqtlagxmevmwylcfukzodp
lbrenqtlagxhiqmwyscfikzodp
jbrenqtnarxhivmwyscfmkzodp
jbrenqtlamxhivmwyscfnkzorp
jbbenqtlavxhivmwyscjukztdp
jbrenqtlagxhivmwyscfnliodp
jbwenetlagxhivmwyscfukzodt
jbrenatlagxhivmwysmfujzodp
jbrsnstlagxhivmwyscfukgodp
jbwvnitlagxhivmwyscfukzodp
jbrenqtbagxhkvmwypcfukzodp
jbrlnqtlafxhivmwyscfukdodp
jbrenztlanxhivmwyscjukzodp
jbrepqtlagxhivmwudcfukzodp
jbrenqtlagxiivmwdscfskzodp
jbrdjqtlagxhivmwyschukzodp
jbrenqtoaguhivmwyccfukzodp
jdrexqjlagxhivmwyscfukzodp
jbrenqtlagxhovmwysckukaodp
pbrfnqblagxhivmwyscfukzodp
jbrenqtlagxrivgiyscfukzodp
jbrelqtgagxhivmryscfukzodp
jbrenqtlagxhicmwjscfikzodp
jbrenqjlagxhivmwyscfmkjodp
jbrenqtlagxpivmwzscgukzodp
jbienqzlagxpivmwyscfukzodp
jbrenqvlagxhivmwdscfukzodx
owrenqtlagxhivmwyicfukzodp
gbrenqtlaathivmwyscfukzodp
jbgenqtlafxhivmwysqfukzodp
jbrenqtlagxhivtwsscfukzokp
jbrnnqylanxhivmwyscfukzodp
ebrenqolagxhivmcyscfukzodp
jbrenqtlarnhivgwyscfukzodp
jbmenqtlagxhivmvyscfukzgdp
jbrevqtlaglhivmwystfukzodp
jbrenqplanthivmwyscfukzodp
jbrenqtlagxhivmkyscbukzosp
jbrenqtlagxaivmwyscfugzodo
jbrenqplagxhnvmwyscfjkzodp
jbrenqtlagxhivgwyscfusrodp
cbrenqtlagxhivmwysmfukzody
jbrenquwaexhivmwyscfukzodp
jbredqtlagxhdvmwyscfukzoup
jbrxnqtlagxhivmwysczukaodp
jbrenqtlafnhivmwyscfuczodp
jbbdkqtlagxhivmwyscfukzodp
ubrenqtlagxhivkwyucfukzodp
ebjenqtlagxhivmwyscfukzodj
jbgenqtlugxxivmwyscfukzodp
jbrenqtoagxqivmwdscfukzodp
bbeenqtlagxhivmwyscfumzodp
jbfeeqtlagxhivmwmscfukzodp
jbrlnqtlagxhiimwescfukzodp
jbrenqtlagwoivmwyscfukhodp
jbrenqtlagnhivmwyscfuszovp`;
const processed = strings
.split("\n")
.map(processKeepString)
.filter(({ occurences }) => Object.keys(occurences).length);
const processedIds = processed.map(({ string }) => string);
const twos = processed.filter(({ occurences }) => occurences[2]).length;
const threes = processed.filter(({ occurences }) => occurences[3]).length;
console.log(findRightBoxes(processedIds));
///////
function buildCounter() {
return [..."abcdefghijklmnopqrstuvwxyz"].reduce((m, l) => {
m[l] = 0;
return m;
}, {});
}
function buildOccurences(string) {
const counter = buildCounter();
[...string].forEach(c => (counter[c] += 1));
return {
occurences: Object.keys(counter).reduce((thoseThatCount, letter) => {
const count = counter[letter];
if (count === 2 || count === 3) {
thoseThatCount[count] = letter;
}
return thoseThatCount;
}, {})
};
}
function processKeepString(string) {
return { string, ...buildOccurences(string) };
}
function findRightBoxes(ids) {
for (let i = 0; i < ids.length; i++) {
let a = ids[i];
for (let j = 0; j < ids.length; j++) {
let b = ids[j];
if (rightBoxes(a, b)) {
return { a, b };
}
}
}
}
function rightBoxes(a, b) {
let count = 0;
for (let i = 0; i < 26; i++) {
if (a[i] !== b[i]) {
count++;
}
if (count > 1) {
return false;
}
}
return count === 1;
}
|
import events from 'utils/events';
class Raf {
constructor() {
// !TODO: calculate avarage FPS
this.fps = undefined;
this.time = window.performance.now();
this.start = this.start.bind(this);
this.pause = this.pause.bind(this);
this.onTick = this.onTick.bind(this);
this.start();
this.bind();
window.requestAnimationFrame(this.onTick);
}
bind() {
events.on(events.VISIBILITY_HIDDEN, this.pause);
events.on(events.VISIBILITY_VISIBLE, this.start);
}
start() {
this.startTime = window.performance.now();
this.oldTime = this.startTime;
this.isPaused = false;
}
pause() {
this.isPaused = true;
}
onTick(now) {
this.time = now;
if (!this.isPaused) {
this.delta = (now - this.oldTime) / 1000;
this.oldTime = now;
events.emit(events.RAF, this.delta, now);
}
window.requestAnimationFrame(this.onTick);
}
}
export default new Raf();
|
import { StyleSheet } from 'react-native';
import { colors, fonts } from '@config/style';
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
marginHorizontal: 10,
},
teamName: {
flexDirection: 'row',
alignItems: 'center',
width: '90%',
height: 50,
backgroundColor: colors.LightGray,
borderRadius: 12,
marginVertical: 10,
},
teamHeaderButtons: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: colors.Salmon,
width: 50,
height: '100%',
},
arrowBack: {
borderTopLeftRadius: 12,
borderBottomLeftRadius: 12,
},
plus: {
borderTopRightRadius: 12,
borderBottomRightRadius: 12,
},
input: {
margin: 10,
padding: 0,
flex: 1,
fontFamily: fonts.MontserratRegular,
paddingHorizontal: 5,
},
text:{
fontFamily: fonts.MontserratRegular,
},
emptyList: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: 150,
},
emptyText: {
fontSize: 16,
color: colors.MediumGray,
},
box: {
alignItems: 'center',
width: '100%',
marginVertical: 20,
},
icon: {
width: 70,
height: 70,
},
image: {
width: 35,
height: 35,
},
name: {
fontFamily: fonts.MontserratBold,
fontSize: 18,
},
number: {
fontFamily: fonts.MontserratBold,
color: colors.MediumGray,
fontSize: 14,
},
moreBtn: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
height: 50,
},
more: {
fontFamily: fonts.MontserratBold,
color: colors.Blue,
},
types: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
margin: 10,
},
list: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-evenly',
},
actions: {
flex: 2,
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
},
description: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
descriptionText: {
fontFamily: fonts.MontserratRegular,
fontSize: 13,
},
});
export default styles;
|
import React from "react";
import moment from "moment";
import { MDBDataTable } from 'mdbreact';
export default class TableContainer extends React.Component {
constructor(props) {
super(props);
this.state = { tableData: { columns: [], rows: [] } }
}
componentDidMount(){
this.packageData(this.props.data)
}
packageData(data){
//Determine columns
let columns= [];
let keys = Object.keys(data[0]);
for(let i = 0; i < keys.length; i++){
columns.push({
label: keys[i].toUpperCase(),
field: keys[i],
sort: 'asc'
});
}
//Format date
for(let i = 0; i < data.length; i++){
data[i].date = moment(data[i].date).format('ll');
}
this.setState( {tableData: {columns: columns, rows: data} })
}
render() {
return (
<MDBDataTable
striped
bordered
small
data={this.state.tableData}
/>
)
}
}
|
var datepickerConfiguration = {
dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
monthNames: ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','December'],
nextText: "→",
prevText: "←",
dateFormat: "yy-mm-dd",
firstDay: 1,
}
var timepickerConfiguration = {
isoTime: true,
minTime: {hour:6,minute:0},
maxTime: {hour:22,minute:0},
timInterval: 30
}
var tooltipConfiguration = {
background: "none",
color: 'black',
border: "none"
}
|
//requires
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var pg = require('pg');
//globals
var port = 8080;
var config = {
database: 'pet_hotel',
host: 'localhost',
port: 5432,
max: 30
}; // end config obj
var pool = new pg.Pool(config);
//uses
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));
//spin up server
app.listen(port, function() {
console.log('server is up on port:', port);
});
//base url
app.get('/', function(req, res) {
console.log('in base url');
res.sendFile(path.resolve('views/index.html'));
}); //end base url
app.get('/owner', function(req, res) {
console.log('drop down');
pool.connect(function(err, connection, done) {
if (err) {
console.log('error');
done();
res.send(400);
} else {
console.log('connected to db');
var allOwners = [];
var resultSet = connection.query('SELECT * FROM pet_table');
resultSet.on('row', function(row) {
allOwners.push(row);
}); //end resultSet
resultSet.on('end', function() {
done();
res.send(allOwners);
}); //end end resultSet
}
}); //done pool get
}); //end get
app.post('/owner', function(req, res) {
console.log('I like pets:', req.body);
pool.connect(function(err, connection, done) {
if (err) {
console.log('error');
done();
res.send(400);
} else {
console.log('connected to database');
connection.query("INSERT INTO pet_table(Owner) values ($1)", [req.body.name]);
done();
res.send(200);
} //end else
}); //end pool connect
}); // end post
app.post('/pet', function(req, res) {
console.log('I like pets2:', req.body);
pool.connect(function(err, connection, done) {
if (err) {
console.log('error');
done();
res.send(400);
} else {
console.log('connected');
connection.query("UPDATE pet_table SET pet = $1, color = $2, breed = $3 WHERE owner= $4", [req.body.name, req.body.color, req.body.breed, req.body.owner]);
done();
res.send(200);
} //end else
}); //end pool connect
}); //end post
app.put('/pet/:id', function(req, res) {
console.log(req.body);
res.send('poop');
}); //end put
app.delete('/pet', function(req, res) {
console.log('pet delete');
pool.connect(function(err, connection, done) {
if (err) {
console.log('error');
done();
res.send(400);
} else {
console.log('connected to database', req.body);
connection.query('DELETE FROM pet_table WHERE +id=' + req.body.id);
done();
res.send(200);
} //end else
}); //end pool connect
});
|
'use strict';
angular.module('studentForm').component('studentForm', {
templateUrl: 'student-form/student-form.template.html',
controller: [
'$scope',
'$routeParams',
'$location',
'Student',
function StudentFormController($scope, $routeParams, $location, Student) {
var self = this;
self.sex = ['M', 'F'];
self.student = $routeParams.id ? Student.get({id: $routeParams.id}) : new Student();
self.submit = function () {
self.student.id ? self.updateStudent() : self.createStudent();
$location.path('/students');
};
self.createStudent = function () {
self.student.$save();
};
self.updateStudent = function () {
self.student.$update();
};
self.reset = function () {
self.student = new Student();
$scope.form.$setPristine(); // reset form
};
}
]
});
|
module.exports = function (bh) {
bh.match('parallels', (ctx) => {
const parallels = ctx.param('parallels');
const tasks = ctx.param('tasks');
ctx.tag('article');
ctx.content({
block: 'wrapper',
content: [
{
block: 'title',
mix: {
block: 'parallels',
elem: 'title'
},
content: ctx.param('title')
},
{
block: 'parallels',
elem: 'list',
content: parallels.map((parallel) => {
var block = bh.utils.extend({
block: 'parallel'
}, parallel);
if (Array.isArray(block.tasks)) {
block.tasks = block.tasks.map((t) => {
return {
code: t,
title: tasks[t]
};
});
}
return block;
})
}
]
});
});
};
|
var axios = require('axios');
var querystring = require('querystring');
var scope_vars = ['activity'];
// axios.get('https://www.fitbit.com/oauth2/authorize', {
// params: {
// response_type: 'code',
// client_id: '227Z6Z',
// redirect_uri: 'https://5673f765.ngrok.io',
// scope: scope_vars.join(' ')
// }
// })
// GET AUTHORIZATION
// axios.request({
// url: 'https://api.fitbit.com/oauth2/token',
// method: 'post',
// headers: {
// 'Authorization': 'Basic MjI3WjZaOjU2NzZlZTFiMjJkOTA3Zjc5ZmI2OGQwYjY0NjIyZDNi=',
// 'Content-Type': 'application/x-www-form-urlencoded'
// },
// params: {
// code: '06884212086111f6463efd5bd6a61e1b0e2a1d68',
// grant_type: 'authorization_code',
// client_id: '227Z6Z',
// redirect_uri: 'https://5673f765.ngrok.io'
// }
// })
// .then(function (response) {
// console.log(response.data);
// })
// .catch(function (error) {
// console.log(error);
// });
// function getDateParameter() {
// var today = new Date();
// var dd = today.getDate();
// var mm = today.getMonth()+1;
// var yyyy = today.getFullYear();
// if(dd<10){
// dd='0'+dd
// }
// if(mm<10){
// mm='0'+mm
// }
// return yyyy+'-'+mm+'-'+dd;
// }
// // GET DATA
// axios.request({
// url: 'https://api.fitbit.com/1/user/4XTL4C/activities/date/'+getDateParameter()+'.json',
// method: 'get',
// headers: {
// 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0WFRMNEMiLCJhdWQiOiIyMjdaNloiLCJpc3MiOiJGaXRiaXQiLCJ0eXAiOiJhY2Nlc3NfdG9rZW4iLCJzY29wZXMiOiJyYWN0IiwiZXhwIjoxNDc0MTAzNzYyLCJpYXQiOjE0NzQwNzQ5NjJ9.aQSbhtFeFOjfPgjlIpcmpEDgS9QWIKhky-OApz1014Q',
// 'Content-Type': 'application/x-www-form-urlencoded'
// }
// })
// .then(function (response) {
// console.log(response.data.summary.steps);
// })
// .catch(function (error) {
// console.log(error);
// });
|
export function helpApple() {
return 'apple';
}
|
// 해시테이블
// 거의 모든 언어에서 사용되고 있는 자료구조로 활용도가 매우 높다.
// 복잡한 데이터를 사람이 쉽게 인지할 수 있는 값으로 교체하여 저장하는 원리다.
// KEY - VALUE = INDEX
// 1. 아주 기본적인 해시펑션
function _hash(key) {
let total;
for (let char of key) {
let value = char.charCodeAt(0) - 96;
total += value;
total %= 10;
}
return total;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// R E F A C T O R I N G //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 2. 첫 번째방법에서 효율을 높인 방법.
// - 속도를 조금이라도 증진시킨다.
// - 랜덤의 범위를 넓힌다.
function _hash(key, arrlength) {
let total = 0, WEIRD_PRIME = 31;
for (let i = 0; i < Math.min(key.length, 100); i++) {
let value = char.charCodeAt(0) - 96;
total += (value + WEIRD_PRIME);
total %= arrlength;
}
return total;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// R E F A C T O R I N G //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 3. 충돌문제를 해결
// - separate chaining 방법 : 같은 인덱스에 추가하여 또다른 배열로 저장하는 방식.
// - Linear Probing 방법 : 인덱스에 값이 존재한다면 그 다음 인덱스에 값을 저장하는 방식
function set(key, value) {
let index = this._hash(key);
if (!this.keyMap) {
this.keyMap = [];
}
this.keyMap[index].push([key, value]);
}
function get(key) {
let index = this._hash(key);
for (let i = 0; i < keyMap[index].length; i++) {
if (this.keyMap[index][i][0] === key) {
return this.keyMap[index][i][1];
}
}
}
|
import "admin-lte/plugins/fontawesome-free/css/all.min.css"
import "admin-lte/dist/css/adminlte.min.css"
import './jquery'
import "admin-lte/plugins/bootstrap/js/bootstrap.bundle.min.js"
import "admin-lte/dist/js/adminlte.js"
|
'use strict';
angular.module('crm')
.controller('MyCampaignsCtrl', function ($scope, $state, resolveCampaigns, ModalService, DataStorage, Notification, GlobalVars, $rootScope, $stateParams) {
if (!$stateParams.clientID)
return $rootScope.showSelectClientModal()
$scope.mdfsSafe = resolveCampaigns.Campaigns || [];
$scope.$state = $state;
$scope.mdfHeaderOptions = {title: $rootScope.translate('campaigns.campaigns.mycampaigns.controller.existing-campaigns'), searchField: {cb: void(0)}};
$scope.addNewCampaign = function () {
$state.go('main.campaignsetup');
};
$scope.edit = function (curName, curUrl) {
ModalService.showModal({
templateUrl: "components/modals/CAMPAIGNS/mdf/editMdf.html",
controller: "EditMdfCtrl",
inputs: {
data: {
modalTitle: $rootScope.translate('campaigns.campaigns.mycampaigns.controller.edit-campaign'),
nameValue: curName,
urlValue: curUrl
}
}
}).then(function (modal) {
//it's a bootstrap element, use 'modal' to show it
modal.element.modal();
modal.close.then(function (result) {
if (result === 'false') return false;
return false;
});
});
};
$scope.delete = function (row) {
ModalService.showModal({
templateUrl: "components/modals/COMMON/sure.html",
controller: "DataModalCtrl",
inputs: {
data: {
modalTitle: $rootScope.translate('campaigns.campaigns.mycampaigns.controller.delete-campaign'),
modalTxt: $rootScope.translate('campaigns.campaigns.mycampaigns.controller.are-you-sure-you-want-to-delete-this-campaign?')
}
}
}).then(function (modal) {
modal.element.modal();
modal.close.then(function (result) {
if (result === 'false') return false;
DataStorage.anyApiMethod('/campaigns/delete/' + row.CampaignGuid).post({},function(resp){
var index = $scope.mdfsSafe.indexOf(row)
if (index > -1)
$scope.mdfsSafe.splice(index,1);
Notification.success({message: $rootScope.translate('campaigns.campaigns.mycampaigns.controller.campaign')+' ' + row.Name + ' ' + $rootScope.translate('campaigns.campaigns.mycampaigns.controller.has-been-successfully-removed'), delay: 5000})
});
});
});
};
$scope.go = $state.go;
$scope.goToEdit = function(campaignGuid){
GlobalVars.setLoadingRequestStatus(true)
$state.go('main.campaignsetup', { 'campaignGuid': campaignGuid})
};
$scope.downloadKit = function(apiGuid){
DataStorage.anyApiMethod('/campaigns/download/'+apiGuid).query(function(resp){
if (resp && resp.Content){
//var blob = $.b64toBlob(resp.Content, 'application/zip');
//$.downloadBlob(blob, resp.Filename || 'kit.zip')
download('data:application/zip;base64,' + resp.Content, resp.Filename || 'kit.zip', "application/zip");
//$.downloadUrl('data:application/zip;base64,' + resp.Content, resp.Filename || 'kit.zip')
}
})
}
});
|
import React, { Component } from 'react';
class List extends Component {
render() {
return (
<div>
<div className="left">
<img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565935063926&di=93a91a6bd762883367d3c9d545fe3d24&imgtype=0&src=http%3A%2F%2Fimg2.artron.net%2Fauction%2F2012%2Fart001308%2Fd%2Fart0013080680.jpg' alt=""/>
</div>
<div className="center">
{this.props.startTime}
</div>
<div className="right">
{this.props.endTime}
</div>
</div>
);
}
}
export default List;
|
$(document).ready(function() {
//alert(1);
//consola Firebug -> copiar -> Nuevo marcador -> pegar en Dirección
var sGuardar = "";
for(var i=0; i<$("div.cuerpoRegionLeft").length; i++){
var oDiv = $("div.cuerpoRegionLeft").eq(i);
var oLI_casa = oDiv.find("UL").eq(1).find("LI");
var oLI_fuera = oDiv.find("UL").eq(2).find("LI");
for(var e=0; e<oLI_casa.length; e++){
var sCasa = oLI_casa.eq(e).html();
if(sCasa.substring(0,1) == " "){
sCasa = sCasa.substring(1);
}
sCasa = sCasa.replace(". ", ".");
var sFuera = oLI_fuera.eq(e).html();
if(sFuera.substring(0,1) == " "){
sFuera = sFuera.substring(1);
}
sFuera = sFuera.replace(". ", ".");
sGuardar += sCasa +"-"+ sFuera +"\n";
if(e==13){
sGuardar += "\n";
}
}
}
if(sGuardar.length > 20){
sGuardar = sGuardar.toUpperCase();
//alert(sGuardar);
$("div.pieRegion").append("<TEXTAREA id='ta' rows='18' cols='35'></TEXTAREA>");
$("#ta").val(sGuardar);
}
});
|
import React, { Component } from 'react'
import {InputItem ,Button ,Toast} from 'antd-mobile'
import axios from 'axios';
class Index extends Component {
state = {
username:'',
password:'',
disabled:true
}
render() {
let {disabled,username,password} = this.state;
return (
<div>
<InputItem
type="text"
placeholder="请输入用户名"
onChange={this.checkLogin.bind(this,'username')}
value={username}
/>
<InputItem
type="password"
placeholder="请输入密码"
onChange={this.checkLogin.bind(this,'password')}
value={password}
/>
<Button type="primary" disabled={disabled} onClick={this.login}>登陆</Button>
</div>
)
}
checkLogin(key,value){
let {username,password,disabled} = this.state;
if(username && password){
disabled = false;
}else{
disabled = true;
}
this.setState({
[key]:value,
disabled
})
}
login=()=>{
let {username,password} = this.state;
axios.post('/api/login',{
username,
password
}).then(res=>{
if(res.data.code === 1){
window.localStorage.setItem('token',res.data.data.token);
this.props.history.push('/home');
}else{
Toast.fail(res.data.msg)
}
})
}
}
export default Index;
|
var _viewer = this;
if (_viewer.opts.readOnly) {
_viewer.readCard();
}
|
import { Stack } from '../Stack';
import { NODE_FN } from '../utils';
export function preorderT(tree, visitor = NODE_FN) {
visitor(tree);
if (tree.l) preorderT(tree.l, visitor);
if (tree.r) preorderT(tree.r, visitor);
}
export function inorderT(tree, visitor = NODE_FN) {
if (tree.l) inorderT(tree.l, visitor);
visitor(tree);
if (tree.r) inorderT(tree.r, visitor);
}
export function postorderT(tree, visitor = NODE_FN) {
if (tree.l) postorderT(tree.l, visitor);
if (tree.r) postorderT(tree.r, visitor);
visitor(tree);
}
export function preorderTraversal(tree, visitor = NODE_FN) {
const stack = new Stack();
stack.push(tree);
while(stack.length > 0) {
const n = stack.peek();
// visit n
visitor(n);
stack.pop();
if (n.r && !n.r.visited) {
stack.push(n.r);
n.r.visited = true;
}
if (n.l && !n.l.visited) {
stack.push(n.l);
n.l.visited = true;
}
}
}
export function inorderTraversal(tree, visitor = NODE_FN) {
const stack = new Stack();
stack.push(tree);
while(stack.length > 0) {
const n = stack.peek();
if (n.l && !n.l.visited) {
stack.push(n.l);
n.l.visited = true;
} else {
// visit n
visitor(n);
stack.pop();
if (n.r && !n.r.visited) {
stack.push(n.r);
n.r.visited = true;
}
}
}
}
export function postorderTraversal(tree, visitor = NODE_FN) {
const stack = new Stack();
stack.push(tree);
while(stack.length > 0) {
const n = stack.peek();
if (n.l && !n.l.visited) {
stack.push(n.l);
n.l.visited = true;
} else if (n.r && !n.r.visited) {
stack.push(n.r);
n.r.visited = true;
} else {
// visit n
visitor(n);
stack.pop();
}
}
}
|
define([], function () {
'use strict';
var ModelError = function (options) {
options = _.defaults(options || {}, {
verbose: 'Unknow',
identifier: 0,
model: null
});
this.verbose = options.verbose;
this.identifier = options.identifier;
this.model = options.model;
};
_.extend(ModelError.prototype, {
clear: function(){
this.model= null;
this.identifier = null;
this.verbose = null;
}
});
return ModelError;
});
|
export const getAccount = token => {
return window.ipcRenderer.invoke('yandex-login/getAccount', token);
};
|
import axios from '@/utils/request'
//日志列表
export function logList(data) {
return axios.post('/api/log/index', data).then(res => {
return Promise.resolve(res)
}).catch(err => {
console.log(err);
})
}
export function clearLog(data) {
return axios.post('/api/log/delete', data).then(res => {
return Promise.resolve(res)
}).catch(err => {
console.log(err);
})
}
|
const Person = (props) => {
let message;
if (props.age < 18) {
message = "you must be 18";
} else {
message = "please go vote!";
}
return (
<div className="card">
<div className="card-body">
<p>Learn some information about this person.</p>
<p>
Name: {props.name.length > 8 ? props.name.slice(0, 6) : props.name}
</p>
<p>Age: {props.age}</p>
<p>Message: {message}</p>
<ul> <u>Hobbies</u>
{props.hobbies.map((hobbie) => (
<li key={hobbie}>{hobbie}</li>
))}
</ul>
</div>
</div>
);
};
|
import { Link } from "gatsby"
import PropTypes from "prop-types"
import styled from "styled-components"
import React from "react"
import Img from "gatsby-image"
import { breakpoints } from "../breakpoints"
const Card = styled.div`
background: #fff;
padding: 0.5em;
display: flex;
align-items: center;
justify-content: center;
flex-direction: row;
min-width: 100%;
img {
width: 100%;
height: auto;
}
`
const Meta = styled.div`
display: grid;
align-items: center;
justify-content: space-between;
grid-template-columns: 1fr;
margin: 0.5em 0;
width: 100%;
@media ${breakpoints.laptop} {
grid-template-columns: 1fr 1fr;
}
h4,
h5 {
margin: 0;
text-align: center;
}
h5{
font-family: "Roboto";
font-size: 1rem;
}
@media ${breakpoints.laptop} {
h4{
text-align: left;
}
h5{
text-align: right;
}
}
`
const TeamCard = ({ person }) => (
<Card>
<Link
to={person.fields.slug}
style={{ textDecoration: `none`, color: "#212121" }}
>
<img src={person.frontmatter.featuredImage.childImageSharp.resize.src} />
<Meta>
<h4>{person.frontmatter.name}</h4>
<h5>{person.frontmatter.title}</h5>
</Meta>
</Link>
</Card>
)
TeamCard.propTypes = {
person: PropTypes.object,
}
TeamCard.defaultProps = {
person: ``,
}
export default TeamCard
|
/**
* 遍历一个vue组件获取其满足特定条件的子
* @param component
* @param checkFunc
* @returns {*}
*/
export default function findVmChildren(component, checkFunc) {
if (component.$children) {
for(let childVmChildren of component.$children) {
if (checkFunc(childVmChildren)) {
return childVmChildren;
} else {
return findVmChildren(childVmChildren, checkFunc);
}
}
}
}
|
// import comments from "../comments";
import CommentModel from "../models/CommentModel";
//GET => List
export function list(request, response) {
CommentModel.find({}).exec()
.then(comments => {
return response.json(comments);
});
}
//GET/:id => Show
export function show(request, response) {
CommentModel.findById(request.params.id).exec()
.then(comment => {
return response.json(comment);
});
}
//POST => Create
export function create(request, response) {
const comment = new CommentModel({
body: request.body.body,
});
comment.save()
.then(comment => {
return response.json(comment);
});
}
//PUT/:id => Update
export function update(request, response) {
CommentModel.findById(request.params.id).exec()
.then(comment => {
comment.body = request.body.body || comment.body;
return comment.save();
})
.then(comment => {
return response.json(comment);
})
}
//DELETE/:id => Remove
export function remove(request, response) {
return response.json({});
}
|
const express = require("express");
const server = express();
const routes = require("./routes");
const path = require("path")
//server.use é um comando usado para setar/habilitar configs no server
//abilitando a view engine ejs no express
server.set('view engine', 'ejs')
// => mudando a localização da pasta views
server.set("views", path.join(__dirname, "views"))
server.use(express.static("public"));
//habilitando statics, arquivos publicos que não serão mudados com muita frequencia e que são publicos
//abilitando a visualização do req.body
server.use(express.urlencoded( { extended: true } ))
server.use(routes)
//importando as rotas para possibilitar o servidor de seguir os caminhos estabelecidos
server.listen(3000, () => console.log("rodando"));
// habilitando o server para detectar a porta padrão 3000
|
'use strict';
const logger = require('../utils/logger');
const bookmarkListStore = require('../models/bookmarkList-store.js');
const bookmarkDB = {
index(request, response) {
logger.info('bookmarkDB rendering');
const viewData = {
title: 'Bookmark List Dashboard',
bookmarks: bookmarkListStore.getAllBookmarkLists(),
};
logger.info('about to render', bookmarkListStore.getAllBookmarkLists());
response.render('bookmarkDB', viewData);
},
};
module.exports = bookmarkDB;
|
import React from 'react';
import {
View,
ToastAndroid,
Dimensions,
Alert,
Keyboard
} from 'react-native';
import { List, ListItem, CheckBox, FooterTab, Footer, Container, Content, Button, Text, H3, Left, Right, Icon } from 'native-base';
import { LogoTitle, UploadIcon } from '../../../components/header';
import Spinner from 'react-native-loading-spinner-overlay';
import Strings from '../../../language/fr'
import { DepartmentsWithEquipments, addCleanSchedule, editCleanSchedule } from '../../../database/realm';
import { styles } from '../../../utilities/styles';
import { CustomPicker } from 'react-native-custom-picker';
import { renderOption, renderFieldDanger, renderFieldSuccess } from '../../../utilities/index'
export class AdminCleanItemScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
drawerLabel: Strings.CLEANING_SCHEDULE,
drawerIcon: ({ tintColor }) => (
<Icon name='snow' style={{ color: tintColor, }} />
),
headerTitle: <LogoTitle HeaderText={Strings.CLEANING_SCHEDULE} />,
headerRight: <UploadIcon navigation={navigation} />,
};
};
constructor(props) {
super(props);
this.state = {
id: this.props.navigation.state.params.id,
department: this.props.navigation.state.params.department,
equipment: this.props.navigation.state.params.equipment,
type: null,
days: [],
departments: [],
types: [
{ name: Strings.MONTHLY, value: 1 },
{ name: Strings.WEEKLY, value: 2 },
{ name: Strings.DAILY, value: 3 }
],
weekly: [
{ name: Strings.MON, value: 1 },
{ name: Strings.TUE, value: 2 },
{ name: Strings.WED, value: 3 },
{ name: Strings.THU, value: 4 },
{ name: Strings.FRI, value: 5 },
{ name: Strings.SAT, value: 6 },
{ name: Strings.SUN, value: 7 },
],
monthly: [
{ name: '1', value: 1 },
{ name: '2', value: 2 },
{ name: '3', value: 3 },
{ name: '4', value: 4 },
{ name: '5', value: 5 },
{ name: '6', value: 6 },
{ name: '7', value: 7 },
{ name: '8', value: 8 },
{ name: '9', value: 9 },
{ name: '10', value: 10 },
{ name: '11', value: 11 },
{ name: '12', value: 12 },
{ name: '13', value: 13 },
{ name: '14', value: 14 },
{ name: '15', value: 15 },
{ name: '16', value: 16 },
{ name: '17', value: 17 },
{ name: '18', value: 18 },
{ name: '19', value: 19 },
{ name: '20', value: 20 },
{ name: '21', value: 21 },
{ name: '22', value: 22 },
{ name: '23', value: 23 },
{ name: '24', value: 24 },
{ name: '25', value: 25 },
{ name: '26', value: 26 },
{ name: '27', value: 27 },
{ name: '28', value: 28 },
{ name: '29', value: 29 },
{ name: '30', value: 30 },
{ name: '31', value: 31 },
],
dimesions: { width, height } = Dimensions.get('window'),
};
this._bootstrapAsync();
}
_showLoader() {
this.setState({ loading: 1 });
}
_hideLoader() {
this.setState({ loading: 0 });
}
_onLayout() {
this.setState({ dimesions: { width, height } = Dimensions.get('window') })
}
_bootstrapAsync = async () => {
this.setState({ departments: await DepartmentsWithEquipments() });
if (this.props.navigation.state.params.type > 0) {
this.setState({ type: this.state.types[this.props.navigation.state.params.type - 1] });
}
if (this.props.navigation.state.params.id.length > 0) {
this._organizeEditDays(this.props.navigation.state.params);
}
};
_organizeEditDays(item) {
let days = [];
if (item.monday == 1) days.push(1);
if (item.tuesday == 1) days.push(2);
if (item.wednesday == 1) days.push(3);
if (item.thursday == 1) days.push(4);
if (item.friday == 1) days.push(5);
if (item.saturday == 1) days.push(6);
if (item.sunday == 1) days.push(7);
this.state.monthly.map(object => {
if (item['day_' + object.value] == 1) {
days.push(object.value);
}
});
this.setState({ days: days });
}
_changeDepartment = async (itemValue) => {
this.setState({ department: itemValue, equipment: null, type: null, days: [] });
}
_changeEquipment = async (itemValue) => {
this.setState({ equipment: itemValue });
}
_changeType = async (itemValue) => {
this.setState({ type: itemValue, days: [] });
}
_toggleDay = (value) => {
let days = this.state.days;
let index = days.indexOf(value);
if (index < 0) {
days.push(value)
} else {
days.splice(index, 1);
}
this.setState({ days: days });
}
_clickSave = () => {
Alert.alert(
Strings.CLEANING_SCHEDULE_SAVE,
Strings.ARE_YOU_SURE,
[
{ text: Strings.CANCEL, style: 'cancel' },
{ text: Strings.OK, onPress: () => this._save() },
],
{ cancelable: false }
)
}
_save = async () => {
this._showLoader();
let form = {
department: this.state.department,
equipment: this.state.equipment,
type: this.state.type.value,
};
setTimeout(async () => {
realmObject = {};
let monthlyObject = {};
let weeklyObject = {};
let weekDays = ['none', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
// Fill monthly object with empty values
this.state.monthly.map(object => {
monthlyObject['day_' + object.value] = 0;
})
// Fill weekly object with
weekDays.map(value => {
weeklyObject[value] = 0;
})
if (this.state.type.value == 1) {
// Monthly
this.state.days.map(day => {
monthlyObject['day_' + day] = 1;
})
} else if (this.state.type.value == 3) {
// Dailly
for (let i = 1; i <= 31; i++) {
monthlyObject['day_' + i] = 1;
}
} else {
// Weekly
this.state.days.map(day => {
weeklyObject[weekDays[day]] = 1;
})
}
// Combine all the fields
realmObject = { ...form, ...monthlyObject, ...weeklyObject };
if (this.state.id.length > 0) {
editCleanSchedule({ ...{ id: this.state.id }, ...realmObject }).then(() => {
this.props.navigation.navigate('AdminCleanIndex');
Keyboard.dismiss();
this._hideLoader();
ToastAndroid.show(Strings.SCHEDULE_SUCCESSFULL_SAVED, ToastAndroid.LONG);
}).catch(error => {
Keyboard.dismiss();
this._hideLoader();
alert(error);
});
} else {
addCleanSchedule(realmObject).then(() => {
this.props.navigation.navigate('AdminCleanIndex');
Keyboard.dismiss();
this._hideLoader();
ToastAndroid.show(Strings.SCHEDULE_SUCCESSFULL_SAVED, ToastAndroid.LONG);
}).catch(error => {
Keyboard.dismiss();
this._hideLoader();
alert(error);
});
}
}, 500);
}
render() {
return (
<Container style={{ flex: 1, paddingTop: 50, }} onLayout={this._onLayout.bind(this)}>
<Spinner visible={this.state.loading} textContent={Strings.LOADING} textStyle={{ color: '#FFF' }} />
<Content style={{ width: this.state.dimesions.width, paddingLeft: 30, paddingRight: 30, }}>
<View style={styles.container}>
{this.state.departments.length == 0 && <H3 style={{ marginTop: 30, textAlign: 'center' }}>{Strings.THERE_IS_NO_DEPARTMENTS}</H3>}
{this.state.departments.length > 0 && <View>
<CustomPicker
optionTemplate={renderOption}
fieldTemplate={this.state.department !== null ? renderFieldSuccess : renderFieldDanger}
placeholder={Strings.SELECT_DEPARTMENT}
getLabel={item => item.name}
options={this.state.departments}
value={this.state.department}
onValueChange={(value) => this._changeDepartment(value)}
/>
{this.state.department !== null && <CustomPicker
optionTemplate={renderOption}
fieldTemplate={this.state.equipment !== null ? renderFieldSuccess : renderFieldDanger}
placeholder={Strings.SELECT_EQUIPMENTS}
getLabel={item => item.name}
options={this.state.department.equipments}
value={this.state.equipment}
onValueChange={(value) => this._changeEquipment(value)}
/>}
{this.state.equipment !== null && <CustomPicker
optionTemplate={renderOption}
fieldTemplate={this.state.type !== null ? renderFieldSuccess : renderFieldDanger}
placeholder={Strings.SELECT_TYPE}
getLabel={item => item.name}
options={this.state.types}
value={this.state.type}
onValueChange={(value) => this._changeType(value)}
/>}
{this.state.type !== null && this.state.type.value == 1 && <View style={{ borderLeftWidth: 5, borderLeftColor: 'lightgray' }}><List>
{this.state.monthly.map((data) => {
return <ListItem style={{ height: 70, }} onPress={() => { this._toggleDay(data.value) }}>
<Left>
<Text>{data.name}</Text>
</Left>
<Right>
<CheckBox style={{ marginRight: 15, }} checked={this.state.days.includes(data.value)} onPress={() => { this._toggleDay(data.value) }} />
</Right>
</ListItem>;
})}
</List></View>}
{this.state.type !== null && this.state.type.value == 2 && <View style={{ borderLeftWidth: 5, borderLeftColor: 'lightgray' }}><List>
{this.state.weekly.map((data) => {
return <ListItem style={{ height: 70, }} onPress={() => { this._toggleDay(data.value) }}>
<Left>
<Text>{data.name}</Text>
</Left>
<Right>
<CheckBox style={{ marginRight: 15, }} checked={this.state.days.includes(data.value)} onPress={() => { this._toggleDay(data.value) }} />
</Right>
</ListItem>;
})}
</List></View>}
</View>}
</View>
</Content >
{this.state.department !== null && this.state.equipment !== null && this.state.type !== null && ( this.state.days.length > 0 || this.state.type.value == 3 ) && <Footer styles={{ height: 100 }}>
<FooterTab styles={{ height: 100 }}><Button full success onPress={_ => this._clickSave()} >
<View style={{ flexDirection: 'row' }}>
<Text style={[{ color: 'white', paddingTop: 5, }, styles.text]}>{Strings.SAVE}</Text>
<Icon name='checkmark' style={{ color: 'white', }} />
</View>
</Button></FooterTab>
</Footer>}
</Container>
);
}
}
|
Given(/^I am on Juices page$/, () => {
juicesPage.goToJuicesPage();
});
When(/^I select "(Price Low-High|Price High-Low|Name Increasing|Name Decreasing)" sort option$/, (sorting) => {
globalVar.sortOption = sorting;
juicesPage.selectSortOption(sorting);
});
Then(/^the items should be correctly sorted$/, () => {
juicesPage.loadMoreItems();
juicesPage.verifySelectedSortOption(globalVar.sortOption);
});
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import UserOptions from './UserOptions';
import { logoutUser } from 'Actions/userAuth';
import { showModal, closeModal } from 'Actions/modal';
import modalTypes from '../../Modal/modalTypes';
import PropTypes from 'prop-types';
const { CHANGE_PASSWORD_MODAL } = modalTypes;
/**
* @class UserDropdown
* @extends { React.Component }
* @description Renders the user dropdown list
* @param { object } props
* @returns { JSX }
*/
class UserDropdown extends Component {
constructor(props){
super(props)
this.viewProfile = this.viewProfile.bind(this);
this.signOut = this.signOut.bind(this);
this.changePassword = this.changePassword.bind(this);
}
/**
* @method viewprofile
* @memberof UserDropdown
* @description Handles on click event to view user profile
* @param { null }
* @returns { void }
*/
viewProfile(event){
event.preventDefault();
alert('My profile')
}
/**
* @method signOut
* @memberof UserDropdown
* @description Handles on click event to sign user out
* @param { null }
* @returns { void }
*/
signOut(event){
event.preventDefault();
this.props.logoutUser();
this.context.router.history.push('/');
}
changePassword(event){
event.preventDefault();
this.props.showModal(CHANGE_PASSWORD_MODAL)
}
render(){
if(this.props.isAuthenticated === false){
return null;
}
return(
<div className="btn-group dropdown">
<UserOptions
user={this.props.user}
isAuthenticated={this.props.isAuthenticated}
viewProfile = {this.viewProfile}
signOut = {this.signOut}
changePassword ={this.changePassword}/>
</div>
)
}
}
UserDropdown.contextTypes = {
router: PropTypes.object.isRequired
}
const mapStateToProps = (state) => ({
user: state.auth.user,
isAuthenticated: state.auth.isAuthenticated
})
const actionCreators = {
showModal,
closeModal,
logoutUser
}
export { UserDropdown }
export default connect(mapStateToProps, actionCreators)(UserDropdown)
|
import { connectRedis, disconnectRedis } from "../../lib/redis";
export default async function handler(req, res) {
const { id } = req.body;
const subreddit = await connectRedis().get(id);
disconnectRedis();
if (!subreddit) {
res.status(404).send("Unable to find game id");
return;
}
res.status(200).json({ id, subreddit });
}
|
import React from 'react';
import Footer from './Footer';
import Grid from '@material-ui/core/Grid';
// import { makeStyles } from '@material-ui/core/styles';
import './styles/about.css';
// const useStyles = makeStyles((theme) => ({
// root: {
// flexGrow: 1,
// },
// paper: {
// padding: theme.spacing(2),
// textAlign: 'center',
// color: theme.palette.text.secondary,
// },
// }));
export default function About() {
return (
<>
<div className='about '>
<Grid container spacing={3} >
<Grid item xs={12} md={12} sm={12} className='headline'>Some of the technologies used:</Grid>
</Grid>
<Grid container className='content' >
<Grid item xs={12} md={2} sm={3} lg={2} className='center'><img src='https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/768px-React-icon.svg.png' alt='react' height='100px' width='150px'></img></Grid>
<Grid item xs={12} md={10} sm={9} lg={10} className='para'><span className='subheader'><a href='https://reactjs.org/'>React</a></span> <br />React is an open-source, front end, JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. Add <a href='https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en'>react dev tools</a> to browser and see state, props and component tree of this page</Grid>
</Grid>
<Grid container className='content' >
<Grid item xs={12} md={2} sm={3} lg={2} className='center'><img src='https://redux.js.org/img/redux.svg' alt='react' height='100px' width='150px'></img></Grid>
<Grid item xs={12} md={10} sm={9} lg={10} className='para'><span className='subheader'><a href='https://redux.js.org/'>Redux</a></span> <br />Redux is a Predictable State Container for JS Apps. The Redux DevTools make it easy to trace when, where, why, and how your application's state changed. <a href='https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl='>Add Redux Dev Tools</a> to browser and see how state changes in app</Grid>
</Grid>
<Grid container className='content' >
<Grid item xs={12} md={2} sm={3} lg={2} className='center'><img src='https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Node.js_logo.svg/885px-Node.js_logo.svg.png' alt='Redux' height='100px' width='150px'></img></Grid>
<Grid item xs={12} md={10} sm={9} lg={10} className='para'><span className='subheader'><a href='https://nodejs.org'>Node</a></span><br />Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser. See <a href='https://nodejs.org/en/docs'>node</a> official doucmentation </Grid>
</Grid>
<Grid container className='content' >
<Grid item xs={12} md={2} sm={3} lg={2} className='center'><img src='https://symbols-electrical.getvecta.com/stencil_79/87_expressjs.72a4a0d57c.svg' alt='Express' height='100px' width='150px'></img></Grid>
<Grid item xs={12} md={10} sm={9} lg={10} className='para'><span className='subheader'><a href='https://expressjs.com/'>Express</a></span><br />Express provides a robust set of features for web, it is a minimal and flexible Node.js web application framework. Express is the first choice of server for js application</Grid>
</Grid>
<Grid container className='content' >
<Grid item xs={12} md={2} sm={3} lg={2} className='center'><img src='https://cdn.worldvectorlogo.com/logos/mongodb.svg' alt='MongoDb' height='100px' width='150px'></img></Grid>
<Grid item xs={12} md={10} sm={9} lg={10} className='para'><span className='subheader'><a href='https://www.mongodb.com/'>MongoDB</a></span><br />Since MongoDB uses JSON documents for database it make it a perfect choice to use in Javacript application </Grid>
</Grid>
<Grid container className='content ' >
<Grid item xs={12} md={2} sm={3} lg={2} className='center'><img src='https://material-ui.com/static/logo.png' alt='Material UI' height='125px' width='150px'></img></Grid>
<Grid item xs={12} md={10} sm={9} lg={10} className='para'><span className='subheader'><a href='https://material-ui.com/'>Material UI</a></span><br />React components for faster and easier web development, helps create responsive web page faster</Grid>
</Grid>
</div>
<br /><br /><br /><br />
This website is soley created as hobbyist project. No copyright infringement intended. All rights reserved to <a href='https://todoist.com/'>todoist</a>
<Footer />
</>
)
}
|
var mongoose = require('mongoose');
var debug = require('debug')('notekeep:postmodel');
var PostSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
dateCreated: {
type: Date,
required: true,
default: Date.now
},
editedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
dateEdited: {
type: Date
},
content: {
type: String,
required: true
}
});
PostSchema.query.findByUser = function(userID) {
debug('Finding posts by user for ' + userID);
return this.find({ user: userID });
};
PostSchema.index({user: 1, dateCreated: -1});
var Post = mongoose.model('Post', PostSchema);
module.exports = Post;
|
import firebase from 'firebase';
import moment from 'moment';
const uploadPicture = (base64) => {
//console.log(dict);
//console.log("dict uploading")
const key = firebase.database().ref('requests').push().key;
const updates = {};
updates[`requests/${key}`] = {
id: key,
timestamp: moment().format()
}
updates[`requests_imgs/${key}`] = {
image: base64,
}
return firebase.database().ref().update(updates);
}
const uploadData = (dict) => {
//console.log(dict);
//console.log("dict uploading")
const key = firebase.database().ref('data').push().key;
const updates = {};
updates[`data/${key}`] = {
id: key,
timestamp: moment().format()
}
updates[`data_imgs/${key}`] = {
data: dict,
}
return firebase.database().ref().update(updates);
}
const getData = () => {
return firebase.database().ref('data_imgs').once('value');
}
const loadDocuments = () => {
return firebase.database().ref('requests').once('value');
}
export {
uploadPicture,
loadDocuments,
uploadData,
getData
}
|
import axios from "axios";
import {API_URL} from "../constants"
class AuthService {
login(email, password){
return axios.post(API_URL + "auth/login", { email, password })
}
logout() {
localStorage.removeItem("GROUPOMANIA_USER");
}
register(username, email, password) {
return axios.post(API_URL + "auth/register", {
username,
email,
password,
});
}
}
export default new AuthService();
|
import React, { Component } from "react";
import "./App.css";
import UserList from "./UserList";
class App extends Component {
state = {
users: [],
isLoaded: false
};
componentDidMount() {
fetch(
"https://api.github.com/search/users?o=desc&q=location%3ARivne&s=followers&type=Users&per_page=10"
)
.then(Response => Response.json())
.then(json => {
this.setState({
isLoaded: true,
users: json
});
// console.log("USERS", json);
});
}
render() {
const { isLoaded, users } = this.state;
// console.log("USERS", this.state.users);
return (
<div className="App">
{!isLoaded ? (
<div>L o a d i n g . . .</div>
) : (
<div>
{this.state.users.items.map(iterator => {
return (
<UserList
{...this.props}
Image={iterator.avatar_url}
User={iterator.login}
URL={iterator.html_url}
key={iterator.id}
/>
);
})}
</div>
)}
</div>
);
}
}
export default App;
|
module.exports = (sequelize, DataTypes) => {
const Group_chatting = sequelize.define('Group_chatting', {
group_room: {
type: DataTypes.STRING(50),
allowNull: false
},
group_name: {
type: DataTypes.STRING(50),
allowNull: false
},
group_message: {
type: DataTypes.TEXT,
allowNull: false
}
}, {
charset: 'utf8mb4', //한글 + 이모티콘 게시글에 이모티콘이 달릴 수 있기 떄문에
collate: 'utf8mb4_general_ci', //이모티콘때문에
});
Group_chatting.associate = (db) => {
db.Group_chatting.belongsTo(db.Group_list_gaci);
}
return Group_chatting;
}
|
import React, { useContext, useEffect } from "react";
import { PostsContext } from "../context/posts/postsContext";
import Loader from "../components/Loader";
import PostBody from "../components/PostBody";
function Post(props) {
const { id: postId } = props.match.params;
const { fetchPost, loading, post } = useContext(PostsContext);
//post = posts.filter((p) => Number(postId) === p.id)[0];
useEffect(() => {
fetchPost(postId);
// eslint-disable-next-line
}, []);
return <>{loading ? <Loader /> : <PostBody post={post} />}</>;
}
export default Post;
|
import Vue from 'vue'
import sample from './data'
var app = new Vue({
el: '#app',
data: {
title: sample.title,
address: sample.address,
about: sample.about,
headerImageStyle: {
'background-image': 'url(images/header.jpg)'
},
amenities: sample.amenities,
prices: sample.prices,
contracted: true,
modalOpen: false
},
methods: {
escapeKeyListener: function(evt) {
if (evt.keyCode === 27 && this.modalOpen) {
this.modalOpen = false;
}
}
},
watch: {
modalOpen: function() {
var className = 'modal-open';
if (this.modalOpen) {
document.body.classList.add(className);
} else {
document.body.classList.remove(className);
}
}
},
created: function() {
document.addEventListener('keyup', this.escapeKeyListener);
console.log(sample['title'])
},
destroyed: function () {
document.removeEventListener('keyup', this.escapeKeyListener);
}
});
|
const get = (div, x, y) => {
if (y > 4 || y < 0 || x < 0 || x > 4) {
return 0;
}
let i = 5 * y + x;
return (div >> i) & 1;
}
const set = (div, x, y, value) => {
if (y > 4 || y < 0 || x < 0 || x > 4) {
return div;
}
let i = 5 * y + x;
return value ? (div | (1 << i)) : (div & ~(1 << i));
}
module.exports = input => {
let current = input.split('\n')
.flatMap(r => r.trim().split(''))
.reduce((div, p, i) => p == '#' ? div | (1 << i) : div, 0);
let seen = new Set();
let neighbours = [[1, 0], [-1, 0], [0, 1], [0, -1]];
while (!seen.has(current)) {
seen.add(current);
let next = current;
for (let x = 0; x < 5; x++) {
for (let y = 0; y < 5; y++) {
let sum = neighbours.reduce((sum, [dx, dy]) => sum + get(current, x + dx, y + dy), 0);
if (get(current, x, y) && sum != 1) {
next = set(next, x, y, 0);
}
if (!get(current, x, y) && sum > 0 && sum < 3) {
next = set(next, x, y, 1);
}
}
}
current = next;
}
return current;
}
|
import { Avatar } from "@material-ui/core";
import React, { forwardRef } from "react";
import InputOption from "./InputOption";
import { Link } from "react-router-dom";
import getDateTime from '../../../util/timeFormat'
const Post = ({ questionData }) => {
const AuthorEmail = questionData.author.email;
const { content, tags } = questionData;
const name = `${questionData.author.firstName} ${questionData.author.lastName}`;
const creationTime = questionData.createdAt
const id = questionData._id;
const newTo = {
pathname: `/question/${id}`,
state: {
AuthorEmail: AuthorEmail,
content: content,
tags: tags,
name: name,
questionData: questionData,
},
};
return (
<Link to={newTo}>
<div className="Post">
<div className="post__header">
<Avatar />
<div className="post__info">
<h2>{name}</h2>
<p>{AuthorEmail}</p>
<p><b>{getDateTime(creationTime)}</b></p>
</div>
</div>
<div className="post__body">
{/* <p>{message}</p> */}
<p>{content}</p>
</div>
<div className="post__tags">
{
tags.map((tag, index) => (
<div className="tag-ele" key={index}>{tag}</div>
))
}
</div>
</div>
</Link>
);
};
export default Post;
|
/*~~~~~~~~~~~~~~~~~~~~ Begin Boiler Plate ~~~~~~~~~~~~~~~~~~*/
const readline = require('readline');
const readlineInterface = readline.createInterface(process.stdin, process.stdout);
function ask(questionText) {
return new Promise((resolve, reject) => {
readlineInterface.question(questionText, resolve);
});
}
/*~~~~~~~~~~~~~~~~~~~~~~End Boiler Plate~~~~~~~~~~~~~~~~~~~~*/
//Classes
class Room {
constructor(name, description, inventory, canChangeTo){
this.name = name;
this.description = description;
this.roomInventory = inventory;
this.canChangeTo = canChangeTo;
}
}
class Item{
constructor(name, description, canPickUp, pickUpText, inventoryText){
this.name = name;
this.description = description;
this.canPickUp = canPickUp;
this.pickUpText = pickUpText;
this.inventoryText = inventoryText;
}
}
const paper = new Item(
"Seven Days",
"Some kind of newspaper",
true,
`You pick up the paper and leaf through it looking for comics and ignoring the articles, just like everybody else does.`,
"You are carrying seven days, Vermonts Alt-Weekly"
);
const sign = new Item(
"Sign",
"Welcome to Burlington Code Academy! Come on up to the third floor. If the door is locked, use the code 12345",
false,
"",
"",
);
//Rooms
let mainSt = new Room(
"182 Main St.",
`You are standing on Main Street between Church and South Winooski.
There is a door here. A keypad sits on the handle.
On the door is a handwritten sign.`,
[sign],
['mainSt', 'foyer'])
let foyer = new Room(
'182 Main St. - Foyer',
`You are in a foyer. Or maybe it's an antechamber. Or a
vestibule. Or an entryway. Or an atrium. Or a narthex.
But let's forget all that fancy flatlander vocabulary,
and just call it a foyer. In Vermont, this is pronounced
"FO-ee-yurr".
A copy of Seven Days lies in a corner.`,
[paper],
['mainSt', 'roomThree'],
);
//Do we need a lookup table for [current].description to work? Marshall mentioned that you can't have the first
//key be a variable unless you use a lookup table to convert the string to an object by naming itself
const roomLookupTable = {
mainSt: mainSt,
foyer: foyer,
//roomThree: roomThree
}
const lookUpItems = {
paper: paper,
"seven days": paper,
sign: sign,
}
class Player {
constructor(currentState, playerInventory) {
this.currentState = currentState
this.playerInventory = playerInventory
}
get actions(actionToDo, item) {
return this[actionToDo] ? this.actionToDo(item) : `I do not know how to do ${actionToDo}`
}
look(itemName) {
console.log([currentState].description);
}
read(itemName){
let item = lookUpItems[itemName];
let currentRoom = roomLookupTable[player.currentState];
console.log({currentState: this.currentState}); //this is currently undefined... why?
console.log(roomLookupTable[player.currentState].inventory); //this is currently undefined... why?
console.log(currentRoom.roomInventory.includes(item));
if (player.playerInventory.includes(item) || currentRoom.roomInventory.includes(item)){
console.log(item.description);
}else{
console.log(`You dont have ${itemName}`);
}
getInput();
}
}
//player
let player = {
currentState: 'mainSt',
playerInventory: [],
//Will need to add functions for interacting - pickUp, drop, look, read, etc...
actions: {
look(){
console.log([currentState].description);
},
read(itemName){
let item = lookUpItems[itemName];
let currentRoom = roomLookupTable[player.currentState];
console.log({currentState: this.currentState}); //this is currently undefined... why?
console.log(roomLookupTable[player.currentState].inventory); //this is currently undefined... why?
console.log(currentRoom.roomInventory.includes(item));
if (player.playerInventory.includes(item) || currentRoom.roomInventory.includes(item)){
console.log(item.description);
}else{
console.log(`You dont have ${itemName}`);
}
getInput();
}
},
enter(code) {
if(code === '12345'){ //move to MainSt actions
console.log('Success! The door opens. You enter the foyer and the door shuts behind you.')
enterState('foyer');
} else {
console.log(`Bzzzzt! The door is still locked.`);
getInput();
}
},
take(itemName){
let item = lookUpItems[itemName];
let currentRoom = roomLookupTable[player.currentState];
if(item.canPickUp && currentRoom.inventory.includes(item)){
let index = currentRoom.roomInventory.indexOf(itemName); //finds the item in the roomInventory
currentRoom.roomInventory.splice(index, 1); //removes the item from the roomInventory
player.playerInventory.push(currentRoom.roomInventory[index]); //pushes the item to the playerInventory based on the index
console.log(`You took the ${itemName}`);
getInput();
}
// if(Object.keys(roomLookupTable[player.currentState].actions).includes(action + " " + itemName)){
// console.log(roomLookupTable[player.currentState].actions[action + " " + itemName]);
// getInput();
// } else if(roomLookupTable[player.currentState].roomInventory.includes(itemName)){
// console.log(player.playerInventory);
// let index = roomLookupTable[player.currentState].roomInventory.indexOf(itemName); //finds the item in the roomInventory
// player.playerInventory.push(roomLookupTable[player.currentState].roomInventory[index]); //pushes the item to the playerInventory based on the index
// roomLookupTable[player.currentState].roomInventory.splice(index, 1); //removes the item from the roomInventory
// console.log(`You took the ${itemName}`);
// getInput();
// } else {
// console.log(`I'm sorry I can't take the ${itemName}`);
// getInput();
// }
},
drop(itemName){
console.log(player.playerInventory);
if(player.playerInventory.includes(itemName)){
let index = player.playerInventory.indexOf(itemName);
roomLookupTable[player.currentState].roomInventory.push(player.playerInventory[index]);
player.playerInventory.splice(index, 1);;
console.log(`You dropped the ${itemName}`);
getInput();
} else {
console.log(`I'm sorry you can't drop the ${itemName}`);
getInput();
}
},
open(action, itemName) {
if(Object.keys(roomLookupTable[player.currentState].actions).includes(action + " " + itemName)){
console.log(roomLookupTable[player.currentState].actions[action + " " + itemName]);
getInput();
} else {
console.log(`I'm sorry I can't open the ${itemName}`);
getInput();
}
},
}
function enterState(newState) {
//console.log(`enterState with ${newState} as the argument`)
let validTransitions = roomLookupTable[player.currentState].canChangeTo;
if (validTransitions.includes(newState)) {
player.currentState = roomLookupTable[newState];
console.log(player.currentState.description);
getInput();
} else {
throw 'Invalid state transition attempted - from ' + player.currentState + ' to ' + newState;
}
}
function start() {
console.log("Please enter your commands as two words. For example 'open door' or 'read sign'.");
player.currentState = 'mainSt';
enterState('mainSt');
}
async function getInput() {
let input = await ask("What would you like to do?\n>_");
console.log(input);
let arrInput = input.toLowerCase().split(" ");
if(arrInput[1] === 'seven' && arrInput[2] === 'days'){
arrInput.push('seven days');
}
checkInput(arrInput[0], arrInput[arrInput.length-1], arrInput);
}
function checkInput(arg1, arg2, arrInput){
if(arg1 === 'i' || arg1 === 'inventory' || (arg1 === 'take' && arg2 === 'inventory')){
if(player.playerInventory.length < 1){
console.log("You have nothing.")
getInput();
} else {
console.log(`You have: ${player.playerInventory.join(" ")}`)
//console.log(player.playerInventory)
getInput();
}
}else if(Object.keys(player.actions).includes(arg1)){player.actions[arg1](arg1, arg2);
}else if(arg1 === 'read'){player.action.read(lookUpItems[arg2]);
}else if(arg1 === 'take'){player.action.take(lookUpItems[arg2]);
}else if(arg1 === 'open'){player.action.open(lookUpItems[arg2]);
}else if(arg1 === 'drop'){player.action.drop(lookUpItems[arg2]);
}else if(arg1 === 'look'){player.action.look();
}else{
console.log(`I'm sorry I don't know how to ${arrInput.join(" ")}`);
}
getInput();
}
start();
|
define([
'lib/easel',
'class/base/BaseObject',
'class/base/GameDefine'
], function(createjs,BaseObject,DEFINE) {
if (typeof createjs === 'undefined' ) {
createjs = window.createjs;
}
function SpriteSheetAsset() {
this.type = DEFINE.ASSET_TYPE.SPRITESHEET;
}
var p = createjs.extend(SpriteSheetAsset, BaseObject);
p.initalize = function(requestdata,result){
var spritemap = {
images : [ "assets/"+ requestdata.src ],
frames : {
width : requestdata.width,
height : requestdata.height
}
};
if(requestdata.hasOwnProperty("animations")){
spritemap.animations = requestdata.animations;
}
this.spritesheet = new createjs.SpriteSheet(spritemap);
}
createjs.SpriteSheetAsset = createjs.promote(SpriteSheetAsset, "BaseObject");
return SpriteSheetAsset;
});
|
const request = require('supertest');
const app = require('../index');
describe('/person/:id',()=>{
it('respond json person', done => {
request(app)
.get('/person/1')
.set('Accept', 'application/json')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, done);
});
})
describe('/father/:id_father',()=>{
it('respond json father', done => {
request(app)
.get('/father/1')
.set('Accept', 'application/json')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, done);
});
})
describe('/mother/:id_mother',()=>{
it('respond json mother', done => {
request(app)
.get('/mother/1')
.set('Accept', 'application/json')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, done);
});
})
describe('/child/:id_child',()=>{
it('respond json child', done => {
request(app)
.get('/child/#')
.set('Accept', 'application/json')
.expect('Content-Type', 'application/json; charset=utf-8')
.expect(200, done);
});
})
|
import App from './App'
import React from 'react'
import ReactDOM from 'react-dom'
import 'antd/dist/antd.less'; // or 'antd/dist/antd.less'
import memoryUntils from './utils/memoryUntils';
import storageUntils from './utils/storageUntils';
import {BrowserRouter} from 'react-router-dom';
//local中获取user
const user = storageUntils.getUser()
//将user赋值到内存中
memoryUntils.user = user
ReactDOM.render(
<BrowserRouter>
<App></App>
</BrowserRouter>,
document.getElementById('root'))
|
/**
* Created by pnfy on 2016/8/25.
*/
$(document).ready(function () {
setting();
});
/*$(document).ready(function () {
var nav = $("#nav").val();
if(nav == '基础信息') {
alert('ddd')
nav();
$("#nav_jcxx").css("color", "#DCD800");
$("#nav_jcxx").css("font-size", "21px");
}
});
function nav() {
alert('eee')
$(".con").css("color", "white");
$(".con").css("font-size", "18px");
}*/
$(window).resize(function(){
setting();
});
function setting() {
var w = $(window).width();
var h = $(window).height();
$(".header").css("width", w);
$(".header").css("height", "60px");
$(".body-left").css("width", "150px");
$(".body-left").css("height", h-60);
$(".body-right").css("width", w-150);
$(".body-right").css("height", h-60);
}
$(function(){
$('#ri_qi_1').date_input();
$('#ri_qi_2').date_input();
});
|
import { combineReducers } from 'redux';
import userReducer from './userReducer';
import stateReducer from './stateReducer';
import columnReducer from './columnReducer';
const rootReducer = combineReducers({
user: userReducer,
columns: columnReducer,
state: stateReducer,
});
export default rootReducer;
|
// @flow
/* **********************************************************
* File: test/utils/mica/parseDataPacket.spec.js
*
* Brief: Test the parsing functionality for arriving packets
*
* Authors: Craig Cheney
*
* 2017.09.20 CC - Document created
*
********************************************************* */
import { TimeEvent } from 'pondjs';
import {
parseDataPacket2,
twosCompToSigned,
sampleRateToPeriodCount,
channelObjToWord,
encodeStartPacket,
encodeStopPacket
} from '../../../app/utils/mica/parseDataPacket';
import {
CMD_START,
CMD_STOP
} from '../../../app/utils/mica/micaConstants';
import { channelArrayToObj } from '../../factories/factories';
import type { sensorParamType, sensorListType } from '../../../app/types/paramTypes';
const accId = 0x01;
const gyrId = 0x02;
/* Return an accelerometer */
function accFactory(): sensorParamType {
return {
name: 'Accelerometer',
active: true,
channels: {
'0': { active: true, name: 'X', offset: 0 },
'1': { active: false, name: 'Y', offset: 0 },
'2': { active: false, name: 'Z', offset: 0 },
},
scalingConstant: 0.004784999880939722,
gain: 0.5,
units: 'm/s^2',
sampleRate: 100,
dynamicParams: {
range: {
address: 15,
value: 3
},
bandwidth: {
address: 16,
value: 11
}
}
};
}
/* Return a gyroscope */
function gyrFactory(): sensorParamType {
return {
name: 'Gyroscope',
active: true,
channels: {
'0': { active: true, name: 'X', offset: 0 },
'1': { active: false, name: 'Y', offset: 0 },
'2': { active: false, name: 'Z', offset: 0 },
},
scalingConstant: 0.03406799957156181,
gain: 1,
units: 'rad/s',
sampleRate: 100,
dynamicParams: {
range: {
address: 15,
value: 0
}
}
};
}
/* Test suite */
describe('parseDataPacket.spec.js', () => {
describe('parseDataPacket', () => {
it('should parse a simple one value data packet', () => {
const tMSB = 0x8F;
const tLSB = 0x00;
const dMSB = 0xBF;
const dLSB = 0xB0;
const simplePacket = new Buffer([tMSB, tLSB, dMSB, dLSB]);
/* Parse the packet */
const accSensor = accFactory();
const { scalingConstant, channels, gain, sampleRate } = accSensor;
const periodLength = 1 / sampleRate;
const startTime = new Date().getTime();
const dataArray = parseDataPacket2(simplePacket, channels, periodLength, scalingConstant, gain, startTime);
/* Evaluate */
expect(dataArray.length).toBe(1);
const dataPoint = dataArray[0];
const timeStamp = dataPoint.toPoint()[0];
const sample = dataPoint.toPoint()[1];
/* Expected value */
const accValue = -9.847;
const timeDiff = -1.808; /* Milliseconds */
expect(sample).toBeCloseTo(accValue);
expect(timeStamp).toBe(Math.round(startTime + timeDiff));
expect(dataPoint.toJSON().data.X).toBeCloseTo(accValue);
});
it('should parse a three channel data packet', () => {
const tMSB = 0x8F;
const tLSB = 0x00;
const d1 = 0xBF;
const d12 = 0xBB;
const d2 = 0xFB;
const d3 = 0x40;
const d34 = 0x50;
const simplePacket = new Buffer([tMSB, tLSB, d1, d12, d2, d3, d34]);
const acc = accFactory();
acc.channels['0'].active = true;
acc.channels['1'].active = true;
acc.channels['2'].active = true;
/* Parse the packet */
const { scalingConstant, channels, gain, sampleRate } = acc;
const periodLength = 1 / sampleRate;
const startTime = new Date().getTime();
const dataArray = parseDataPacket2(simplePacket, channels, periodLength, scalingConstant, gain, startTime);
/* Evaluate */
expect(dataArray.length).toBe(1);
const dataPoint = dataArray[0];
const timeStamp = dataPoint.toPoint()[0];
/* Expected value */
const accValue = -9.847;
const timeDiff = -1.808; /* Milliseconds */
expect(timeStamp).toBe(Math.round(startTime + timeDiff));
expect(dataPoint.toJSON().data.X).toBeCloseTo(accValue);
expect(dataPoint.toJSON().data.Y).toBeCloseTo(accValue);
expect(dataPoint.toJSON().data.Z).toBeCloseTo(-accValue);
});
});
describe('Two Complement', () => {
/* Two's Complement */
it('twosCompToSigned returns the correct values', () => {
expect(twosCompToSigned(23, 8)).toEqual(23);
expect(twosCompToSigned(233, 8)).toEqual(-23);
expect(twosCompToSigned(128, 8)).toEqual(-128);
expect(twosCompToSigned(3840, 12)).toEqual(-256);
expect(twosCompToSigned(467, 12)).toEqual(467);
});
});
describe('Period Count', () => {
it('sampleRateToPeriodCount returns the correct values', () => {
let { msb, lsb } = sampleRateToPeriodCount(100000);
expect(msb).toEqual(0x00);
expect(lsb).toEqual(0x01);
({ msb, lsb } = sampleRateToPeriodCount(1000));
expect(msb).toEqual(0x00);
expect(lsb).toEqual(0x64);
({ msb, lsb } = sampleRateToPeriodCount(525));
expect(msb).toEqual(0x00);
expect(lsb).toEqual(0xBE);
({ msb, lsb } = sampleRateToPeriodCount(100));
expect(msb).toEqual(0x03);
expect(lsb).toEqual(0xE8);
({ msb, lsb } = sampleRateToPeriodCount(10));
expect(msb).toEqual(0x27);
expect(lsb).toEqual(0x10);
});
it('SampleRateToPeriodCount should clip very low sample rates', () => {
let { msb, lsb } = sampleRateToPeriodCount(1);
expect(msb).toEqual(0xFF);
expect(lsb).toEqual(0xFF);
({ msb, lsb } = sampleRateToPeriodCount(1.5));
expect(msb).toEqual(0xFF);
expect(lsb).toEqual(0xFF);
({ msb, lsb } = sampleRateToPeriodCount(2));
expect(msb).toEqual(0xC3);
expect(lsb).toEqual(0x50);
});
});
describe('channelObjToWord', () => {
it('Channel Array to word produces the correct result', () => {
expect(channelObjToWord(channelArrayToObj([]))).toEqual(0);
expect(channelObjToWord(channelArrayToObj([0]))).toEqual(1);
expect(channelObjToWord(channelArrayToObj([1]))).toEqual(2);
expect(channelObjToWord(channelArrayToObj([0, 1]))).toEqual(3);
expect(channelObjToWord(channelArrayToObj([2]))).toEqual(4);
expect(channelObjToWord(channelArrayToObj([0, 2]))).toEqual(5);
expect(channelObjToWord(channelArrayToObj([1, 2]))).toEqual(6);
expect(channelObjToWord(channelArrayToObj([0, 1, 2]))).toEqual(7);
});
});
describe('encodeStartPacket', () => {
/* Format: startCommand, pcMSB, pcLSB, sensorId, channels, numParams, params */
it('Return start packet for one sensor with no params', () => {
const accSensor = accFactory();
const accNoParam = { ...accSensor, dynamicParams: {} };
const sensorList: sensorListType = {};
sensorList[accId] = accNoParam;
const sampleRate = 100;
/* Result constants */
const msb = 0x03;
const lsb = 0xE8;
const sensorId = 0x01;
const channels = 0x01;
const numParams = 0x00;
/* Test */
expect(encodeStartPacket(sampleRate, sensorList)).toEqual([
CMD_START, msb, lsb, sensorId, channels, numParams
]);
});
it('Return start packet for one sensor with params', () => {
const accSensor = accFactory();
const accWithParam = { ...accSensor, channels: channelArrayToObj([0, 1]) };
const sensorList: sensorListType = {};
sensorList[accId] = accWithParam;
const sampleRate = 10;
/* Result constants */
const msb = 0x27;
const lsb = 0x10;
const sensorId = 0x01;
const channels = 0x03;
const numParams = 0x02;
const params = [15, 3, 16, 11];
/* Test */
expect(encodeStartPacket(sampleRate, sensorList)).toEqual([
CMD_START, msb, lsb, sensorId, channels, numParams, ...params
]);
});
it('Return start packet for two sensor with params', () => {
const accSensor = accFactory();
const gyrSensor = gyrFactory();
const acc = { ...accSensor, channels: channelArrayToObj([2]) };
const gyr = { ...gyrSensor, channels: channelArrayToObj([0, 2]) };
const sensorList: sensorListType = {};
sensorList[accId] = acc;
sensorList[gyrId] = gyr;
const sampleRate = 525;
const msb = 0x00;
const lsb = 0xBE;
/* Acc Result constants */
const aSensorId = 0x01;
const aChannels = 0x04;
const aNumParams = 0x02;
const aParams = [15, 3, 16, 11];
/* Gyr result constants */
const gSensorId = 0x02;
const gChannels = 0x05;
const gNumParams = 0x01;
const gParams = [15, 0];
/* Test */
expect(encodeStartPacket(sampleRate, sensorList)).toEqual([
CMD_START, msb, lsb,
aSensorId, aChannels, aNumParams, ...aParams,
gSensorId, gChannels, gNumParams, ...gParams
]);
});
it('Do not include inactive sensors', () => {
const accSensor = accFactory();
const gyrSensor = gyrFactory();
const acc = { ...accSensor, channels: channelArrayToObj([2]) };
const gyr = { ...gyrSensor, active: false };
const sensorList: sensorListType = {};
sensorList[accId] = acc;
sensorList[gyrId] = gyr;
const sampleRate = 525;
const msb = 0x00;
const lsb = 0xBE;
/* Acc Result constants */
const aSensorId = 0x01;
const aChannels = 0x04;
const aNumParams = 0x02;
const aParams = [15, 3, 16, 11];
/* Test */
expect(encodeStartPacket(sampleRate, sensorList)).toEqual([
CMD_START, msb, lsb,
aSensorId, aChannels, aNumParams, ...aParams
]);
});
it('Inactive sensors should return an empty array', () => {
const accSensor = accFactory();
const gyrSensor = gyrFactory();
const acc = { ...accSensor, active: false };
const gyr = { ...gyrSensor, active: false };
const sensorList: sensorListType = {};
const sampleRate = 525;
/* Create the sensor array */
sensorList[accId] = acc;
sensorList[gyrId] = gyr;
/* Test */
expect(encodeStartPacket(sampleRate, sensorList)).toEqual([]);
});
});
describe('Encode stop packet', () => {
it('Should return the correct stop packet', () => {
const sensorList: sensorListType = {};
expect(encodeStopPacket(sensorList)).toEqual([CMD_STOP]);
});
});
});
/* [] - END OF FILE */
|
loadProgression = function (userId, callback) {
var progressionList = [];
fetch("http://localhost:3000/groups").then(function (response) {
console.log("Progressions received. Status", response.status);
return response.json()
}).then(function (data) {
data.forEach(function (entry) {
if (entry.userId === userId) {
progressionList.push(new Progression(entry.progression, entry.id, entry.name, entry.userId));
}
});
callback(progressionList);
});
};
// testing userId 5967d6b8b91cd3039b3c57e3
|
// Basic
import React from 'react';
import ReactDOM from 'react-dom';
// Application
import App from './App';
// Render
ReactDOM.render(
<App />,
document.getElementById('root'));
|
const { Clutter, Gio, GObject, Shell, St } = imports.gi;
const PopupMenu = imports.ui.popupMenu;
const Me = imports.misc.extensionUtils.getCurrentExtension();
const helper = Me.imports.src.helper;
var MenuWindowItem = GObject.registerClass(
class MenuWindowItem extends PopupMenu.PopupBaseMenuItem {
_init(window) {
this.window = window;
this.app = helper.getWindowApp(this.window);
super._init(this.window.appears_focused ? {
style_class: 'popup-menu-window-focused',
} : {});
this.label = new St.Label({
text: this.window.get_title(),
style_class: 'popup-menu-window-title',
x_expand: true,
y_align: Clutter.ActorAlign.CENTER,
});
this.add_child(this.label);
this.label_actor = this.label;
this.closeButton = new St.Button({
child: new St.Icon({
icon_name: 'edit-delete-symbolic',
style_class: 'popup-menu-icon',
}),
style_class: 'popup-menu-button',
});
this.closeButton.connect('clicked', () => this.closeWindow());
this.add_child(this.closeButton);
this.connect('activate', () => this.focusWindow());
}
focusWindow() {
if (!this.window) return;
helper.focusWindow(this.window);
}
closeWindow() {
helper.closeWindow(this.window);
this.window = null;
this.app = null;
}
}
);
|
class Character {
constructor(hp, dmg, mana, status = "playing") {
this.hp = hp;
this.dmg = dmg;
this.mana = mana;
this.status = status;
}
dealDamage = (victim) => {
if (victim.hp <= 0) {
console.log("La cible est deja morte.");
} else {
console.log(
`${this.name} attaque ${victim.name} et lui inflige ${this.dmg} degats!`
);
victim.takeDamage(this.dmg);
}
};
takeDamage = (dmg) => {
if (this instanceof Fighter && this.shield == true) {
this.hp -= dmg - 2;
} else if (this instanceof Assassin && this.chargedSpecial === "charged") {
console.log("Ce personnage ne peut pas prendre de degats ce tour-ci");
} else {
this.hp -= dmg;
}
if (this.hp <= 0) {
console.log(`${this.name} est mort`);
this.status = "loser";
}
};
}
|
import '../classes.css'
import {addDeadlines, updateDeadlines} from "../../../actions/deadlines";
import {useDispatch} from "react-redux";
function Editdeadlines() {
const dispatch = useDispatch()
const addDeadline = () => {
let name = prompt('name ')
let type = prompt('type ')
let lesson = 9
let description = prompt('description ')
let deadline_time = prompt('deadline_time ')
let id = 9
dispatch(updateDeadlines(lesson,name, description, deadline_time, type, id))
}
return <form encType="multipart/form-data" action="" method="post">
{/*{% csrf_token %}*/}
<div className="flex-container">
<div className="col1">
<div className="subject-title">
<label for="id_name">Name:</label>
<input type="text" name="name" maxlength="20" required id="id_name" value="{{update_deadline.name}}"/>
</div>
</div>
<div className="col1">
<div className="deadline-time">
<label for="id_deadline_time">Deadline time:</label>
<input type="date" name="deadline_time" required id="id_deadline_time"
value="{{update_deadline.deadline_time}}"/>
</div>
</div>
<div className="col1">
<div className="lesson-check">
<label for="id_lesson">Lesson:</label>
<select name="lesson" required id="id_lesson">
<option disabled>Виберіть предмет</option>
{/*{% for lesson in get_lesson %}*/}
{/*<option value="{{ lesson.id }}">{{ lesson.name }}</option>*/}
{/*{% endfor %}*/}
</select>
</div>
</div>
<div className="col1">
<div className="group-check">
<label for="id_group">Group:</label>
<select name="group" required id="id_group">
<option disabled>Виберіть групу</option>
{/*{% for group in get_group %}*/}
{/*<option value="{{ group.id }}">{{ group.name }}</option>*/}
{/*{% endfor %}*/}
</select>
</div>
</div>
<div className="col1">
<div className="modal-add">
<button type="submit" name="button" onClick={addDeadline}>Add</button>
</div>
</div>
</div>
</form>
}
export default Editdeadlines
|
import {Col, Row} from 'react-native-easy-grid';
import {View} from 'react-native';
import {Text} from 'react-native-elements';
import PropTypes from 'prop-types';
import React from 'react';
import {useDerbyTheme} from '../../utils/theme';
export default function Scores({item, only}) {
const {colors, sizes} = useDerbyTheme();
let scoreIsSet = true;
if (isNaN(item.team_red_score) || isNaN(item.team_blue_score)) {
scoreIsSet = false;
}
if (!scoreIsSet) {
return (
<Col size={1} style={{alignItems: 'flex-end'}}>
<Text>-</Text>
</Col>
);
}
let teamRedScore = parseInt(item.team_red_score, 10);
let teamBlueScore = parseInt(item.team_blue_score, 10);
const winner =
teamRedScore > teamBlueScore
? 'team1'
: teamRedScore === teamBlueScore
? 'none'
: 'team2';
let firstTeamBgColor = colors.textMuted;
let firstTeamTextColor = colors.textMuted;
let secondTeamBgColor = colors.textMuted;
let secondTeamTextColor = colors.textMuted;
if (winner === 'team1') {
firstTeamBgColor = colors.backgroundSuccess;
firstTeamTextColor = colors.success;
secondTeamBgColor = colors.backgroundError;
secondTeamTextColor = colors.error;
}
if (winner === 'team2') {
firstTeamBgColor = colors.backgroundError;
firstTeamTextColor = colors.error;
secondTeamBgColor = colors.backgroundSuccess;
secondTeamTextColor = colors.success;
}
const cond =
item.team_red_score !== undefined && item.team_blue_score !== undefined;
let showRed = true;
let showBlue = true;
if (only === 'red') {
showRed = true;
showBlue = false;
}
if (only === 'blue') {
showRed = false;
showBlue = true;
}
return (
<>
{cond && (
<Col size={1.3} style={{alignItems: 'flex-end', borderColor: '0099ff'}}>
<Row style={{justifyContent: 'center'}}>
{showRed && (
<Col size={1}>
<View
style={{
borderColor: firstTeamBgColor,
borderWidth: 1,
width: 35,
height: 28,
borderRadius: 5,
justifyContent: 'center',
alignItems: 'center',
marginLeft: 5,
}}>
<Text
style={{
color: firstTeamTextColor,
fontSize: 13,
marginHorizontal: 5,
fontFamily: 'Rubik_300Light',
}}>
{item.team_red_score ? item.team_red_score : '-'}
</Text>
</View>
</Col>
)}
{showBlue && (
<Col size={1}>
<View
style={{
borderColor: secondTeamBgColor,
borderWidth: 1,
width: 35,
height: 28,
borderRadius: 5,
justifyContent: 'center',
alignItems: 'center',
marginLeft: 5,
}}>
<Text
style={{
color: secondTeamTextColor,
fontSize: 13,
marginHorizontal: 5,
fontFamily: 'Rubik_300Light',
}}>
{item.team_blue_score ? item.team_blue_score : '-'}
</Text>
</View>
</Col>
)}
</Row>
</Col>
)}
</>
);
}
Scores.propTypes = {
item: PropTypes.any,
only: PropTypes.string,
};
|
import React, { useState, useEffect } from 'react';
import MaterialTable from 'material-table';
import { AddProduct, DeleteProduct, UpdateProduct } from './utils/fetchData';
import columns from './utils/columnsTable';
function TableProducts() {
//hooks controla produtos da requisação
const [products, setProducts] = useState([]);
//Fazendo requisção ao endpoint (back-end)
useEffect(() => {
fetch('http://localhost:3001/')
.then((resp) => resp.json())
.then((resp) => setProducts(resp));
}, []);
return (
<div>
<MaterialTable
options={{
paging: false,
actionsColumnIndex: -1,
addRowPosition: 'first',
}}
title='Tabela Produtos'
data={products}
columns={columns}
editable={{
onRowAdd: (newRow) =>
new Promise((resolve, reject) => {
const updateTable = [...products, newRow];
//Salvando dados no back
AddProduct(newRow);
setProducts(updateTable);
resolve();
// console.log('add');
}),
onRowDelete: (selectedRow) =>
new Promise((resolve, reject) => {
const index = selectedRow.tableData.id;
const updatedRows = [...products];
//Salvando dados no back
DeleteProduct(selectedRow);
updatedRows.splice(index, 1);
//setTimeout ->
//espera o tempo de renderização da tabela (delay)
setTimeout(() => {
setProducts(updatedRows);
resolve();
// console.log('delete', selectedRow);
}, 2000);
}),
onRowUpdate: (updatedRow, oldRow) =>
new Promise((resolve, reject) => {
//Obten o index da linha
const index = oldRow.tableData.id;
//Obtendo a linha atualizada
const updatedRows = [...products];
updatedRows[index] = updatedRow;
//Salvando dados no back
UpdateProduct(updatedRow);
//setTimeout ->
//espera o tempo de renderização da tabela (delay)
setTimeout(() => {
setProducts(updatedRows);
resolve();
// console.log('update', updatedRow);
}, 2000);
}),
}}
/>
</div>
);
}
export default TableProducts;
|
$(document).ready(function() {
$('#persistentlocking input').change(function () {
var currentInput = $(this);
var name = currentInput.attr('name');
var isValid = true;
var app = '';
var value = '';
if (name === 'enable_lock_file_action') {
app = 'files';
if (this.checked) {
value = 'yes';
} else {
value = 'no';
}
} else {
app = 'core';
value = currentInput.val();
var minRange = currentInput.attr('min');
var maxRange = currentInput.attr('max');
// range validation (mainly for firefox) to prevent saving wrong values
if (minRange !== undefined && value < minRange) {
isValid = false;
}
if (maxRange !== undefined && value > maxRange) {
isValid = false;
}
}
if (isValid) {
OC.AppConfig.setValue(app, name, value);
}
// browser should take care of the visual indication if the value
// isn't in the range
});
});
|
const {Product} = require('../models');
// agregar paciente
exports.add = async (req, res, next) => {
try {
if (!req.body.name) {
res.status(400).json({ error: true, message: 'The name are required.' });
next();
}else{
data = req.body;
data.UserId = req.user.id;
// crear una revisión con los datos recibidos
await Product.create(data);
res.json({ message: 'The product was added.' });
}
} catch (error) {
console.error(error);
let errores=[];
if(error.errors){
errores = error.errors.map((item) => ({
campo: item.path,
error: item.message,
}))
}
res.status(400).json({
error: true,
message: 'Failed to add review for patient.',
errores,
});
next();
}
};
exports.listProductUserVendedor = async (req, res, next) => {
try {
const product = await Product.findAll({
where: { UserId: req.body.id, status: true, }
});
if(!product) {
res.tatus(404).json({message: 'Products product not found.'})
} else {
res.json(product);
}
} catch (error) {
console.error(error);
res.json({ message: 'Error reading products for seller' });
next();
}
};
exports.listReviewPatientManager = async (req, res, next) => {
try {
const review = await Review.findAll({
include: [ { model: User, required: true, }, { model: Patient, required: true } ],
});
if(!review) {
res.tatus(404).json({message: 'Patient review not found.'})
} else {
res.json(review);
}
} catch (error) {
console.error(error);
res.json({ message: 'Error reading review for patient' });
next();
}
};
// actualizar pacientes
exports.updatePatientArea = async (req, res, next) => {
try {
// obtener el registro de los pacientes desde la bd
const review = await Review.findByPk(req.params.id, {
where: { UserId: req.user.id, }
});
if (!review) {
res.status(404).json({ error:true, message: 'The review for patient was not found.'});
} else {
let newReview = req.body;
// actualizar en la bd
// procesar las propiedades que viene en body
Object.keys(newReview).forEach((propiedad) => {
review[propiedad] = newReview[propiedad];
});
review.status = false;
review.dateHourCompletion = new Date();
// guaradar cambios
await review.save();
return res.json({ message: 'The review for patient was updated.' });
}
} catch (error) {
console.log(error);
res.status(503).json({ error:true, message: 'Failed to update review for patient.' });
}
};
// actualizar pacientes
exports.updateOwn = async (req, res, next) => {
try {
// obtener el registro de los pacientes desde la bd
const review = await Review.findByPk(req.params.id, {
});
if (!review) {
res.status(404).json({ error:true, message: 'The review for patient was not found.'});
} else {
let newReview = req.body;
// actualizar en la bd
// procesar las propiedades que viene en body
Object.keys(newReview).forEach((propiedad) => {
review[propiedad] = newReview[propiedad];
});
// guaradar cambios
await review.save();
return res.json({ message: 'The review for patient was updated.' });
}
} catch (error) {
console.log(error);
res.status(503).json({ error:true, message: 'Failed to update review for patient.' });
}
};
// delete patient
exports.delete = async (req, res, next) => {
try {
const review = await Review.findByPk(req.params.id);
if (!review) {
res.status(403).json({ message: 'The review for patient was not found.'});
} else {
await review.destroy(); // review.destroy({ where: {id: req.params.id }});
res.json({ message: 'review for patient was deleted ' });
}
} catch (error) {
res.status(503).json({ message: 'Failed to delete review for patient. ' });
}
};
|
const Category = require("../models/categoryModel");
const Product = require("../models/productModel");
const Order = require("../models/orderModel");
exports.initialData = async (req, res) => {
const categories = await Category.find({}).exec();
const products = await Product.find({})
.select("_id name price quantity description imageUrl category")
.populate({ path: "category", select: "_id name" })
.exec();
const orders = await Order.Order.find({})
.populate("items.product", "name")
.exec();
res.status(200).json({
categories,
products,
orders,
});
};
|
const data = [
{
type: 'renderTitle',
content: 'EventBus'
},
{
type: 'renderHtml',
content: `
<text>利用发布/订阅的模式</text>
<text>注册一个对象【中间者】, 里面主要包含addEventListener 和 dispatch 两个函数。
每一次addEventListener时,会向总对象订阅一个事件 【一般包含作用域、事件名字、参数】
而执行dispatch 的时候, 就是在该对象中去寻找对应的事件,并执行</text>
<text>具体实践,在vue 中使用eventbus</text>
`
},
{
type: 'renderJS',
content: `
// 创建Index.vue 包含两个子组件
<template>
<div>
<click-child></click-child>
<show-child></show-child>
</div>
</template>
<script>
import ClickChild from './ClickChild.vue'
import ShowChild from './ShowChild.vue'
export default {
name: 'event-bus' ,
components:{ClickChild,ShowChild},
}
</script>
`
},
{
type: 'renderSubTitle',
content: '一、利用vue自身的$emit $on '
},
{
type: 'renderHtml',
content: `
<text>直接创建一个vue 实例, 可以利用实例的$emit $on 方法直接进行组件间的交互</text>
<text>平时组件内使用的this.$emit 方法, this指向的是vm 实例, 所以其实本质是一样的</text>
<codeBlock>
// bus.js 文件
<code>import Vue from 'vue'</code>
<code>export const EventBus = new Vue()</code>
// click-child组件
<code>EventBus.$emit('click')</code>
// show-child组件
<code>EventBus.$on('click', () => {} )</code>
</codeBlock>
`
},
{
type: 'renderSubTitle',
content: '二、全局的事件总线 -- 发布/订阅方法 , '
},
{
type: 'renderHtml',
content: `
<text> 相比于前者,只是把EventBus 创建的实例放到了 Vue的原型上</text>
<text>这样就可以在全局通过this.$bus来直接访问 事件总线的实例, 避免各处引用bus.js 文件的弊端</text>
<codeBlock>
<pre><code>
Object.defineProperties(Vue.prototype, {
$bus: {
get: function () {
return EventBus
}
}
})
</code></pre>
</codeBlock>
`
},
{
type: 'renderSubTitle',
content: '三、原生实现 '
},
{
type: 'renderJS',
content: `
// 在Index.vue 中引入文件 import './eventBus'
// 核心文件 eventBus.js
import Vue from 'vue'
var factory = function (){
var EventBusClass = {}
EventBusClass = function () {
this.listeners = {}
}
EventBusClass.prototype = {
addEventListener: function(type, callback, scope) {
// arguments 是伪数组 无法直接调用slice方法
// 利用 call 将Array.prototype.slice 方法作用域arguments
// 而slice方法会返回一个新的数组
// 所以变相将arguments 转化成了一个具有实例方法的数组 【本质是生成了新的数组】
var args = Array.prototype.slice.call(arguments)
args = args.length > 3 ? args.slice(3) : []
if(typeof this.listeners[type] != "undefined") {
this.listeners[type].push({scope:scope, callback:callback, args:args});
} else {
this.listeners[type] = [{scope:scope, callback:callback, args:args}];
}
},
removeEventListener: function(type, callback, scope) {
var curListeners = this.listeners[type]
if(typeof curListeners != "undefined") {
var len = this.listeners[type].length;
var newArray = [];
for(var i=0; i<len; i++) {
var listener = this.listeners[type][i];
if(listener.scope != scope || listener.callback != callback) {
newArray.push(listener)
}
}
this.listeners[type] = newArray;
}
},
dispatch: function(type) {
var args = Array.prototype.slice.call(arguments)
var curListener = this.listeners[type]
if(typeof curListener != "undefined") {
var listeners = curListener.slice();
for(var i=0; i<listeners.length; i++) {
var listener = listeners[i];
if(listener && listener.callback) {
var concatArgs = args.slice(1).concat(listener.args);
listener.callback.apply(listener.scope, concatArgs);
}
}
}
},
}
var EventBus = new EventBusClass();
return EventBus;
}
var EventBus = factory()
Object.defineProperties(Vue.prototype, {
$bus: {
get: function () {
return EventBus
}
}
})
`
},
{
type:'renderJS',
content:`
// showChild 子组件
mounted() {
// 由于this.$bus 注册到了全局 所以可以直接使用addEventListener, 注册自定义事件
this.$bus.addEventListener('click', (e, data) => {
console.log(e, 'clickme')
})
}
`
},
{
type:'renderJS',
content:`
// clickChild 子组件
methods:{
handleClick(item){
this.$bus.dispatch('click', item)
}
}
`
},
{
type: 'renderHtml',
content: `<text> 注: 虽然尚未使用过vue1.0, 但是查看资料说,vue1.0 中组件的通信主要通过vm.dispatch 沿父链向上传播, 用vm.$broadcast 向下广播</text>`
}
]
export default data
|
const Sequelize = require("sequelize");
const dbConfig = require("../config/database");
// IMPORT MODELS
const Producer = require("../models/Producer");
const Farms = require("../models/Farms");
const dbConnect = new Sequelize(dbConfig);
Producer.init(dbConnect);
Farms.init(dbConnect);
Producer.associate(dbConnect.models);
Farms.associate(dbConnect.models);
module.exports = dbConnect;
|
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { Link } from "react-router-dom";
import Banner from "../../assets/banner.svg";
export const Worker = styled.div`
position: relative;
margin: 10px;
background: white;
width: calc(50% - 10px - 1rem);
height: max-content;
& > * {
display: inline-block;
}
${breakpoint('mobile', 'desktop')`
width: calc(100% - 10px - 1rem);
`}
`;
export const InfoWrapper = styled.div`
display: flex;
align-items: center;
position: relative;
width: 100%;
`;
export const SkillsWrapper = styled.div`
margin-bottom: .75rem;
`;
export const WorkerInfo = styled.div`
padding-left: 10px;
font-family: "resagokrregular";
display: flex;
align-items: center;
position: relative;
flex-direction: column;
margin: 0 1.5rem;
width: 100%;
box-sizing: border-box;
`;
export const WorkerBio = styled(WorkerInfo)`
width: auto;
`;
export const InfoName = styled.p`
font-size: .9em;
color: rgb(22, 28, 36);
margin-bottom: 0;
white-space: nowrap;
`;
export const InfoEmail = styled.p`
font-size: .8em;
margin: 0;
color: rgb(57, 59, 61);
white-space: nowrap;
`;
export const InfoBio = styled.p`
font-size: .75em;
text-align: left;
color: rgb(57, 59, 61);
position: relative;
`;
export const InfoSkillTitle = styled(InfoBio)`
font-size: .8em;
font-weight: bolder;
margin: 0;
text-align: center;
`;
export const InfoSkill = styled(InfoBio)`
display: inline-block;
padding: 0 1.5rem;
margin-top: 0;
margin-bottom: 0;
&::after {
content: "•";
position: absolute;
right: 0;
font-size: 1rem;
}
&:last-child {
&::after {
content: "";
}
}
`;
export const WorkerButtons = styled.div`
position: absolute;
z-index: 50;
right: 0;
top: 0;
height: 40px;
display: flex;
align-items: center;
`;
const Button = `
display: inline-flex;
align-items: center;
justify-content: center;
width: 50px;
height: 50px;
margin-left: 5px;
&:hover {
cursor: pointer;
color: white;
}
`;
export const EditButton = styled(Link)`
${Button}
color: ${props => props.theme.lightGrey}
`;
export const DeleteButton = styled.div`
${Button}
color: ${props => props.theme.lightGrey}
`;
export const BgImage = styled(Banner)`
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 40px;
`;
export const ProfileImage = styled.img`
border-radius: 50%;
top: 15px;
z-index: 10;
position: relative;
height: 65px;
width: 65px;
border: 4px solid white;
`;
export const Divider = styled.p`
position: relative;
display: block;
margin: .5rem .5rem 0;
text-align: left;
width: 100%;
font-size: .8rem;
color: ${props => props.theme.darkBlue};
i {
margin: 0 .5rem;
font-size: .8rem;
${props => props.isOpened && `
transform: rotate(180deg);
`}
}
&::after {
content: "";
height: 1px;
background: grey;
width: calc(100% - 6.5rem);
position: absolute;
top: 50%;
transform: scaleY(.4);
opacity: .4;
}
&:hover {
cursor: pointer;
}
`;
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var request = require('request');
var Recipe = require('./models/recipe.js');
var mongoose = require('mongoose');
var cors = require('cors');
//mongoose.connect('mongodb://recipe:nutrilicious@ds033699.mongolab.com:33699/recipe_site');
var MongoURI = process.env.MONGO_URI || 'mongodb://localhost/recipes';
mongoose.connect(MongoURI, function(err, res) {
if (err) {
console.log('ERROR connecting to: ' + MongoURI + '. ' + err);
} else {
console.log('MongoDB connected successfully to ' + MongoURI);
}
});
// var corsOptions = {
// methods: ['GET', 'PUT', 'POST'],
// origin: 'http://localhost:000/',
// credentials: true
// };
//app.use(cors(corsOptions))
app.use(cors());
app.use(bodyParser.json());
app.use(jsonParser);
app.get('/recipes', function(req, res) {
Recipe.find({}, function(err, recipes) {
if (err) {
res.send(err);
} else {
res.json(recipes);
}
})
});
app.get('/recipes/:recipeId', function(req, res) {
var recipeId = req.params.recipeId;
Recipe.find({
_id: recipeId
}, function(err, recipe) {
if (err) {
res.send(err);
} else {
res.json(recipe);
}
})
});
app.get('/recipes/nutrition/:nutritionPick', function(req, res) {
var nutritionPick = req.params.nutritionPick;
if (nutritionPick === "highFat") {
Recipe.find({
percentFat: {
$gte: 35
}
}, function(err, recipes) {
if (err) {
res.send(err);
} else {
res.json(recipes);
}
})
} else if (nutritionPick === "highProtein") {
Recipe.find({
percentProtein: {
$gte: 25
}
}, function(err, recipes) {
if (err) {
res.send(err);
} else {
res.json(recipes);
}
})
} else if (nutritionPick === "highCarbohydrates") {
Recipe.find({
percentCarbohydrates: {
$gte: 55
}
}, function(err, recipes) {
if (err) {
res.send(err);
} else {
res.json(recipes);
}
})
} else if (nutritionPick === "lowFat") {
Recipe.find({
percentFat: {
$lte: 35
}
}, function(err, recipes) {
if (err) {
res.send(err);
} else {
res.json(recipes);
}
})
} else if (nutritionPick === "lowProtein") {
Recipe.find({
percentProtein: {
$lte: 10
}
}, function(err, recipes) {
if (err) {
res.send(err);
} else {
res.json(recipes);
}
})
} else if (nutritionPick === "lowCarbohydrates") {
Recipe.find({
percentCarbohydrates: {
$lte: 45
}
}, function(err, recipes) {
if (err) {
res.send(err);
} else {
res.json(recipes);
}
})
}
// Recipe.find({
// percentFat: {
// $gte: 34
// }
// }, function(err, recipes) {
// if (err) {
// res.send(err);
// } else {
// res.json(recipes);
// }
// })
});
var server = app.listen(process.env.PORT || 3000);
|
import React from 'react'
import moment from 'moment'
export {
Accountability,
DailyExpense,
calculateTotalDailyExpenses,
calculateFreePerDay,
calculateTotalAccountability,
displayRemainingDays,
displayDaysFromInit,
displayCurrency,
displayDays,
calculateAccountability,
applyAccountability
}
const accountabilitiesType = {
substraction: (price, money) => {
return price
},
percentage: (price, money) => price / 100 * money
}
function Accountability (money) {
return (acc) => (
<li key={acc.id}>
<strong>{ acc.label }</strong>: { calculateAccountability(acc, money) }
</li>
)
}
function DailyExpense (amount) {
return (expense, index) => (
<li key={index}>
{expense.label}: { displayCurrency(expense.amount) }
</li>
)
}
function calculateTotalDailyExpenses (dailyExpenses) {
return dailyExpenses.reduce((acc, exp) => {
return acc + exp.amount
}, 0)
}
function calculateFreePerDay ({
accountabilitiesTotal,
money,
circleDays,
circleInitiatedAt,
currentTime,
dailyExpensesTotal
}) {
const accountabilityPerDay = accountabilitiesTotal / circleDays
const moneyPerDay = money / circleDays
const a = moment(circleInitiatedAt)
.add(circleDays, 'days')
.diff(moment(currentTime), 'days')
const totalDailyPerDay = dailyExpensesTotal / a
return moneyPerDay - accountabilityPerDay - totalDailyPerDay
}
function calculateTotalAccountability (accountabilities, money) {
const total = accountabilities.reduce((acc, actb) => {
return acc + applyAccountability(actb.type, actb.perCircle, money)
}, 0)
return total
}
function displayRemainingDays (circleDays) {
return moment.duration().add(circleDays, 'days').humanize(true)
}
function displayDaysFromInit ({ currentTime, circleInitiatedAt }) {
const now = moment(currentTime)
const init = moment(circleInitiatedAt)
const minutes = now.diff(init, 'seconds')
return moment.duration().subtract(
minutes, 'seconds'
).humanize()
}
function displayCurrency (amount) {
return (amount / 100).toLocaleString('pt-BR', {
style: 'currency',
currency: 'BRL'
})
}
function displayDays (days) {
return days > 1 ? days + ' days' : days + ' day'
}
function calculateAccountability (acc, money) {
const amount = applyAccountability(acc.type, acc.perCircle, money)
return displayCurrency(amount)
}
function applyAccountability(type, circle, money) {
const apply = accountabilitiesType[type]
return apply(circle, money)
}
|
export function msgScroll() {
window.onload = roll(30);
}
function roll(t) {
var ul1 = document.getElementById("child1");
var ul2 = document.getElementById("child2");
var ulbox = document.getElementById("parent");
ul2.innerHTML = ul1.innerHTML;
ulbox.scrollTop = 0; // 开始无滚动时设为0
var timer = setInterval(rollStart, t); // 设置定时器,参数t用在这为间隔时间(单位毫秒),参数t越小,滚动速度越快
// 鼠标移入div时暂停滚动
ulbox.onmouseover = function () {
clearInterval(timer);
}
// 鼠标移出div后继续滚动
ulbox.onmouseout = function () {
timer = setInterval(rollStart, t);
}
}
// 开始滚动函数
function rollStart() {
// 上面声明的DOM对象为局部对象需要再次声明
var ul1 = document.getElementById("child1");
var ul2 = document.getElementById("child2");
var ulbox = document.getElementById("parent");
// 正常滚动不断给scrollTop的值+1,当滚动高度大于列表内容高度时恢复为0
if (ulbox.scrollTop >= ul1.scrollHeight) {
ulbox.scrollTop = 0;
} else {
ulbox.scrollTop++;
}
}
|
'use strict';
// TODO separate into different files
window.onload = function() {
var groupOnData = JSON.parse(localStorage.getItem('groupOnData'));
var address = JSON.parse(localStorage.getItem('inputAddress'));
var dealsContainer = $('#deals-container');
var dropdown = $('#dropdown1');
var modalSection = $('#modals-section');
var allDealsButton = $('#all-deals');
var cards = new GroupOnCards(groupOnData, address);
cards.createDropdown(dropdown);
cards.createHorizontalCards(dealsContainer, modalSection);
cards.allDeals(allDealsButton);
$(`.modal-trigger`).leanModal();
// TODO find OOP place for this
$(document).on('click', '.modal-trigger', function() {
var uuid = this.getAttribute('href').slice(1);
var modalMap = document.getElementById(`map\&${uuid}`);
var curCoord;
$(modalMap).css('height', '400px');
$(modalMap).css('width', '100%');
// var test = document.createElement('p');
console.log(modalMap);
for (let card of cards.data) {
if (card.uuid === uuid) {
curCoord = {
lat: card.lat,
lng: card.lng
};
}
}
initMap(curCoord, address, modalMap);
});
};
// TODO find OOP place for this
function initMap(coordDeal, address, modalElement) {
var directionsRequest = {
origin: new google.maps.LatLng(coordDeal.lat, coordDeal.lng),
destination: new google.maps.LatLng(address.geometry.location.lat, address.geometry.location.lng),
travelMode: 'DRIVING'
};
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var mapCenter = new google.maps.LatLng((coordDeal.lat + address.geometry.location.lat) / 2, (coordDeal.lng + address.geometry.location.lng) / 2);
var map = new google.maps.Map(modalElement, {
zoom: 12,
center: mapCenter
});
directionsDisplay.setMap(map);
calcAndDisplayRoute(directionsService, directionsDisplay, directionsRequest);
}
// TODO find OOP place for this
function calcAndDisplayRoute(directionsService, directionsDisplay, directionsRequest) {
directionsService.route(directionsRequest, function(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
}
});
}
|
// import { stringify } from 'qs';
import { get, post } from '../utils/request';
export async function find(params) {
return post('/admin/api/find_reaction_list', params);
}
export async function detail(_id) {
return get(`/admin/api/detail_reaction/${_id}`);
}
export async function update(params) {
return post('/admin/api/update_reaction', params);
}
export async function remove(_id) {
return get(`/admin/api/remove_reaction/${_id}`);
}
export async function add(params) {
return post('/admin/api/add_reaction', params);
}
|
import Vue from 'vue'
import Vuex from 'vuex'
import router from './router'
import App from './App.vue'
import store from './store'
//import {actions, getters, mutations, state} from "./store/movies.module.js";
import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
//import axios from 'axios';
Vue.config.productionTip = false; // <- utile? créé automatiquement par webstorm
Vue.use(Vuex);
Vue.use(BootstrapVue);
//export const store = new Vuex.Store(auth);
new Vue({
store, //instancie store
router,
/*HTTP: axios.create({
baseURL: `http://localhost:8080/authentication/authenticate`,
timeout: 1000,
headers: {
//Authorization: 'Bearer {token}'
}
}),*/
render: h => h(App),
}).$mount('#app');
|
const createElement = (tag, {
href,
innerHTML,
dataset,
className
} = {}) => {
const element = document.createElement(tag);
element.innerHTML = innerHTML || '';
element.href = href;
if (className) {
className.forEach(item => element.classList.add(item));
}
if (dataset) {
for (const key in dataset) {
element.dataset[key] = dataset[key];
}
}
return element;
};
export {createElement}
|
/**
* Created by Taoxinyu on 2015/10/27.
*/
var MarketTemplate={
CouponListTemp:function(data){
var Couponlistdom='<div class="cus_info_div" id="'+data.id+'">'+
'<div class="wid20 fl khxx pad_l20">'+
'<div class="customer_info">'+
'<div class="cus_name" title="'+data.title+'">'+data.title+'</div>'+
'</div>'+
'</div>'+
'<div class="wid15 fl">'+
'<div class="coupon_lx">'+data.type+'/'+CheckCouponType(data.type,data.amount)+'</div>'+
'<div class="coupon_jz">'+'最低消费:¥'+data.type_extend_value+'</div>'+
'</div>'+
'<div class="wid15 fl">'+
'<div class="lqfs">'+'每人'+data.receive_limit+'张'+'</div>'+
'<div class="sykc">'+'库存:'+data.inventory+'</div>'+
'</div>'+
'<div class="wid20 fl">'+
'<div>'+data.start_time+'至'+'</div>'+
'<div>'+data.end_time+'</div>'+
'</div>'+
'<div class="wid10 fl pad12 tc">'+data.received_num+'</div>'+
'<div class="wid8 fl pad12 tc">'+data.used_num+'</div>'+
'<div class="wid12 fl tc rel pad12 hover_con">'+
'<span class="coupon_bianji">编辑</span>'+
'<span class="fenge">|</span>'+
'<span class="coupon_shanchu">删除</span>'+
'<span class="fenge">|</span>'+
'<span class="coupon_tuiguang">推广</span>'+
'<div class="preview_qrcode_con dis">'+
'<div class="m_qrcode_tab">' +
'<ul class="service_tabcon_ul m_qrcode_ul">' +
'<li class="on">'+ '独立优惠券' +'</li>'+
'<li>'+ '商品页上层显示' +'</li>'+
'<div class="cle"></div>'+
'</ul>'+
'</div>'+
'<div class="market_qrcode_con">' +
'<div class="qrcode_img_con">'+
'<span static_url="'+FormatUrl(data.coupon_url)+'" id="'+data.id+"url1"+'"'+'></span>'+
'</div>'+
'<div class="basic_info_line">'+
'<span class="info_lab ver_top">'+
'<span class="ver_top f12">独立优惠券链接:</span>'+
'</span>'+'</br>'+
'<input type="text" style="width:100px;" class="info_text static_url" value="'+ FormatUrl(data.coupon_url) +'">'+
'<input type="button" static_url="'+FormatUrl(data.coupon_url)+'" data-clipboard-text="'+FormatUrl(data.coupon_url)+'" class="cope_qrcode_btn" value="复制"/>'+
'</div>'+
'</div>'+
'<div class="market_qrcode_con dis">' +
'<div class="qrcode_img_con">'+
'<span static_url="'+FormatUrl(data.coupon_product_url)+'" id="'+data.id+"url2"+'"'+'></span>'+
'</div>'+
'<div class="basic_info_line">'+
'<span class="info_lab ver_top">'+
'<span class="ver_top f12">商品页上层显示链接:</span>'+
'</span>'+'</br>'+
'<input type="text" style="width:100px;" class="info_text static_url" value="'+ FormatUrl(data.coupon_product_url) +'">'+
'<input type="button" static_url="'+FormatUrl(data.coupon_product_url)+'" data-clipboard-text="'+FormatUrl(data.coupon_product_url)+'" class="cope_qrcode_btn" value="复制">'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'<div class="cle"></div>'+
'</div>';
$("#coupon_table_container").append(Couponlistdom);
}
};
//判断是否为折扣券,是的话截掉0和小数点
function CutAmountValue(value){
var cutvalue='';
var valkv=value.toString().split("0");
if(valkv[0].substring(valkv[0].length-1)==='.'){
var spval=valkv[0].split('.');
cutvalue=spval[0];
}
else{
cutvalue=valkv[0];
}
return cutvalue;
}
function CheckCouponType(type,value){
var val='';
if(type=='折扣券'){
var cutval=CutAmountValue(value);
val=cutval+'折';
}
else{
val=value+'元';
}
return val;
}
//传输数据格式
var CouponData={
limit:'20',
offset:'0',
order:'desc',
search:''
}
//渲染优惠券列表逻辑
function RanderCouponList(result){
if(result.status!=1){
layer.msg(result.msg);
return;
}
if(result.data.length==0){
$("#coupon_none").show();
}
else{
$("#coupon_none").hide();
}
for(var i=0;i<result.data.length;i++){
MarketTemplate.CouponListTemp(result.data[i]);
}
$("#total_coupon").text(result.total);
var total_num=Math.ceil(result.total/$("#couponlb_pagenum").text());
if(total_num===0){
total_num=1;
}
$("#coupon_tot_page").text(total_num);
}
//统一请求后端的查询优惠券数据
function CouponPostData(){
CouponData.limit=$("#couponlb_pagenum").text();
CouponData.offset=($("#coupon_now_page").text()-1)*CouponData.limit;
CouponData.search=$("#coupon_select").val();
return JSON.stringify(CouponData);
}
//清空优惠券列表
function ClearCouponList(){
$("#coupon_table_container").children(".cus_info_div").remove();
}
//查询优惠券信息服务器请求
function CouponServerRequest(flag){
if(!flag){
$("#coupon_now_page").text("1");
}
AjaxPostData("../Home/Discount/queryDiscount",CouponPostData(),function(result){
ClearCouponList();
RanderCouponList(result);
});
}
//删除优惠券信息
function DelCouponServerRequest(id){
var postdata={
discount_id:id
};
var jpostdata=JSON.stringify(postdata);
AjaxPostData("../Home/Discount/delDiscount",jpostdata,function(result){
if(result.status!=1){
layer.alert(result.msg);
return;
}
CouponServerRequest();
});
}
function FormatUrl(url){
if(url==null){
url="";
}
return url;
}
$(function($){
AddNaviListClass("yhq");
CouponServerRequest();
$("#coupon_select_btn").bind("click",function(){
if(!illegalChar($("#coupon_select").val())){
ShowMsgTip($("#coupon_select"),"输入中含有特殊字符!");
$("#coupon_select").val('');
return;
}
CouponServerRequest();
});
$("#coupon_select").keydown(function(e){
if((e.keyCode || e.which)==13){
$("#coupon_select_btn").trigger("click");
}
});
$("#coupon_limit li").bind("click",function(){
var nlimit=$(this).text();
$("#couponlb_pagenum").text(nlimit);
$("#coupon_limit").hide();
CouponServerRequest();
});
$("#coupon_pre").bind("click",function(){
var nowpage=parseInt($("#coupon_now_page").text());
nowpage-=1;
if(nowpage<=0){return;}
else{
$("#coupon_now_page").text(nowpage);
CouponServerRequest(1);
}
});
$("#coupon_next").bind("click",function(){
var nowpage=parseInt($("#coupon_now_page").text());
var totalpage=parseInt($("#coupon_tot_page").text());
nowpage+=1;
if(nowpage>totalpage){
return;
}
else{
$("#coupon_now_page").text(nowpage);
CouponServerRequest(1);
}
});
$("#coupon_table_container").delegate("span.coupon_shanchu","click",function(){
var nid=$(this).parents(".cus_info_div").attr("id");
if(!confirm("确定要删除此优惠券?")){
return;
}
DelCouponServerRequest(nid);
});
$("#coupon_table_container").delegate("span.coupon_bianji","click",function(){
var nid=$(this).parents(".cus_info_div").attr("id");
window.location.href="../Home/Coupon?discount_id="+nid;
});
$("#create_coupon_btn").bind("click",function(){
window.location.href='../Home/Coupon';
});
$("#coupon_table_container").delegate("span.coupon_tuiguang","mouseenter",function(){
//var good_id = $(this).parents(".cus_info_div").attr("id");
var id = $(this).parents(".cus_info_div").attr("id");
var url1=$("#"+id+"url1").attr("static_url");
var url2=$("#"+id+"url2").attr("static_url");
$("#"+id+"url1").text("");
$("#"+id+"url2").text("");
if(url1!=""){
jQuery("#"+id+"url1").qrcode({width: 108,height: 108,text: url1});
}
if(url2!=""){
jQuery("#"+id+"url2").qrcode({width: 108,height: 108,text: url2});
}
$(this).parent().children(".preview_qrcode_con").show();
});
$("#coupon_table_container").delegate(".cope_qrcode_btn","click",function(){
var static_url = $(this).attr("static_url");
if(static_url!="" && static_url!=null){
new Clipboard('.cope_qrcode_btn');
layer.msg("复制成功!");
}
});
$("#coupon_table_container").delegate(".hover_con","mouseleave",function(){
$(this).find(".preview_qrcode_con").hide();
});
$("#coupon_table_container").delegate(".m_qrcode_ul li","click",function(){
$(this).parent().children().removeClass("on");
$(this).addClass("on");
var nindex=$(this).index();
$(this).parents(".preview_qrcode_con").children(".market_qrcode_con").hide();
$(this).parents(".preview_qrcode_con").children(".market_qrcode_con").eq(nindex).show();
})
});
|
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
// SPECIAL case, versal-sdk has require in the env but stil need Browser globals
// Browser globals (root is window)
root.BaseCompMethods = factory();
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.BaseCompMethods = factory();
}
}(this, function () {
var _extend;
if(typeof _ === 'function' && _.extend) {
_extend = _.extend;
} else {
//straight from underscore
//http://underscorejs.org/docs/underscore.html
_extend = function(obj) {
Array.prototype.forEach.call(Array.prototype.slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
}
var BaseMethods = {
propertiesObject : {
editable: {
get: function(){ return this.getAttribute('editable') === 'true'; }
},
env: {
get: function(){ return this.readAttributeAsJson('data-environment'); }
},
config: {
get: function(){ return this.readAttributeAsJson('data-config'); }
},
userstate: {
get: function(){ return this.readAttributeAsJson('data-userstate'); }
}
},
trigger: function(eventName, data, options) {
//set up default options to be overwritten
var eventObj = {
type: 'defaultEvent',
bubbles: true,
cancelable: false,
detail: {}
};
//add eventName and data
_extend(eventObj, {
type: '' + eventName,
detail: data
});
//add options
_extend(eventObj, options);
//fire away
this.dispatchEvent( new CustomEvent(eventName, eventObj) );
},
on: function(){
return this.addEventListener.apply(this, arguments);
},
off: function(){
return this.removeEventListener.apply(this, arguments);
},
readAttributeAsJson : function(name) {
if(!this.hasAttribute(name)) { return undefined; }
return JSON.parse(this.getAttribute(name));
}
};
// Just return a value to define the module export.
// This example returns an object, but the module
// can return a function as the exported value.
return BaseMethods;
}));
|
import {
Box,
Paper,
Table,
TableCell,
TableContainer,
TableHead,
TableRow,
Typography,
} from '@material-ui/core';
import { parseSecondsToDuration } from '../shared/functions';
import { styles } from '../theme';
export const HistoryItem = ({ data }) => {
return (
<Paper
style={{
maxWidth: 500,
padding: 20,
borderRadius: 10,
flexGrow: 1,
}}
>
<Typography variant="h6">
PeerPrepped with {data.partnerName || 'Guest'}!
</Typography>
<TableContainer component={Box}>
<Table>
<TableHead>
<TableRow hover>
<TableCell
padding="none"
color="primary"
style={{ width: 100, borderBottom: 'none', color: styles.BLUE }}
>
Date:
</TableCell>
<TableCell
colSpan="5"
align="right"
padding="none"
style={{ width: 400, borderBottom: 'none', color: styles.BLUE }}
>
{new Date(data.createdAt).toLocaleString('en-us', {
day: 'numeric',
month: 'long',
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
})}
</TableCell>
</TableRow>
<TableRow hover>
<TableCell
padding="none"
color="primary"
style={{ borderBottom: 'none', color: styles.BLUE }}
>
Question:
</TableCell>
<TableCell
colSpan="5"
align="right"
color="primary"
padding="none"
style={{ borderBottom: 'none', color: styles.BLUE }}
>
<Table
component="a"
target="_blank"
padding="none"
rel="noreferrer"
href={`https://leetcode.com/problems/${data.leetcodeSlug}`}
>
{data.questionName}
</Table>
</TableCell>
</TableRow>
<TableRow hover>
<TableCell
padding="none"
color="primary"
style={{ borderBottom: 'none', color: styles.BLUE }}
>
Time Taken:
</TableCell>
<TableCell
colSpan="5"
align="right"
color="primary"
padding="none"
style={{ borderBottom: 'none', color: styles.BLUE }}
>
{parseSecondsToDuration(data.timeTaken)}
</TableCell>
</TableRow>
<TableRow hover>
<TableCell
padding="none"
color="inherit"
color="primary"
style={{ borderBottom: 'none', color: styles.BLUE }}
>
Status:
</TableCell>
<TableCell
colSpan="5"
align="right"
color="primary"
padding="none"
style={{ borderBottom: 'none', color: styles.BLUE }}
>
{data.isCompleted ? 'Completed' : 'Forfeited'}
</TableCell>
</TableRow>
</TableHead>
</Table>
</TableContainer>
</Paper>
);
};
|
const form = document.getElementById('formFashion');
let isWholesale = false;
let wholesaleElem = document.getElementById('wholesale');
let params = [];
function getUriParams () {
let parts = window.location.href
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
params.push({[key]: value});
});
}
function setFormParam (param) {
for(const key in param){
switch (key) {
case 'size':
case 'color':
form.querySelectorAll('input[name="'+key+'"]')
.forEach((elem) => {
if (elem.value === param[key]) {
elem.checked = true
}
});
break;
case 'manufacturer':
form.querySelectorAll('select[name="'+key+'"] option')
.forEach((elem) =>{
if (elem.value === decodeURIComponent(param[key])) {
elem.selected = true;
}
});
break
case 'sale':
param[key] === "1" ? isWholesale = true : isWholesale = false;
if (isWholesale){
form.querySelector('input[name="'+key+'"]').checked = true;
form.addEventListener('change', function (e) {
e.target.checked = true;
}, false);
}
break;
}
}
}
function clearForm () {
for(let field of form){
switch (field.type) {
case 'checkbox':
case 'radio':
field.checked = false;
break;
case 'select-multiple':
field.querySelectorAll('option')
.forEach((option) =>{
option.selected = false;
});
break;
}
}
}
function setFormParams () {
clearForm();
getUriParams();
params.every(function (param) {
setFormParam(param);
return true;
});
}
function logFormParams () {
const query = [];
let url = window.location.origin + window.location.pathname + '/?filter?';
for(let field of form){
switch (field.type) {
case 'checkbox':
case 'radio':
if (field.checked) {
query.push({[field.name]: field.value});
}
break;
case 'select-multiple':
field.querySelectorAll('option')
.forEach((option) =>{
if(option.selected) {
query.push({[field.name]: option.value});
}
});
break;
}
}
query.every(function(param){
for(let key in param ) {
url = url + '&' + key + '=' + encodeURIComponent(param[key]);
}
return true;
});
console.log(url);
}
setFormParams();
form.addEventListener('change', logFormParams, false);
|
/* In order to make the helloWorld() function available client-side, you have to add a reference to the 'MyRPCmodule' module in the GUI Designer.
The helloWorld() function can be executed from your JS file as follows:
alert(MyRPCmodule.helloWorld());
For more information, refer to http://doc.wakanda.org/Wakanda0.Beta/help/Title/en/page1516.html
*/
exports.userNameIsUnique = function (userName) {
var theOwner = ds.Owner( {username : userName} );
var theUser = ds.User( {userid : userName} );
if ((theOwner == null) && (theUser == null)) {
return true; // username available
} else {
return false; // username taken
}
};
exports.createNewOwner = function (owner) {
var newOwner = new ds.Owner ({
username : owner.username,
password : owner.password,
fullName : owner.fullName,
email : owner.email,
street1 : owner.street1,
street2 : owner.street2,
postcode : owner.postcode,
city : owner.city,
state : owner.state,
officePhone : owner.officePhone,
mobilePhone : owner.mobilePhone
});
try
{
newOwner.save();
return true;
}
catch (e)
{
return false;
}
};
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "39dadb3a6bd813792671",
"url": "css/app.91fb029d.css"
},
{
"revision": "55ce4761c5de36bf1ff1",
"url": "css/chunk-vendors.ab91ceed.css"
},
{
"revision": "83f820b57009de0e6aba5652eaff5c88",
"url": "index.html"
},
{
"revision": "39dadb3a6bd813792671",
"url": "js/app.c830e4f9.js"
},
{
"revision": "55ce4761c5de36bf1ff1",
"url": "js/chunk-vendors.7f53931b.js"
},
{
"revision": "b8f0b326ea946e58446dc9de0edcac0b",
"url": "manifest.json"
},
{
"revision": "b6216d61c03e6ce0c9aea6ca7808f7ca",
"url": "robots.txt"
}
]);
|
import React from "react";
import RewardDetails from "./RewardDetails";
import "../css/RewardsList.css";
import UserContext from "../context/userContext";
const RewardList = ({ rewards, redeemReward, category }) => {
const rewardsList = (user) =>{
if (!user) return "loading..."
return rewards.map((reward) => {
if (category !== reward.category && category !== "all") return null;
const redeemed = user.redeemedRewards
.map((reward) => reward._id)
.includes(reward._id);
return (
<RewardDetails
key={reward._id}
reward={reward}
redeemReward={redeemReward}
redeemed={redeemed}
/>
);
})
}
return (
<UserContext.Consumer>{user => rewardsList(user)}</UserContext.Consumer>
);
};
export default RewardList;
|
'use strict';
var isUtils = require('./is-utils');
module.exports = {
noop: function () {
// do nothing
},
times: function (n, fn) {
while (n-- > 0) {
fn();
}
},
valueFn: function (value) {
return function () {
return value;
};
},
overload: function () {
var fns = [],
index, fn;
for (index = 0; index < arguments.length; index++) {
fn = arguments[index];
if (!isUtils.isFunction(fn)) {
throw new Error();
}
if (isUtils.isDefined(fns[fn.length])) {
throw new Error();
}
fns[fn.length] = fn;
}
return function () {
fn = fns[arguments.length];
if (isUtils.isFunction(fn)) {
return fn.apply(this, arguments);
}
throw new Error();
};
}
};
|
define(['page', 'schema', 'editor'], function (
pageLib,
schemaLib,
editorProxy
) {
'use strict'
var ngMod = angular.module('page.enroll', [])
/**
* app's pages
*/
ngMod.provider('srvEnrollPage', function () {
var _siteId, _appId, _matterType, _baseUrl
_matterType = window.MATTER_TYPE.toLowerCase()
_baseUrl = '/rest/pl/fe/matter/' + _matterType + '/page/'
this.config = function (siteId, appId) {
_siteId = siteId
_appId = appId
}
this.$get = [
'$uibModal',
'$q',
'http2',
'noticebox',
'srv' + window.MATTER_TYPE + 'App',
function ($uibModal, $q, http2, noticebox, srvApp) {
var _self
_self = {
create: function () {
var deferred = $q.defer()
srvApp.get().then(function (app) {
$uibModal
.open({
templateUrl:
'/views/default/pl/fe/matter/enroll/component/createPage.html?_=4',
backdrop: 'static',
controller: [
'$scope',
'$uibModalInstance',
function ($scope, $mi) {
$scope.options = {}
$scope.ok = function () {
if (!$scope.options.title) {
noticebox.warn('请指定页面的名称!')
return
}
if (!$scope.options.type) {
noticebox.warn('请指定页面的类型!')
return
}
$mi.close($scope.options)
}
$scope.cancel = function () {
$mi.dismiss()
}
},
],
})
.result.then(function (options) {
http2
.post(
_baseUrl + 'add?site=' + _siteId + '&app=' + _appId,
options
)
.then(function (rsp) {
var page = rsp.data
pageLib.enhance(page)
app.pages.push(page)
deferred.resolve(page)
})
})
})
return deferred.promise
},
update: function (oPage, names) {
var defer = $q.defer(),
updated = {},
url
angular.isString(names) && (names = [names])
names.forEach(function (name) {
if (name === 'html') {
updated.html = encodeURIComponent(oPage.html)
} else {
updated[name] = oPage[name]
}
})
url = _baseUrl + '/update'
url += '?site=' + _siteId
url += '&app=' + _appId
url += '&page=' + oPage.id
url += '&cname=' + oPage.code_name
http2.post(url, updated).then(function (rsp) {
oPage.$$modified = false
noticebox.success('完成保存')
defer.resolve()
})
return defer.promise
},
clean: function (page) {
page.html = ''
page.dataSchemas = []
page.actSchemas = []
return _self.update(page, ['dataSchemas', 'actSchemas', 'html'])
},
remove: function (page) {
var defer = $q.defer()
srvApp.get().then(function (app) {
var url = _baseUrl + 'remove'
url += '?site=' + _siteId
url += '&app=' + _appId
url += '&pid=' + page.id
url += '&cname=' + page.code_name
http2.get(url).then(function (rsp) {
app.pages.splice(app.pages.indexOf(page), 1)
defer.resolve(app.pages)
noticebox.success('完成删除')
})
})
return defer.promise
},
repair: function (aCheckResult, oPage) {
return $uibModal
.open({
templateUrl:
'/views/default/pl/fe/matter/enroll/component/repair.html',
controller: [
'$scope',
'$uibModalInstance',
function ($scope2, $mi) {
$scope2.reason = aCheckResult[1]
$scope2.ok = function () {
$mi.close()
}
$scope2.cancel = function () {
$mi.dismiss()
}
},
],
backdrop: 'static',
})
.result.then(function () {
var aRepairResult
aRepairResult = oPage.repair(aCheckResult)
if (aRepairResult[0] === true) {
if (aRepairResult[1] && aRepairResult[1].length) {
aRepairResult[1].forEach(function (changedProp) {
switch (changedProp) {
case 'dataSchemas':
// do nothing
break
case 'html':
if (oPage === editorProxy.getPage()) {
editorProxy.refresh()
}
break
}
})
}
}
})
},
}
return _self
},
]
})
/**
* page editor
*/
ngMod.controller('ctrlPageEdit', [
'$scope',
'$uibModal',
'http2',
'CstApp',
'mediagallery',
'srvSite',
function ($scope, $uibModal, http2, CstApp, mediagallery, srvSite) {
var tinymceEditor
$scope.activeWrap = false
$scope.setActiveWrap = function (domWrap) {
$scope.activeWrap = editorProxy.setActiveWrap(domWrap)
}
$scope.wrapEditorHtml = function () {
var url = null
if ($scope.activeWrap && $scope.activeWrap.type) {
if (!/score|matter|text|button/.test($scope.activeWrap.type)) {
url =
'/views/default/pl/fe/matter/enroll/wrap/' +
$scope.activeWrap.type +
'.html?_=' +
new Date().getMinutes()
}
}
return url
}
$scope.refreshWrap = function (wrap) {
editorProxy.modifySchema(wrap)
}
/* 设置页面操作 */
$scope.configButton = function (oEditingPage) {
http2
.post('/rest/script/time', {
html: {
buttons:
'/views/default/pl/fe/matter/enroll/component/pageButtons',
},
})
.then(function (rsp) {
$uibModal.open({
templateUrl:
'/views/default/pl/fe/matter/enroll/component/pageButtons.html?_=' +
rsp.data.html.buttons.time,
controller: [
'$scope',
'$uibModalInstance',
function ($scope2, $mi) {
var _oPage, _oActiveButton, appPages, _nextPages
$scope2.page = _oPage = oEditingPage
appPages = $scope.app.pages
$scope2.nextPages = _nextPages = []
$scope2.cancel = function () {
$mi.dismiss()
}
$scope2.ok = function () {
_oPage.$$modified = true
$mi.close()
}
$scope2.newButton = function (btn) {
var oSchema, oWrap
oSchema = angular.copy(btn)
switch (oSchema.n) {
case 'submit':
var oFirstViewPage
for (var i = appPages.length - 1; i >= 0; i--) {
if (appPages[i].type === 'V') {
oFirstViewPage = appPages[i]
break
}
}
if (oFirstViewPage) {
oSchema.next = oFirstViewPage.name
}
break
case 'addRecord':
case 'editRecord':
var oFirstInputPage
for (var i = appPages.length - 1; i >= 0; i--) {
if (appPages[i].type === 'I') {
oFirstInputPage = appPages[i]
break
}
}
if (oFirstInputPage) {
oSchema.next = oFirstInputPage.name
}
break
default:
oSchema.next = ''
}
oWrap = {
id: 'act' + new Date() * 1,
name: oSchema.n,
label: oSchema.l,
next: oSchema.next || '',
}
_oPage.actSchemas.push(oWrap)
$scope2.setButton(oWrap)
}
$scope2.setButton = function (oBtn) {
$scope2.activeButton = _oActiveButton = oBtn
if (
$scope2.buttons[_oActiveButton.name] &&
$scope2.buttons[_oActiveButton.name].next
) {
appPages.forEach(function (oPage) {
if (
$scope2.buttons[_oActiveButton.name].next.indexOf(
oPage.type
) !== -1
) {
_nextPages.push({
name: oPage.name,
title: oPage.title,
})
}
})
} else {
appPages.forEach(function (oPage) {
_nextPages.push({
name: oPage.name,
title: oPage.title,
})
})
}
}
$scope2.removeButton = function (oBtn) {
_oPage.actSchemas.splice(_oPage.actSchemas.indexOf(oBtn), 1)
$scope2.activeButton = _oActiveButton = null
}
$scope2.chooseType = function () {
_oActiveButton.label =
$scope2.buttons[_oActiveButton.name].l
_oActiveButton.next = ''
if (
['addRecord', 'editRecord', 'removeRecord'].indexOf(
_oActiveButton.name
) !== -1
) {
for (var i = 0, ii = appPages.length; i < ii; i++) {
if (appPages[i].type === 'I') {
_oActiveButton.next = appPages[i].name
break
}
}
if (i === ii) noticebox.warn('没有类型为“填写页”的页面')
}
}
// page's buttons
var buttons = {},
button,
btnName
for (btnName in schemaLib.buttons) {
button = schemaLib.buttons[btnName]
if (
button.scope &&
button.scope.indexOf(_oPage.type) !== -1
) {
buttons[btnName] = button
}
}
$scope2.buttons = buttons
},
],
size: 'lg',
windowClass: 'auto-height',
})
})
}
$scope.removeActiveWrap = function () {
var activeWrap = $scope.activeWrap,
wrapType = activeWrap.type,
schema
if (/input|value/.test(wrapType)) {
editorProxy.removeWrap(activeWrap)
if (/I|V/.test($scope.ep.type)) {
schema = activeWrap.schema
$scope.$broadcast(
'xxt.matter.enroll.page.dataSchemas.removed',
schema
)
}
$scope.setActiveWrap(null)
} else if (/radio|checkbox|score/.test(wrapType)) {
var optionSchema
schema = editorProxy.optionSchemaByDom(activeWrap.dom, $scope.app)
optionSchema = schema[1]
schema = schema[0]
schema.ops.splice(schema.ops.indexOf(optionSchema), 1)
// 更新当前页面
editorProxy.removeWrap(activeWrap)
// 更新其它页面
$scope.$emit('xxt.matter.enroll.app.dataSchemas.modified', {
originator: $scope.ep,
schema: schema,
})
$scope.setActiveWrap(null)
} else {
editorProxy.removeWrap(activeWrap)
$scope.setActiveWrap(null)
}
}
$scope.moveWrap = function (action) {
$scope.activeWrap = editorProxy.moveWrap(action)
}
$scope.embedMatter = function (page) {
var options = {
matterTypes: CstApp.innerlink,
singleMatter: true,
}
if ($scope.app.mission) {
options.mission = $scope.app.mission
}
srvSite.openGallery(options).then(function (result) {
var dom = tinymceEditor.dom,
style = 'cursor:pointer',
fn,
domMatter,
sibling
if ($scope.activeWrap) {
sibling = $scope.activeWrap.dom
while (sibling.parentNode !== tinymceEditor.getBody()) {
sibling = sibling.parentNode
}
// 加到当前选中元素的后面
result.matters.forEach(function (matter) {
fn = "openMatter('" + matter.id + "','" + result.type + "')"
domMatter = dom.create(
'div',
{
wrap: 'matter',
class: 'form-group',
},
dom.createHTML(
'span',
{
style: style,
'ng-click': fn,
},
dom.encode(matter.title)
)
)
dom.insertAfter(domMatter, sibling)
})
} else {
// 加到页面的结尾
result.matters.forEach(function (matter) {
fn = "openMatter('" + matter.id + "','" + result.type + "')"
domMatter = dom.add(
tinymceEditor.getBody(),
'div',
{
wrap: 'matter',
class: 'form-group',
},
dom.createHTML(
'span',
{
style: style,
'ng-click': fn,
},
dom.encode(matter.title)
)
)
})
}
})
}
$scope.$on('tinymce.content.change', function (event, changedNode) {
var status, html
if (changedNode) {
// 文档中的节点发生变化
status = editorProxy.nodeChange(changedNode.node)
} else {
status = {}
html = editorProxy.purifyPage({
type: 'I',
page: tinymceEditor.getContent(),
})
if (html !== $scope.ep.html) {
status.htmlChanged = true
$scope.ep.$$modified = true
}
}
if (status.schemaChanged === true) {
// 更新其他页面
$scope.$emit('xxt.matter.enroll.app.dataSchemas.modified', {
originator: $scope.ep,
schema: $scope.activeWrap.schema || status.schema,
})
}
})
//添加选项
$scope.$on('tinymce.option.add', function (event, domWrap) {
var optionDom, schemaOptionId, schemaId, schema
if (/radio|checkbox/.test(domWrap.getAttribute('wrap'))) {
optionDom = domWrap.querySelector('input')
schemaId = optionDom.getAttribute('name')
if (/radio/.test(domWrap.getAttribute('wrap'))) {
schemaOptionId = optionDom.getAttribute('value')
} else if (/checkbox/.test(domWrap.getAttribute('wrap'))) {
schemaOptionId = optionDom.getAttribute('ng-model')
schemaOptionId = schemaOptionId.split('.')[2]
}
} else if (/score/.test(domWrap.getAttribute('wrap'))) {
schemaId = domWrap.parentNode.parentNode.getAttribute('schema')
schemaOptionId = domWrap.getAttribute('opvalue')
}
for (var i = $scope.app.dataSchemas.length - 1; i >= 0; i--) {
if (schemaId === $scope.app.dataSchemas[i].id) {
schema = $scope.app.dataSchemas[i]
if (schema.ops) {
var newOp
newOp = schemaLib.addOption(schema, schemaOptionId)
editorProxy.addOptionWrap(domWrap, schema, newOp)
}
break
}
}
})
$scope.$on('tinymce.wrap.add', function (event, domWrap) {
$scope.$apply(function () {
$scope.setActiveWrap(domWrap)
})
})
$scope.$on('tinymce.wrap.select', function (event, domWrap) {
$scope.$apply(function () {
$scope.setActiveWrap(domWrap)
})
})
$scope.$on('tinymce.multipleimage.open', function (event, callback) {
var options = {
callback: callback,
multiple: true,
setshowname: true,
}
mediagallery.open($scope.app.siteid, options)
})
// 切换编辑的页面
$scope.$watch('ep', function (oNewPage) {
if (!oNewPage) return
$scope.setActiveWrap(null)
// page's content
if (tinymceEditor) {
var oldPage = editorProxy.getPage()
if (oldPage) {
oldPage.html = editorProxy.purifyPage({
type: oldPage.type,
html: tinymceEditor.getContent(),
})
}
editorProxy.load(tinymceEditor, oNewPage)
}
})
$scope.$on('tinymce.instance.init', function (event, editor) {
tinymceEditor = editor
if ($scope.ep) {
editorProxy.load(editor, $scope.ep)
} else {
editorProxy.setPage(null)
}
})
},
])
/**
* input
*/
ngMod.controller('ctrlAppSchemas4IV', [
'$scope',
function ($scope) {
var _oChooseState
$scope.choose = function (schema) {
if (_oChooseState[schema.id]) {
var ia, sibling, domNewWrap
ia = $scope.app.dataSchemas.indexOf(schema)
if (ia === 0) {
sibling = $scope.app.dataSchemas[++ia]
while (
ia < $scope.app.dataSchemas.length &&
!_oChooseState[sibling.id]
) {
sibling = $scope.app.dataSchemas[++ia]
}
domNewWrap = editorProxy.appendSchema(schema, sibling, true)
} else {
sibling = $scope.app.dataSchemas[--ia]
while (ia > 0 && !_oChooseState[sibling.id]) {
sibling = $scope.app.dataSchemas[--ia]
}
if (sibling) {
if (_oChooseState[sibling.id]) {
domNewWrap = editorProxy.appendSchema(schema, sibling)
} else {
ia = $scope.app.dataSchemas.indexOf(schema)
sibling = $scope.app.dataSchemas[++ia]
while (
ia < $scope.app.dataSchemas.length &&
!_oChooseState[sibling.id]
) {
sibling = $scope.app.dataSchemas[++ia]
}
domNewWrap = editorProxy.appendSchema(schema, sibling, true)
}
} else {
domNewWrap = editorProxy.appendSchema(schema)
}
}
$scope.setActiveWrap(domNewWrap)
editorProxy.scroll(domNewWrap)
} else {
if (editorProxy.removeSchema(schema)) {
if (
$scope.activeWrap &&
schema.id === $scope.activeWrap.schema.id
) {
$scope.setActiveWrap(null)
}
}
}
}
$scope.$on(
'xxt.matter.enroll.page.dataSchemas.removed',
function (event, removedSchema) {
if (removedSchema && removedSchema.id) {
_oChooseState[removedSchema.id] = false
}
}
)
$scope.$watch('ep', function (oPage) {
if (oPage) {
_oChooseState = {}
if (!$scope.app) return
$scope.app.dataSchemas.forEach(function (schema) {
_oChooseState[schema.id] = false
})
if (oPage.type === 'I') {
if (oPage.dataSchemas && oPage.dataSchemas.length) {
oPage.dataSchemas.forEach(function (dataWrap) {
if (dataWrap.schema) {
_oChooseState[dataWrap.schema.id] = true
}
})
}
} else if (oPage.type === 'V') {
$scope.otherSchemas = [
{
id: 'enrollAt',
type: '_enrollAt',
title: '填写时间',
},
{
id: 'roundTitle',
type: '_roundTitle',
title: '填写轮次',
},
]
if (oPage.dataSchemas && oPage.dataSchemas.length) {
oPage.dataSchemas.forEach(function (config) {
config.schema &&
config.schema.id &&
(_oChooseState[config.schema.id] = true)
})
}
_oChooseState['enrollAt'] === undefined &&
(_oChooseState['enrollAt'] = false)
_oChooseState['roundTitle'] === undefined &&
(_oChooseState['roundTitle'] = false)
}
$scope.chooseState = _oChooseState
}
$scope.$watchCollection('ep.dataSchemas', function (newVal) {
var aUncheckedSchemaIds
if (/I|V/.test($scope.ep.type)) {
if (newVal) {
aUncheckedSchemaIds = Object.keys(_oChooseState)
newVal.forEach(function (oWrap) {
var i
_oChooseState[oWrap.schema.id] = true
i = aUncheckedSchemaIds.indexOf(oWrap.schema.id)
if (i !== -1) {
aUncheckedSchemaIds.splice(i, 1)
}
})
aUncheckedSchemaIds.forEach(function (schemaId) {
_oChooseState[schemaId] = false
})
}
}
})
})
},
])
/**
* 登记项编辑
*/
ngMod.controller('ctrlInputWrap', [
'$scope',
'$timeout',
function ($scope, $timeout) {
$scope.addOption = function () {
var newOp
newOp = schemaLib.addOption($scope.activeWrap.schema)
$timeout(function () {
$scope.$broadcast('xxt.editable.add', newOp)
})
}
$scope.onKeyup = function (event) {
// 回车时自动添加选项
if (event.keyCode === 13) {
$scope.addOption()
}
}
$scope.$on('xxt.editable.changed', function (e, op) {
$scope.updWrap()
})
$scope.$on('xxt.editable.remove', function (e, op) {
var schema = $scope.activeWrap.schema,
i = schema.ops.indexOf(op)
schema.ops.splice(i, 1)
$scope.updWrap()
})
$scope.$watch('activeWrap.schema.setUpper', function (nv) {
var schema = $scope.activeWrap.schema
if (nv === 'Y') {
schema.upper = schema.ops ? schema.ops.length : 0
}
})
$scope.updWrap = function () {
$scope.ep.$$modified = true
editorProxy.modifySchema($scope.activeWrap)
$scope.$emit('xxt.matter.enroll.app.dataSchemas.modified', {
originator: $scope.ep,
schema: $scope.activeWrap.schema,
})
}
if ($scope.activeWrap.schema.mschema_id) {
;(function () {
var i, j, memberSchema, schema
/*自定义用户*/
for (i = $scope.memberSchemas.length - 1; i >= 0; i--) {
memberSchema = $scope.memberSchemas[i]
if ($scope.activeWrap.schema.mschema_id === memberSchema.id) {
for (j = memberSchema._schemas.length - 1; j >= 0; j--) {
schema = memberSchema._schemas[j]
if ($scope.activeWrap.schema.id === schema.id) {
break
}
}
$scope.selectedMemberSchema = {
schema: memberSchema,
attr: schema,
}
break
}
}
})()
}
},
])
/**
* value wrap
*/
ngMod.controller('ctrlValueWrap', [
'$scope',
function ($scope) {
$scope.updWrap = function () {
$scope.ep.$$modified = true
editorProxy.modifySchema($scope.activeWrap)
}
},
])
})
|
//Questão 1//
var data = new Date();
var dia_semana = data.getDay();
switch(dia_semana){
case 0: console.log("Hoje é: domingo");
break;
case 1: console.log("Hoje é: segunda-feira");
break;
case 2: console.log("Hoje é: terça-feira");
break;
case 3: console.log("Hoje é: quarta-feira");
break;
case 4: console.log("Hoje é: quinta-feira");
break;
case 5: console.log("Hoje é: sexta-feira");
break;
case 6: console.log("Hoje é: sábado");
break;
default:;
}
//Criando data e hora.
var data = new Date();
var hora = data.getHours();
var min = data.getMinutes();
var seg = data.getSeconds();
var horario = 'Hora atual: ' + hora + ':' + min + ':' + seg;
console.log(horario);
|
// Copyright 2010-2016 i-designer.net. All rights reserved.
// This script will generator file with guide for bootstrap
// Written by Nguyen Nhu Tuan
// Version: 1.0.0
// Created at: 2015-06-05
// Updated at: 2015-06-05
// Email: tuanquynh0508@gmail.com
// Using function guideLine and clearGuides of Patrick. Thanks Patrick !. Ref: http://www.ps-scripts.com/bb/viewtopic.php?t=1775&highlight=&sid=9980aca4225b16adf2b0543df74aa975
// Using function StrToIntWithDefault of Adobe Systems. Thanks Adobe Systems !.
/*
@@@BUILDINFO@@@ BoostrapGridGenerator.jsx 1.0.0
*/
/*
// BEGIN__HARVEST_EXCEPTION_ZSTRING
<javascriptresource>
<name>$$$/JavaScripts/BoostrapGridGenerator/Menu=Bootstrap Grid Generator...</name>
<about>$$$/JavaScripts/BoostrapGridGenerator/About=Bootstrap Grid Generator ^r^rCopyright 2010-2016 i-designer.net. All rights reserved.^r^rGenerator Grid For Bootstrap</about>
<category>aaaThisPutsMeAtTheTopOfTheMenu</category>
</javascriptresource>
// END__HARVEST_EXCEPTION_ZSTRING
*/
// enable double clicking from the Macintosh Finder or the Windows Explorer
#target photoshop
// debug level: 0-2 (0:disable, 1:break on error, 2:break at beginning)
// $.level = 0;
// debugger; // launch debugger on next line
// on localized builds we pull the $$$/Strings from a .dat file, see documentation for more details
$.localize = true;
//=================================================================
// Globals
//=================================================================
// UI strings to be localized
//Label
var strTextCopyrightTNQSoft = localize("$$$/JavaScripts/BoostrapGridGenerator/TextCopyrightTNQSoft=(c) 2010-2016. i-designer.net");
var strTitle = localize("$$$/JavaScripts/BoostrapGridGenerator/Title=Bootstrap Grid Generator");
var strButtonRun = localize("$$$/JavaScripts/BoostrapGridGenerator/Run=Create");
var strButtonCancel = localize("$$$/JavaScripts/BoostrapGridGenerator/Cancel=Cancel");
var strLabelContainerWidth = localize("$$$/JavaScripts/BoostrapGridGenerator/ContainerWidth=Container width(px):");
var strLabelColPadding = localize("$$$/JavaScripts/BoostrapGridGenerator/ColPadding=Column padding(px):");
var strLabelTotalHeight = localize("$$$/JavaScripts/BoostrapGridGenerator/TotalHeight=Total height(Not less than 200px):");
var strLabelDocumentType = localize("$$$/JavaScripts/BoostrapGridGenerator/DocumentType=Background Contents:");
//Default value
var stretContainerWidth = localize( "$$$/locale_specific/JavaScripts/BoostrapGridGenerator/ETContainerWidthLength=1170" );
var stretColPadding = localize( "$$$/locale_specific/JavaScripts/BoostrapGridGenerator/ETColPaddingLength=15" );
var stretTotalHeight = localize( "$$$/locale_specific/JavaScripts/BoostrapGridGenerator/ETTotalHeightLength=2000" );
var strddDocumentType = localize( "$$$/locale_specific/JavaScripts/BoostrapGridGenerator/DDDocumentType=100" );
//Alert
var strAlertSpecifyContainerWidth = localize("$$$/JavaScripts/BoostrapGridGenerator/SpecifyContainerWidth=Please specify Container width.");
var strAlertNotNullContainerWidth = localize("$$$/JavaScripts/BoostrapGridGenerator/NotNullContainerWidth=Value of Container width is not equal zero.");
var strAlertSpecifyColPadding = localize("$$$/JavaScripts/BoostrapGridGenerator/SpecifyColPadding=Please specify Column padding left and right.");
var strAlertNotNullColPadding = localize("$$$/JavaScripts/BoostrapGridGenerator/NotNullColPadding=Value of Column padding is not equal zero.");
var strAlertSpecifyTotalHeight = localize("$$$/JavaScripts/BoostrapGridGenerator/SpecifyTotalHeight=Total height value not less than 200.");
// ok and cancel button
var runButtonID = 1;
var cancelButtonID = 2;
var documentWith = 1600;
var totalColumn = 12; //Total column of bootstrap grid system
var primaryVerticalSpace = 10;
var whiteIndex = 0;
var backgroundColorIndex = 1;
var transparentIndex = 2;
///////////////////////////////////////////////////////////////////////////////
// Dispatch
///////////////////////////////////////////////////////////////////////////////
main();
///////////////////////////////////////////////////////////////////////////////
// Functions
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Function: main
// Usage: the core routine for this script
// Input: <none>
// Return: <none>
///////////////////////////////////////////////////////////////////////////////
function main() {
var generatorObj = new Object();
initGeneratorObj(generatorObj);
if ( DialogModes.ALL == app.playbackDisplayDialogs ) {
if (cancelButtonID == settingDialog(generatorObj)) {
return 'cancel'; // quit, returning 'cancel' (dont localize) makes the actions palette not record our script
}
}
gridGeneratorTemplate(generatorObj);
}
///////////////////////////////////////////////////////////////////////////////
// Function: settingDialog
// Usage: pop the ui and get user settings
// Input: generatorObj object containing our parameters
// Return: on ok, the dialog info is set to the generatorObj object
///////////////////////////////////////////////////////////////////////////////
function settingDialog(generatorObj)
{
dlgMain = new Window("dialog", strTitle);
// match our dialog background color to the host application
//var brush = dlgMain.graphics.newBrush(dlgMain.graphics.BrushType.THEME_COLOR, "appDialogBackground");
//dlgMain.graphics.backgroundColor = brush;
//dlgMain.graphics.disabledBackgroundColor = brush;
dlgMain.orientation = 'column';
dlgMain.alignChildren = 'left';
// -- two groups, one for left and one for right ok, cancel
dlgMain.grpTop = dlgMain.add("group");
dlgMain.grpTop.orientation = 'column';
dlgMain.grpTop.alignChildren = 'left';
dlgMain.grpTop.alignment = 'fill';
// -- two groups, one for left and one for right ok, cancel
dlgMain.grpButton = dlgMain.add("group");
dlgMain.grpButton.orientation = 'row';
dlgMain.grpButton.alignChildren = 'center';
dlgMain.grpButton.alignment = 'fill';
dlgMain.pnlCreateOption = dlgMain.add("panel", undefined, "Options");
dlgMain.pnlCreateOption.alignChildren = 'left';
dlgMain.pnlCreateOption.alignment = 'fill';
dlgMain.grpBottom = dlgMain.add("group");
dlgMain.grpBottom.orientation = 'column';
dlgMain.grpBottom.alignChildren = 'center';
dlgMain.grpBottom.alignment = 'fill';
// -- the third line in the dialog
dlgMain.grpTop.add("statictext", undefined, strLabelContainerWidth);
// -- the fourth line in the dialog
dlgMain.etContainerWidth = dlgMain.grpTop.add("edittext", undefined, generatorObj.containerWidth.toString());
dlgMain.etContainerWidth.alignment = 'fill';
dlgMain.etContainerWidth.preferredSize.width = StrToIntWithDefault( strLabelContainerWidth, 160 );
// -- the third line in the dialog
dlgMain.grpTop.add("statictext", undefined, strLabelColPadding);
// -- the fourth line in the dialog
dlgMain.etColPadding = dlgMain.grpTop.add("edittext", undefined, generatorObj.colPadding.toString());
dlgMain.etColPadding.alignment = 'fill';
dlgMain.etColPadding.preferredSize.width = StrToIntWithDefault( strLabelColPadding, 160 );
// -- the fourth line in the dialog
dlgMain.etHorizontalGuides = dlgMain.pnlCreateOption.add("checkbox", undefined, 'Horizontal Guides');
// -- the third line in the dialog
dlgMain.pnlCreateOption.add("statictext", undefined, strLabelTotalHeight);
// -- the fourth line in the dialog
dlgMain.etTotalHeight = dlgMain.pnlCreateOption.add("edittext", undefined, generatorObj.totalHeight.toString());
dlgMain.etTotalHeight.alignment = 'fill';
dlgMain.etTotalHeight.preferredSize.width = StrToIntWithDefault( strLabelTotalHeight, 160 );
// -- the third line in the dialog
dlgMain.pnlCreateOption.add("statictext", undefined, strLabelDocumentType);
dlgMain.ddDocumentType = dlgMain.pnlCreateOption.add("dropdownlist", undefined);
dlgMain.ddDocumentType.preferredSize.width = StrToIntWithDefault( strddDocumentType, 100 );
dlgMain.ddDocumentType.alignment = 'left';
dlgMain.ddDocumentType.add("item", "White");
dlgMain.ddDocumentType.add("item", "Black");
dlgMain.ddDocumentType.add("item", "Transparent");
dlgMain.ddDocumentType.items[generatorObj.documentType].selected = true;
dlgMain.btnRun = dlgMain.grpButton.add("button", undefined, strButtonRun );
dlgMain.btnRun.onClick = function() {
var containerWidth = dlgMain.etContainerWidth.text;
if (containerWidth.length == 0) {
alert(strAlertSpecifyContainerWidth);
return;
}
if (Math.abs(parseInt(containerWidth, 10)) == 0) {
alert(strAlertNotNullContainerWidth);
return;
}
var colPadding = dlgMain.etColPadding.text;
if (colPadding.length == 0) {
alert(strAlertSpecifyColPadding);
return;
}
if (Math.abs(parseInt(colPadding, 10)) == 0) {
alert(strAlertNotNullColPadding);
return;
}
var totalHeight = dlgMain.etTotalHeight.text;
if (Math.abs(parseInt(totalHeight, 10)) < 200) {
alert(strAlertSpecifyTotalHeight);
return;
}
dlgMain.close(runButtonID);
}
dlgMain.btnCancel = dlgMain.grpButton.add("button", undefined, strButtonCancel );
dlgMain.btnCancel.onClick = function() {
dlgMain.close(cancelButtonID);
}
dlgMain.grpBottom.add("statictext", undefined, strTextCopyrightTNQSoft);
dlgMain.defaultElement = dlgMain.btnRun;
dlgMain.cancelElement = dlgMain.btnCancel;
app.bringToFront();
dlgMain.center();
var result = dlgMain.show();
if (cancelButtonID == result) {
return result; // close to quit
}
// get setting from dialog
generatorObj.containerWidth = Math.abs(parseInt(dlgMain.etContainerWidth.text, 10));
generatorObj.colPadding = Math.abs(parseInt(dlgMain.etColPadding.text, 10));
generatorObj.horizontalGuides = dlgMain.etHorizontalGuides.value;
generatorObj.totalHeight = Math.abs(parseInt(dlgMain.etTotalHeight.text, 10));
generatorObj.documentType = dlgMain.ddDocumentType.selection.index;
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Function: initGeneratorObj
// Usage: create our default parameters
// Input: a new Object
// Return: a new object with params set to default
///////////////////////////////////////////////////////////////////////////////
function initGeneratorObj(generatorObj)
{
generatorObj.containerWidth = parseInt(stretContainerWidth, 10);
generatorObj.colPadding = parseInt(stretColPadding, 10);
generatorObj.totalHeight = parseInt(stretTotalHeight, 10);
generatorObj.horizontalGuides = false;
generatorObj.documentType = whiteIndex;
}
///////////////////////////////////////////////////////////////////////////////
// Function: gridGeneratorTemplate
// Usage: create our default parameters
// Input: a new Object
// Return: a new object with params set to default
///////////////////////////////////////////////////////////////////////////////
function gridGeneratorTemplate(generatorObj)
{
var p = generatorObj.colPadding;
var w1 = generatorObj.containerWidth;
var c = totalColumn;
var h = generatorObj.totalHeight;
var dt = generatorObj.documentType;
var w_grid = (w1-c*p*2)/c;
var documentPadding = (documentWith-w1)/2;
if ( ( h == 0 ) || ( !h) ) h=Math.abs(parseInt(stretTotalHeight, 10));
var strtRulerUnits = app.preferences.rulerUnits;
var strtTypeUnits = app.preferences.typeUnits;
app.preferences.rulerUnits = Units.PIXELS;
app.preferences.typeUnits = TypeUnits.POINTS;
if ( dt == whiteIndex ) {
var newDocumentRef = app.documents.add(documentWith, h, 72.0, "Grid Template " + w1 + "-" + c + "-" + p, NewDocumentMode.RGB,DocumentFill.WHITE);
}
if ( dt == backgroundColorIndex ) {
var newDocumentRef = app.documents.add(documentWith, h, 72.0, "Grid Template " + w1 + "-" + c + "-" + p, NewDocumentMode.RGB,DocumentFill.BACKGROUNDCOLOR);
}
if ( dt == transparentIndex ) {
var newDocumentRef = app.documents.add(documentWith, h, 72.0, "Grid Template " + w1 + "-" + c + "-" + p, NewDocumentMode.RGB,DocumentFill.TRANSPARENT);
}
//Add text
var textColor = new SolidColor;
textColor.rgb.red = 0;
textColor.rgb.green = 0;
textColor.rgb.blue = 0;
var newTextLayer = newDocumentRef.artLayers.add();
newTextLayer.kind = LayerKind.TEXT;
newTextLayer.textItem.justification = Justification.CENTERJUSTIFIED;
newTextLayer.textItem.size = 12;
newTextLayer.textItem.font = "Arial";
newTextLayer.textItem.color = textColor;
newTextLayer.textItem.antiAliasMethod = AntiAlias.NONE;
newTextLayer.textItem.contents = "Container width: " + w1 + ", Columns: " + c + ", Column padding lef and right: " + p + ". Generator By Gridgenerator: " + strTextCopyrightTNQSoft;
//Now change the text layer type to paragraph so you can determine the width of the text
newTextLayer.textItem.kind = TextType.PARAGRAPHTEXT;
newTextLayer.textItem.width = w1;
newTextLayer.textItem.position = Array(documentPadding,20);
app.preferences.rulerUnits = strtRulerUnits;
app.preferences.typeUnits = strtTypeUnits;
newDocumentRef = null;
textColor = null;
newTextLayer = null;
//Add guide
guideLine(documentPadding, 'Vrtc');
guideLine(documentPadding+p, 'Vrtc');
var j = documentPadding+p;
for(i=1;i<=c;i++)
{
j += w_grid;
guideLine(j, 'Vrtc');
if(i < c) {
j += p*2;
} else {
j += p;
}
guideLine(j, 'Vrtc');
}
if(true === generatorObj.horizontalGuides) {
j = 50;
for(i=0;i<((h-100)/primaryVerticalSpace);i++)
{
j += primaryVerticalSpace;
guideLine(j, 'Hrzn');
}
}
}
///////////////////////////////////////////////////////////////////////////
// Function: guideLine
// Usage: make guideline
// Input: number and string
// Return: void
///////////////////////////////////////////////////////////////////////////
function guideLine(position, type) {
// types: Vrtc & Hrzn
// =======================================================
var id296 = charIDToTypeID( "Mk " );
var desc50 = new ActionDescriptor();
var id297 = charIDToTypeID( "Nw " );
var desc51 = new ActionDescriptor();
var id298 = charIDToTypeID( "Pstn" );
var id299 = charIDToTypeID( "#Pxl" );
desc51.putUnitDouble( id298, id299, position );
var id300 = charIDToTypeID( "Ornt" );
var id301 = charIDToTypeID( "Ornt" );
var id302 = charIDToTypeID( type );
desc51.putEnumerated( id300, id301, id302 );
var id303 = charIDToTypeID( "Gd " );
desc50.putObject( id297, id303, desc51 );
executeAction( id296, desc50, DialogModes.NO );
};
///////////////////////////////////////////////////////////////////////////////
// Function: clearGuides
// Usage: clear all guidelines
// Input:
// Return: void
///////////////////////////////////////////////////////////////////////////////
function clearGuides() {
// =======================================================
var id556 = charIDToTypeID( "Dlt " );
var desc102 = new ActionDescriptor();
var id557 = charIDToTypeID( "null" );
var ref70 = new ActionReference();
var id558 = charIDToTypeID( "Gd " );
var id559 = charIDToTypeID( "Ordn" );
var id560 = charIDToTypeID( "Al " );
ref70.putEnumerated( id558, id559, id560 );
desc102.putReference( id557, ref70 );
executeAction( id556, desc102, DialogModes.NO );
};
///////////////////////////////////////////////////////////////////////////
// Function: StrToIntWithDefault
// Usage: convert a string to a number, first stripping all characters
// Input: string and a default number
// Return: a number
///////////////////////////////////////////////////////////////////////////
function StrToIntWithDefault( s, n ) {
var onlyNumbers = /[^0-9]/g;
var t = s.replace( onlyNumbers, "" );
t = parseInt( t , 10);
if ( ! isNaN( t ) ) {
n = t;
}
return n;
}
// End Layer Comps To Files.jsx
|
/*
* addAssociateController.js
*
* Copyright (c) 2017 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
(function() {
angular.module('productMaintenanceUiApp').controller('AddAssociateController', addAssociateController);
addAssociateController.$inject = ['UpcSwapApi', 'ProductInfoService'];
/**
* Constructs the controller to support the addAssociate page.
*
* @param upcSwapApi The API that will all the backend for most of the functions of this page.
* @param productInfoService The service that supports showing product information.
*/
function addAssociateController(upcSwapApi, productInfoService) {
var self = this;
/**
* Error messages to show the user.
*
* @type {String}
*/
self.error = null;
/**
* Success messages to show the user.
*
* @type {String}
*/
self.success = null;
/**
* Whether or not the front end is waiting on a response from the back end.
*
* @type {boolean}
*/
self.isWaitingForResponse = false;
/**
* Whether or not the front end has the data for what's on the page.
*
* @type {boolean}
*/
self.hasData = false;
/**
* Whether or not to show the error column on the source side.
*
* @type {boolean}
*/
self.hasSourceError = false;
/**
* Whether or not to show the error column on the destination side.
*
* @type {boolean}
*/
self.hasDestinationError = false;
/**
* The list of records the user wants to add associates to.
*
* @type {Array}
*/
self.addAssociateList = [];
/**
* List of updated associate upcs
* @type {Array}
*/
self.addAssociateUpdateList=[];
/**
* Flag set for when to show the results html
* @type {boolean}
*/
self.showAfterUpdate= false;
/**
* Whether or not to show the error column on the source side.
*
* @type {boolean}
*/
self.hasSourceUpdateError = false;
/**
* Whether or not to show the error column on the destination side.
*
* @type {boolean}
*/
self.hasDestinationUpdateError = false;
/**
* Initializes the controller.
*/
self.init = function() {
productInfoService.hide();
self.addAssociateList = [];
self.addEmptyRow();
};
/**
* Clear all datas that user entered or the system generated.
*/
self.clearData = function(){
self.init();
self.success = null;
self.error = null;
self.showAfterUpdate =false;
self.hasDestinationError = false;
self.hasSourceError = false;
};
/**
* This function is used to check datas are null or not.
*
* @returns {boolean}
*/
self.isEmptyData = function(){
for (var i = 0; i < self.addAssociateList.length; i++) {
if ((self.addAssociateList[i].source.upc != null && self.addAssociateList[i].source.upc != "")
|| (self.addAssociateList[i].source.productId != null && self.addAssociateList[i].source.productId != "")
|| (self.addAssociateList[i].source.itemCode != null && self.addAssociateList[i].source.itemCode != "")
|| (self.addAssociateList[i].destination.upc != null && self.addAssociateList[i].destination.upc != "")
|| (self.addAssociateList[i].destination.checkDigit != null && self.addAssociateList[i].destination.checkDigit != "")
){
return false;
}
}
return true;
};
/**
* Returns wheter or not the product info panel should be showing.
*
* @returns {boolean}
*/
self.isViewingProductInfo = function() {
return productInfoService.isVisible();
};
/**
* Shows the panel that contains product detail information.
*
* @param productId The product ID of the product to show.
*/
self.showProductInfo = function(productId){
productInfoService.hide();
productInfoService.show(self, productId);
};
/**
* Adds an empty row to the table.
*/
self.addEmptyRow = function() {
self.hasData = false;
upcSwapApi.getEmptySwap(self.addEmptyRowCallback, self.setError);
};
/**
* The callback from the request from the backend for a new, empty request.
*
* @param results The empty requst sent from the backend.
*/
self.addEmptyRowCallback = function(results) {
self.addAssociateList.push(results);
};
/**
* Retrieves details about the item you're trying to add an associate to.
*/
self.getAddAssociateDetails = function() {
self.isWaitingForResponse = true;
self.hasSourceError = false;
self.hasDestinationError = false;
self.error = null;
productInfoService.hide();
upcSwapApi.getAddAssociateDetails(self.addAssociateList,
self.loadData, self.setError);
};
/**
* The callback for when the front-end requests detailed information from the back end.
*
* @param results The fully populated request objects.
*/
self.loadData = function(results) {
self.isWaitingForResponse = false;
self.addAssociateList = results;
self.hasData = true;
for(var index = 0; index < self.addAssociateList.length; index++) {
var upcSwap = self.addAssociateList[index];
// See if the error columns need to be shown.
if (upcSwap.source != null && upcSwap.source.errorMessage != null) {
self.hasSourceError = true;
}
if (upcSwap.destination != null && upcSwap.destination.errorMessage != null) {
self.hasDestinationError = true;
}
upcSwap.sourceInformation = formatSwapInformation(upcSwap.source);
}
self.showProductInfoWhenViewingOneProduct();
};
/**
* Returns whether or not the data row has fetched the details from the back end.
*
* @param upcSwapRecord data row to look at
* @returns {boolean}
*/
self.alreadyFetchedDetails = function(upcSwapRecord){
return (upcSwapRecord != null && upcSwapRecord.errorFound == false);
};
/**
* Callback for when there is an error returned from the server.
*
* @param error The error from the server.
*/
self.setError = function(error){
self.isWaitingForResponse = false;
if (error && error.data) {
if (error.data.message && error.data.message != "") {
self.error = error.data.message;
} else {
self.error = error.data.error;
}
} else {
self.error = "An unknown error occurred.";
}
};
/**
* Callback for when an add associate successfully happens.
*
* @param result The repsonse from the backend.
*/
self.saveSuccess = function(result) {
self.showAfterUpdate = true;
self.isWaitingForResponse = false;
self.success = result.message;
angular.forEach(result.data, function (associate) {
if(associate.errorFound){
self.success = null;
}
});
self.addAssociateUpdateList=result.data;
self.hasSourceUpdateError = result.data[0].errorFound;
self.hasDestinationUpdateError = result.data[0].errorFound;
self.showProductInfoWhenViewingOneProduct();
};
/**
* Will, if there is only one product being worked on, show the product info panel.
*/
self.showProductInfoWhenViewingOneProduct = function() {
if (self.addAssociateList[0].source.productId == null) {
return;
}
// If there is only one row, show the product information.
var productId = self.addAssociateList[0].source.productId;
// If there is more than one row, see if they are all related to the same product, if so, then
// go ahead and show the prodcut info.
for (var i = 1; i < self.addAssociateList.length; i++) {
if (self.addAssociateList[i].source.productId != productId) {
return;
}
}
self.showProductInfo(self.addAssociateList[0].source.productId);
};
/**
* Submits a request to add the associate UPC.
*/
self.submitAddAssociate = function() {
self.isWaitingForResponse = true;
productInfoService.hide();
upcSwapApi.addAssociateUpcs(self.addAssociateList, self.saveSuccess, self.setError);
};
/**
* Determines if the details for the page can be submitted.
*
* @returns {boolean}
*/
self.canSubmit = function() {
// Can't submit if there are errors on any row.
if (self.hasSourceError || self.hasDestinationError) {
return false;
}
// If we've got data, you can submit.
return self.hasData;
};
/**
* To handle when the user types in an item code, will clear out the UPC.
*
* @param addAssociate The UpcSwap to clear the UPC from.
*/
self.resetUpc = function(addAssociate) {
self.hasData = false;
if (addAssociate.source.itemCode != null) {
addAssociate.source.upc = null;
}
};
/**
* To handle when the user types in UPC, will clear out the item code.
*
* @param addAssociate The UpcSwap to clear the item code from.
*/
self.resetItemCode = function(addAssociate) {
self.hasData = false;
if (addAssociate.source.upc != null) {
addAssociate.source.itemCode = null;
}
};
/**
* Removes an add associate request from the list of requests being worked on.
*
* @param addAssociate The add associate request to remove.
*/
self.removeAddAssociate = function(addAssociate) {
var indexToRemove = -1;
for(var index = 0; index < self.addAssociateList.length; index++) {
if (self.addAssociateList[index] == addAssociate) {
indexToRemove = index;
break;
}
}
if (indexToRemove != -1) {
self.addAssociateList.splice(indexToRemove, 1);
}
};
/**
* Called when the user has updated the UPC to add.
*
* @param addAssociate The add associate reqeust the user edited.
*/
self.typedUpcToAdd = function(addAssociate) {
self.hasData = false;
};
}
})();
|
import React,{Component} from 'react';
import { createAppContainer } from 'react-navigation';
import NavigationDrawer from './NavigationDrawer';
const AppContainer = createAppContainer(NavigationDrawer);
export default class App extends Component{
render(){
return(
<AppContainer />
);
}
}
|
import React from "react";
import { Button, Form, InputNumber } from "antd";
const SatSetting = ({ onShow }) => {
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 11 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 13 },
},
};
const showSatellite = (values) => {
onShow(values);
};
return (
<Form {...formItemLayout} className="sat-setting" onFinish={showSatellite}>
<Form.Item
label="Longitude (degrees)"
name="longitude"
rules={[
{
required: true,
message: "Please input your Longitude",
},
]}
>
<InputNumber
min={-180}
max={180}
style={{ width: "100%" }}
placeholder="Please input Longitude"
/>
</Form.Item>
<Form.Item
label="Latitude (degrees)"
name="latitude"
rules={[
{
required: true,
message: "Please input your Latitude",
},
]}
>
<InputNumber
placeholder="Please input Latitude"
min={-90}
max={90}
style={{ width: "100%" }}
/>
</Form.Item>
<Form.Item
label="Elevation (meters)"
name="elevation"
rules={[
{
required: true,
message: "Please input your Elevation",
},
]}
>
<InputNumber
placeholder="Please input Elevation"
min={-413}
max={8850}
style={{ width: "100%" }}
/>
</Form.Item>
<Form.Item
label="Altitude (degrees)"
name="altitude"
rules={[
{
required: true,
message: "Please input your Altitude",
},
]}
>
<InputNumber
placeholder="Please input Altitude"
min={0}
max={90}
style={{ width: "100%" }}
/>
</Form.Item>
<Form.Item
label="Duration (secs)"
name="duration"
rules={[
{
required: true,
message: "Please input your Duration",
},
]}
>
<InputNumber
placeholder="Please input Duration"
min={0}
max={90}
style={{ width: "100%" }}
/>
</Form.Item>
<Form.Item className="show-nearby">
<Button
type="primary"
htmlType="submit"
style={{ textAlign: "center" }}
>
Find Nearby Satellite
</Button>
</Form.Item>
</Form>
);
};
export default SatSetting;
|
import React from "react";
import databaseScores from "./DatabaseScores";
import ExamScore from "./ExamScore";
import 'bootstrap/dist/css/bootstrap.min.css';
function Scores(){
function makeExamScore(obj){
return <ExamScore name={obj.name} score={obj.score}/>
}
return (
<div>
<div className="container-fluid">
<table id="total votes" className="table table-hover text-centered">
<thead>
<tr>
<th>Exam Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{databaseScores.map(makeExamScore)}
</tbody>
</table>
</div>
</div>
)
}
export default Scores;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.