text
stringlengths
7
3.69M
// Create express app var express = require('express'); var app = express(); var cors = require('cors'); var db = require('./database.js'); app.use(cors()); // ? // Server port var HTTP_PORT = 8000; // Start server app.listen(HTTP_PORT, () => { console.log('Server running on port %PORT%'.replace('%PORT%', HTTP_PORT)); }); // Root endpoint // when connecting to localhost app.get('/', (req, res, next) => { res.json({ message: 'Ok' }); }); // Insert here other API endpoints // get all todos app.get('/api/todos', (req, res, next) => { console.log('HEJ'); var sql = 'select * from todos'; var params = []; db.all(sql, params, (err, rows) => { if (err) { res.status(400).json({ error: err.message }); return; } res.json({ message: 'success', data: rows, }); }); }); app.put('/api/todos/:message', (req, res, next) => { console.log(req.body); console.log(req.params); var insert = 'INSERT INTO todos (data, completed) VALUES (?,?)'; db.run(insert, [req.params.message, false]); res.status(200).json({ success: 'true' }); }); app.delete('/api/todos/:message', (req, res, next) => { var deleter = 'DELETE from todos WHERE data=?'; db.run(deleter, req.params.message); res.status(200).json({ success: 'true' }); }); // Default response for any other request app.use(function (req, res) { res.status(404); });
var { IEnumerable } = require("./IEnumerable"); class IGrouping extends IEnumerable { constructor(key, source) { super(function* () { yield* source; }); this._key = key; } get Key() { return this._key; } } module.exports = { IGrouping };
// Core import React from 'react'; import { render } from 'react-dom'; // Router import {Router, Route, browserHistory} from 'react-router'; // Components import App from './components/App'; import StreamPicker from './components/StreamPicker'; // Routes var routes = ( <Router history={browserHistory}> <Route path="/" component={StreamPicker}/> <Route path="*" component={App}/> </Router> ); render(routes, document.querySelector('#main'));
var Stream = require('stream').Stream, util = require('util'), spawn = require('child_process').spawn; var GZipStream = function() { // readable stream this.readable = true; // writable stream this.writable = true; this._gzipper = spawn('gzip'); // emit data at some point this._gzipper.stdout.on('data', this.emit.bind(this, 'data')); // emit end at some point this._gzipper.on('exit', this.emit.bind(this, 'end')); }; // this is a custom stream object util.inherits(GZipStream, Stream); // implement write, process some data GZipStream.prototype.write = function(data) { if(this._gzipper.stdin.writable) { this._gzipper.stdin.write(data); } }; // implement end GZipStream.prototype.end = function(data) { // shut down processing this.readable = false; this.writable = false; // clean up this._gzipper.stdin.end(); this._gzipper = null; }; module.exports = GZipStream;
// -------------------------------- // ------- GLOBAL VARIABLES ------- // -------------------------------- // size of square tiles in pixels const SQUARE_SIZE = 20; // Informations about the game status const game = { status: "playing", score: 0, speed: 40 } // Game boards characteristcs const width = 20 const height =20 const color = "green" // Snake characteristics const snake = { color_head:"pink", color_body: "blue", head: {x: width/2, y: height/2}, length: 4, direction: RIGHT, body: [ {x: width/2, y: height/2}, {x: width/2 - 1, y: height/2}, {x: width/2 - 2, y: height/2}, {x: width/2 - 3, y: height/2}, ] } // fruit object const fruit = { pos: {x: 0, y: 0}, color: "red", spawned: false, } // ------------------------- // ------- FUNCTIONS ------- // ------------------------- // Main Drawing function, you should put all of the things that you want to draw in this function function draw() { draw_board(width, height, color) draw_snake() draw_square(fruit.pos.x,fruit.pos.y,fruit.color,fruit.color) } // Main loop function, this function is called every "game.speed" milliseconds. function loop() { if (game.status==="playing"){ move_snake() spawn_fruit() const fruit_eaten = eat_fruit() snake_body_movement(snake.body,snake.length,snake.head,) } } // This function is called when a key is pressed function onKeyDown(key_pressed) { if (key_pressed === ARROW_UP && snake.direction !== DOWN) { snake.direction = UP } if (key_pressed === ARROW_DOWN && snake.direction !== UP) { snake.direction = DOWN } if (key_pressed === ARROW_LEFT && snake.direction !== RIGHT) { snake.direction = LEFT } if (key_pressed === ARROW_RIGHT && snake.direction !== LEFT) { snake.direction = RIGHT } } // --- Functions that they will have to do --- // Handle the snake function move_snake () { if (snake.direction === UP) { if(snake.head.y===0){ snake.head.y=height-1 } else { snake.head.y = snake.head.y - 1 } } if (snake.direction === DOWN) { if(snake.head.y===height - 1){ snake.head.y=0 } else { snake.head.y = snake.head.y + 1 } } if (snake.direction === LEFT) { if(snake.head.x===0){ snake.head.x=width - 1 } else { snake.head.x = snake.head.x - 1 } } if (snake.direction === RIGHT) { if(snake.head.x===width -1){ snake.head.x= 0 } else { snake.head.x = snake.head.x+ 1 } } } function draw_snake() { draw_square (snake.head.x,snake.head.y,snake.color_head,snake.color_head) draw_snake_body (snake.body,snake.length,snake.color_body) } // Handle the fruit function spawn_fruit(){ if (fruit.spawned===false) { fruit.pos.x=get_random_number(0,width-1) fruit.pos.y=get_random_number(0,height-1) fruit.spawned=true } }function eat_fruit() { if(snake.head.y ===fruit.pos.y && snake.head.x ===fruit.pos.x){ fruit.spawned = false snake.length = snake.length+1 game.score = game.score + 100 update_score(game.score) return true }else{ return false } }
const midLogin = (req, res, next) => { let logged = true; if(logged) next(); else res.send('No tiene permisos de acceso'); } module.exports = midLogin;
const express = require('express') const bodyParser = require('body-parser'); const cors = require('cors') const ObjectId = require('mongodb').ObjectId; const app = express(); app.use(bodyParser.json()); app.use(cors()) require('dotenv').config() const MongoClient = require('mongodb').MongoClient; const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.4ioes.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); app.get('/',(req,res)=>{ res.send("Party Maker Working") }) client.connect(err => { const orderCollection = client.db("partyMaker").collection("orderList"); const serviceCollection = client.db("partyMaker").collection("services"); const reviewCollection = client.db("partyMaker").collection("review"); const adminCollection = client.db("partyMaker").collection("admin"); app.post('/addService', (req, res) => { const newService = req.body; console.log('adding new event: ', newService) serviceCollection.insertOne(newService) .then(result => { console.log('inserted count', result.insertedCount); res.send(result.insertedCount > 0) }) }) app.get('/service',(req,res)=>{ serviceCollection.find() .toArray((err,documents)=>{ res.send(documents) }) }) app.get('/service/:title', (req, res) => { serviceCollection.find({title: req.params.title}) .toArray( (err, documents) => { res.send(documents[0]); }) }) app.post('/addOrder', (req, res) => { const newOrder = req.body; orderCollection.insertOne(newOrder) .then(result => { res.send(result.insertedCount > 0); }) }) app.get('/orderDetails',(req,res)=>{ orderCollection.find() .toArray((err,documents)=>{ res.send(documents) }) }) app.get('/userOrder',(req,res)=>{ orderCollection.find({email: req.query.email}) .toArray((err,documents)=>{ res.send(documents) }) }) app.post('/addReview', (req, res) => { const newReview = req.body; console.log('adding new event: ', newReview) reviewCollection.insertOne(newReview) .then(result => { console.log('inserted count', result.insertedCount); res.send(result.insertedCount > 0) }) }) app.post('/addAdmin', (req, res) => { const newAdmin = req.body; console.log('adding new event: ', newAdmin) adminCollection.insertOne(newAdmin) .then(result => { console.log('inserted count', result.insertedCount); res.send(result.insertedCount > 0) }) }) app.get('/review',(req,res)=>{ reviewCollection.find() .toArray((err,documents)=>{ res.send(documents) }) }) app.get('/admin', (req, res) => { adminCollection.find({}) .toArray((err, documents) => { res.send(documents); }) }); app.post('/isAdmin', (req, res) => { const email = req.body.email; adminCollection.find({ email: email }) .toArray((err, admin) => { res.send(admin.length > 0); }) }) app.patch('/updateOrder/:id',(req,res)=>{ orderCollection.updateOne({_id: ObjectId(req.params.id)}, { $set: {status: req.body.status} }) .then(result=>{ res.send(result.modifiedCount > 0) }) }) app.delete('/deleteService/:id', (req, res) => { const id = req.params.id; serviceCollection.deleteOne({_id: ObjectId(req.params.id)}) .then(result => { res.send(result.deletedCount > 0) }) }) }); app.listen(process.env.PORT || 5000)
'use strict'; var app = angular.module('app', ['ngAnimate', 'ui.grid', 'ui.grid.edit', 'ui.bootstrap', 'angularjs-dropdown-multiselect']); app.controller('MainCtrl', ['$scope', '$modal', '$http', 'uiGridConstants', function ($scope, $modal, $http, uiGridConstants) { $scope.gridOptions = { showFooter: true, enableSorting: true, columnDefs: [ { field: 'prefix', enableHiding: false, suppressRemoveSort: true, cellFilter: 'nullify', cellClass: nullify, menuItems: [ { title: 'Filter', icon: 'ui-grid-icon-filter', action: function() { $scope.open(this.context); } } ] }, { field: 'first', enableHiding: false, suppressRemoveSort: true, cellFilter: 'nullify', cellClass: nullify, menuItems: [ { title: 'Filter', icon: 'ui-grid-icon-filter', action: function() { $scope.open(this.context); } } ] }, { field: 'last', enableHiding: false, suppressRemoveSort: true, cellFilter: 'nullify', cellClass: nullify, menuItems: [ { title: 'Filter', icon: 'ui-grid-icon-filter', action: function() { $scope.open(this.context); } } ] }, { field: 'gender', enableHiding: false, suppressRemoveSort: true, cellFilter: 'nullify', cellClass: nullify, menuItems: [ { title: 'Filter', icon: 'ui-grid-icon-filter', action: function() { $scope.open(this.context); } } ] }, { field: 'height', enableHiding: false, suppressRemoveSort: true, cellFilter: 'nullify', aggregationType: 'Mode', cellClass: nullify, menuItems: [ { title: 'Filter', icon: 'ui-grid-icon-filter', action: function() { $scope.open(this.context); } } ] }, { field: 'weight', enableHiding: false, suppressRemoveSort: true, cellFilter: 'nullify', aggregationType: 'Range', cellClass: nullify, menuItems: [ { title: 'Filter', icon: 'ui-grid-icon-filter', action: function() { $scope.open(this.context); } } ] }, { field: 'age', enableHiding: false, suppressRemoveSort: true, cellFilter: 'nullify', aggregationType: 'Standard Deviation', cellClass: nullify, menuItems: [ { title: 'Filter', icon: 'ui-grid-icon-filter', action: function() { $scope.open(this.context); } } ] }, { field: 'has_nose', enableHiding: false, suppressRemoveSort: true, cellFilter: 'nullify', cellClass: nullify, menuItems: [ { title: 'Filter', icon: 'ui-grid-icon-filter', action: function() { $scope.open(this.context); } } ] } ] }; // add styles to NULL cells function nullify(grid, row, col, rowRenderIndex, colRenderIndex) { if (grid.getCellValue(row,col) === null || grid.getCellValue(row,col) === "") { return 'null-cell'; } } // TODO Change: Load the stub data $http.get('data/100.json').success(function(data) { $scope.gridOptions.data = data; }); // Modal Filter $scope.open = function (context) { $scope.context = context; var modalInstance = $modal.open({ templateUrl: 'filter.html', controller: 'ModalInstanceCtrl', windowClass: 'modal-'+context.col.colDef.type, resolve: { context: function() { return $scope.context; } } }); // After OK modalInstance.result.then(function (context) { var name = context.col.colDef.name; var type = context.col.colDef.type; var selected = context.msselected; var rows = context.col.grid.rows; // Filter out max/min if (type === "number") { if (typeof context.min == "number") { selected = selected.filter(function(e) { return e.id >= context.min; }); } if (typeof context.max == "number") { selected = selected.filter(function(e) { return e.id <= context.max; }); } } // Filter out rows rows.forEach( function(row) { var entry = row.entity[name]; if (entry !== null) { (selected.has(entry, "id")) ? row.clearRowInvisible(row) : row.setRowInvisible(row); } else { (selected.has("NULL", "id")) ? row.clearRowInvisible(row) : row.setRowInvisible(row); } }); // Apply aggregation if (context.aggregate) { context.col.aggregationType = context.aggregate; } }); }; }]); // Replace null values with the string "NULL" app.filter('nullify', function($filter) { return function(input) { return (input == null || input === "") ? 'NULL' : input; }; }); // Helper method Array.prototype.has = function(e, property) { for (var i=0; i<this.length; i++){ if (this[i][property] == e) return true; } return false; } Array.prototype.max = function (property) { var arr = this.map(function (e) { return e[property]; }); return Math.max.apply(Math, arr); }; Array.prototype.min = function (property) { var arr = this.map(function (e) { return e[property]; }); return Math.min.apply(Math, arr); }; // Modal Filter angular.module('ui.bootstrap').controller('ModalInstanceCtrl', function ($scope, $modalInstance, context) { $scope.name = context.col.colDef.name; $scope.type = context.col.colDef.type; var col = context.col.grid.getColumn($scope.name); var rows = context.col.grid.rows; $scope.mssettings = {displayProp: 'label', idProp: 'label', scrollableHeight: '200px', scrollable: true}; // Build MultiSelect Data Structure $scope.msdata = []; $scope.msselected = []; var flag = false; // check if NULL already added rows.forEach( function(row) { var entry = row.entity[$scope.name]; if (!$scope.msdata.has(entry, "label")) { if (entry !== null) { $scope.msdata.push({id: $scope.msdata.length, label: entry}); if (row.visible) $scope.msselected.push({id: entry}); } else if(!flag) { $scope.msdata.push({id: $scope.msdata.length, label: "NULL"}); if (row.visible) $scope.msselected.push({id: "NULL"}); flag = true; } } }); $scope.msdata.sort(function (a, b) { if (a.label == "NULL") return 1; // keep null at the bottom if (b.label == "NULL") return -1; if (a.label > b.label) return 1; if (a.label < b.label) return -1; return 0; }); // Additional filters for numbers if ($scope.type === "number") { // Aggregate $scope.filter = {}; $scope.filter.min = $scope.msdata.min('label'); $scope.filter.max = $scope.msdata.max('label'); $scope.msaggselected = {}; $scope.msaggdata = [ {id: 1, label: "Sum"}, {id: 2, label: "Average"}, {id: 3, label: "Min"}, {id: 4, label: "Max"}, {id: 5, label: "Mode"}, {id: 6, label: "Range"}, {id: 7, label: "Standard Deviation"}]; $scope.mssettingssingle = {selectionLimit: 1, dynamicTitle: true, showUncheckAll: false, closeOnSelect: true, scrollableHeight: '100px', scrollable: true, smartButtonMaxItems: 1, smartButtonTextConverter: function(itemText, originalItem) { return itemText; }}; } $scope.ok = function () { context.msselected = $scope.msselected; if ($scope.type === "number") { context.min = $scope.filter.min; context.max = $scope.filter.max; ($scope.msaggselected.id-1 >= 0) ? context.aggregate = $scope.msaggdata[$scope.msaggselected.id-1].label : context.aggregate = undefined; } $modalInstance.close(context); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; });
import React, { Component } from 'react'; import { View, Text, StyleSheet, Dimensions, TouchableOpacity, Image } from 'react-native'; const width_R = Math.round(Dimensions.get('window').width/5) const height_R= Math.round(Dimensions.get('window').height/8.5) const added = width_R+height_R const circle = Math.round(added/2) class Quotes extends Component { constructor(props) { super(props); this.state = { }; } // Go Sentences screen goSentenceScreen(lan){ this.props.navigation.navigate('Sentences',{data: lan}); } render() { return ( <View style={styles.container}> <View style={{flex:2, flexDirection:'row'}}> <View style={{flex:1, justifyContent:'center', alignItems:'center'}}> <Text style={{ color:'#1a1a1a', fontSize: 65, fontWeight:'bold' }}>Quotes</Text> <Text style={{ fontStyle:'italic', fontSize: 20 }}>Learn With Sentences</Text> </View> </View> <View style={{flex:2, flexDirection:'row'}}> <View style={styles.itemContainer}> <TouchableOpacity onPress={() => this.goSentenceScreen("en")} style={styles.rounded}> <Image style={{flex:1 ,resizeMode: 'contain' }} source={require('../../../images/en512.png')} /> </TouchableOpacity> <Text>English</Text> </View> <View style={styles.itemContainer}> <TouchableOpacity onPress={() => this.goSentenceScreen("fr")} style={styles.rounded}> <Image style={{flex:1 ,resizeMode: 'contain' }} source={require('../../../images/fr512.png')} /> </TouchableOpacity> <Text>French</Text> </View> </View> <View style={{flex:2, flexDirection:'row', justifyContent:'center'}}> <View style={styles.itemContainer}> <TouchableOpacity onPress={() => this.goSentenceScreen("tr")} style={styles.rounded}> <Image style={{flex:1 ,resizeMode: 'contain' }} source={require('../../../images/tr512.png')} /> </TouchableOpacity> <Text>Turkish</Text> </View> <View style={styles.itemContainer}> <TouchableOpacity onPress={() => this.goSentenceScreen("es")} style={styles.rounded}> <Image style={{flex:1 ,resizeMode: 'contain' }} source={require('../../../images/es512.png')} /> </TouchableOpacity> <Text>Spanish</Text> </View> </View> <View style={{flex:2, flexDirection:'row'}}> <View style={styles.itemContainer}> <TouchableOpacity onPress={() => this.goSentenceScreen("pr")} style={styles.rounded}> <Image style={{flex:1 ,resizeMode: 'contain' }} source={require('../../../images/pr512.png')} /> </TouchableOpacity> <Text>Portuguese</Text> </View> <View style={styles.itemContainer}> <TouchableOpacity onPress={() => this.goSentenceScreen("it")} style={styles.rounded}> <Image style={{flex:1 ,resizeMode: 'contain' }} source={require('../../../images/it512.png')} /> </TouchableOpacity> <Text>Italian</Text> </View> </View> </View> ); } } const styles = StyleSheet.create({ container:{ flex:1 }, itemContainer:{ flex:2, justifyContent:'center', alignItems:'center' }, rounded:{ width: circle, height: circle, overflow: 'hidden', alignItems: 'center', justifyContent:'center', }, image: { flex: 1 } }) export default Quotes;
var studentName; console.log(typeof studentName); // "undefined" console.log(typeof doesntExist); // "undefined" console.log(typeof studentName === typeof doesntExist) // true
import React, { useRef, useEffect } from 'react'; import * as d3 from 'd3'; import classes from './tinyAxis.module.css'; const TinyAxis = ({ dimensions, xScale, yScale }) => { const xTinyAxisRef = useRef(null); const yTinyAxisRef = useRef(null); const xAxis = d3.axisTop(); const yAxis = d3.axisLeft(); useEffect(() => { doAxis(); }); const doAxis = () => { const xRef = d3.select(xTinyAxisRef.current); const yRef = d3.select(yTinyAxisRef.current); xAxis.scale(xScale).ticks(d3.timeDay.every(90)); yAxis.scale(yScale).ticks(2,',.0f'); xRef.call(xAxis.tickSize(10).tickFormat(d3.timeFormat("%b"))) yRef.call(yAxis.tickSize(10)); }; return ( <> <g ref={xTinyAxisRef} className={classes.tinyAxisGroupX} transform={`translate(0,${dimensions.height - dimensions.margin.top})`} ></g> <g ref={yTinyAxisRef} className={classes.tinyAxisGroupY} transform={`translate(${dimensions.width-dimensions.margin.left}, 0)`} ></g> </> ); }; export default TinyAxis;
import React, { Component } from "react"; import RouletteWheel from "assets/roulette-wheel.png"; import RouletteWheelLight from "assets/roulette-wheel-light.png"; import Konva from "konva"; import PropTypes from "prop-types"; import Sound from "react-sound"; import { getAppCustomization } from "../../lib/helpers"; import rouletteSound from "assets/roulette-sound.mp3"; import ballSound from "assets/ball-stop-sound.mp3"; import "./index.css"; const numberAngles = { 0: 360, 1: 224, 2: 58, 3: 340, 4: 38, 5: 185, 6: 98, 7: 301, 8: 156, 9: 262, 10: 175, 11: 136, 12: 321, 13: 116, 14: 243, 15: 19, 16: 204, 17: 78, 18: 282, 19: 29, 20: 233, 21: 48, 22: 272, 23: 166, 24: 195, 25: 68, 26: 350, 27: 107.5, 28: 310, 29: 291, 30: 146, 31: 252, 32: 9, 33: 214, 34: 88, 35: 330, 36: 126 }; const mobileBreakpoint = 768; let anim = null; let endAnim = null; export default class Roulette extends Component { static propTypes = { result: PropTypes.number, bet: PropTypes.bool, onAnimation: PropTypes.func.isRequired }; static defaultProps = { result: null, bet: false }; state = { ballStop: false }; componentDidMount() { const stageSize = 270; const stage = new Konva.Stage({ container: "container", width: stageSize, height: stageSize }); const layer = new Konva.Layer(); const ball = new Konva.Circle({ x: stageSize / 2, y: stageSize / 2, width: 14, height: 14, fill: "white", offset: { x: 0, y: 84 }, opacity: 0 }); layer.add(ball); stage.add(layer); let angle = 0; endAnim = new Konva.Animation(() => { const { result, onAnimation } = this.props; ball.rotation(angle); angle += 3; if (angle >= 361) { angle = 0; } if ( angle >= numberAngles[result] - 2 && angle < numberAngles[result] + 2 ) { endAnim.stop(); this.setState({ ballStop: false }); ball.rotation(numberAngles[result]); if (document.documentElement.clientWidth <= mobileBreakpoint) { setTimeout(() => { onAnimation(false); }, 1000); } else { onAnimation(false); } } }, layer); anim = new Konva.Animation(() => { ball.opacity(1); ball.rotation(angle); angle += 6; if (angle >= 361) { angle = 0; } }, layer); } componentDidUpdate(prevProps) { const { result, bet, onAnimation } = this.props; if (!bet) { return; } if (result !== prevProps.result) { anim.start(); onAnimation(true); setTimeout(() => { anim.stop(); endAnim.start(); this.setState({ ballStop: true }); }, 2000); } } renderSound = () => { const soundConfig = localStorage.getItem("sound"); if (soundConfig !== "on" || !anim || !anim.isRunning()) { return null; } return ( <Sound volume={100} url={rouletteSound} playStatus="PLAYING" autoLoad /> ); }; renderBallStopSound = () => { const soundConfig = localStorage.getItem("sound"); const { ballStop } = this.state; if (soundConfig !== "on" || !endAnim || !ballStop) { return null; } return <Sound volume={100} url={ballSound} playStatus="PLAYING" autoLoad />; }; render() { const isLight = getAppCustomization().theme === "light"; return ( <div> <div styleName="container" id="container" style={{ backgroundImage: `url(${isLight ? RouletteWheelLight : RouletteWheel})` }} /> {this.renderSound()} {this.renderBallStopSound()} </div> ); } }
// Write your JavaScript code. $(function () { $(".heading-compose").click(function () { $(".side-two").css({ "left": "0" }); }); $(".newMessage-back").click(function () { $(".side-two").css({ "left": "-100%" }); }); }) // Stop carousel $('.carousel').carousel({ interval: false });
import TaskItem from './TaskItem'; const Todos = ({todos,deletTodoItem,handleIsDone,triggerEditColumn,handleSave}) =>( <div className="todos"> {todos?.map((item)=>(<TaskItem key={item.id} pk={item.id} deletTodoItem={deletTodoItem} handleSave={handleSave} handleIsDone={handleIsDone} todo={item} triggerEditColumn={triggerEditColumn}/>))} </div> ) export default Todos;
const express = require('express'); const routes = express.Router(); routes.get('/',(request, response)=>{ response.send('Welcome to the Home Page'); }); routes.post('/register', async (request, response)=>{ let userObject = request.body; const userOperations = require('../db/services/useroperations'); let result =await userOperations.register(userObject); if(result && result._id){ response.status(200).json({message:'Record added Successfully'}); } else{ response.status(200).json({message:'Record Not added'}); } }); routes.post('/login', async (request, response)=>{ let userObject = request.body; const userOperations = require('../db/services/useroperations'); const adminOperations = require('../db/services/adminoperations'); let adminresult = await adminOperations.admin(userObject); let result = await userOperations.login(userObject); if(result && result._id){ response.status(200).json({message:'Welcome '+result.name}); console.log('Login Result is ', result); } else{ if(adminresult && adminresult._id){ response.status(200).json({message:'Admin '+adminresult.name}); console.log('Login Result is ', adminresult); } else { response.status(200).json({message: 'Invalid Userid or Password'}); } } } ); module.exports = routes;
import React,{ Component } from 'react'; import { StyleSheet, Text , View } from 'react-native'; const styles = StyleSheet.create({ red: { color : 'red', fontWeight: 'bold', fontSize: 30, }, blue: { color : 'blue', }, }); class Greeting extends Component{ render(){ return ( <View style={{alignItems: 'center'}}> <Text style={styles.red}>Hello {this.props.name}! Your age is {this.props.age}</Text> <Text style={styles.blue}>Hello {this.props.name}! Your age is {this.props.age}</Text> </View> ); } } export default class LotsOfGreetings extends Component { render(){ return ( <View style={{alignItems:'center',top : 150}}> <Greeting name='Chandan' age = {22} ></Greeting> <Greeting name='Rawat' age = {22}></Greeting> <Greeting name='Bhujel' age = {22}></Greeting> </View> ); } }
// helper class to wrap node including its meshInstances class BakeMeshNode { constructor(node, meshInstances = null) { this.node = node; this.component = node.render || node.model; meshInstances = meshInstances || this.component.meshInstances; // original component properties this.store(); this.meshInstances = meshInstances; // world space aabb for all meshInstances this.bounds = null; // render target with attached color buffer for each render pass this.renderTargets = []; } store() { this.castShadows = this.component.castShadows; } restore() { this.component.castShadows = this.castShadows; } } export { BakeMeshNode };
const buttonUser = $('.press-button'); const result = $('.result'); const buttonAdmin = $('.button_admin'); const adminButton = $('.admin-button'); const adminForm = $('.admin-form'); const buttonRuleCancel = $('.button_rule-cancel'); const converterForm = $('.converter-form'); const addRuleButton = $('.button_rule-add'); const placeValueUnitShot = $('#placeValueUnitShot'); const placeValueUnitFull = $('#placeValueUnitFull'); const placeValueCoefficient = $('#placeValueCoefficient'); $.getJSON("data.json").done( function(json) { if ((typeof json) != "object") {json = JSON.parse(json)}; let valToMeter = { m: 1, cm: .01, in: .0254, ft: .3048, // mm: .001, // yd: .9144, // km: 1000, // mile: 1609.3 }; $(".get").text(`Вход: ${JSON.stringify(json)}`); let jsonResult = JSON.stringify(convertApp(json)); $(".set").text(`Выход: ${jsonResult}`); $('#convertValueUnit').val(json.distance.unit); $('#convertValueNumber').val(json.distance.value ); $('#convertValueUnitNew').val(json.convert_to); convertApp(json); let resultValue = $(".result__value"); if (convertApp(json).value >= 0.01) { resultValue.text(convertApp(json).value) } else { resultValue.text("~ 0"); } let resultValueSolution = $(".result__value-solution"); if (convertApp(json).value >= 0.01) { resultValueSolution.text(`( ${roundTo(json.distance.value)} ${json.distance.unit} = ${convertApp(json).value} ${convertApp(json).unit} )`); } else { resultValueSolution.text() = resultValueSolution.text(`( ${roundTo(json.distance.value)} ${json.distance.unit} ~ 0 ${convertApp(json).unit} )`); } buttonUser.toggleClass("hideblock"); result.toggleClass("hideblock"); function roundTo(number, pow = 2) { let multiplier = Math.pow(10, pow); return Math.round(number * multiplier) / multiplier; }; function convertApp(conv) { let newValueNum = roundTo(conv.distance.value * valToMeter[conv.distance.unit] / valToMeter[conv.convert_to]); let resultApp = {unit: conv.convert_to, value: newValueNum}; return resultApp; } function addRule() { if (placeValueUnitShot.val() && placeValueUnitFull.val() && (placeValueCoefficient.val() != "")) { $("#convertValueUnit, #convertValueUnitNew").append(`<option value="${placeValueUnitShot.val()}">${placeValueUnitFull.val()}</option>`) valToMeter[placeValueUnitShot.val()] = Number(parseFloat(placeValueCoefficient.val())); } }; function showResult(json) { } $('#convertValueUnit').on("input", function(){ const target = $(this); if ($("#convertValueUnit").val() === $("#convertValueUnitNew").val() ) { $("#convertValueUnitNew").val(""); } let convertValList = $("#convertValueUnitNew > option"); convertValList.each(function(i, el) { if ($(el).val() === target.val()){ $(el).toggleClass("hideblock"); } else { if ($(el).hasClass("hideblock")) {$(el).toggleClass("hideblock")}; } }); }); $(".convert-value__number, .place-value__coefficient").on("input", function() { $(this).val($(this).val().replace(/[^0-9.]/g, '').replace( /^([^\.]*\.)|\./g, '$1' )); }); buttonUser.on("click", function(){ const target = $(this); const unitVal = $('#convertValueUnit'); const valueValReplace = $('#convertValueNumber'); const convertVal = $('#convertValueUnitNew'); if ((valueValReplace.val()) && (convertVal.val() != "")) { json.distance.unit = unitVal.val(); json.distance.value = valueValReplace.val(); json.convert_to = convertVal.val(); $(".change").text(`Изменения: ${JSON.stringify(json)}`); $(".change").css('backgroundColor', '#ffffff'); target.toggleClass("hideblock"); result.toggleClass("hideblock"); convertApp(json); jsonResult = JSON.stringify(convertApp(json)); $(".set").text(`Выход: ${jsonResult}`); showResult(convertApp(json)) let resultValue = $(".result__value"); if (convertApp(json).value >= 0.01) { resultValue.text(convertApp(json).value) } else { resultValue.text("~ 0"); } let resultValueSolution = $(".result__value-solution"); if (convertApp(json).value >= 0.01) { resultValueSolution.text(`( ${roundTo(json.distance.value)} ${json.distance.unit} = ${convertApp(json).value} ${convertApp(json).unit} )`); } else { resultValueSolution.text() = resultValueSolution.text(`( ${roundTo(json.distance.value)} ${json.distance.unit} ~ 0 ${convertApp(json).unit} )`); } } else { alert("Ошибка введения данных"); }; }); $('#convertValueUnit, #convertValueNumber, #convertValueUnitNew').on("click", function(){ if (buttonUser.hasClass("hideblock")) { buttonUser.toggleClass("hideblock"); result.toggleClass("hideblock"); }; }); buttonAdmin.on("click", function(){ adminButton.toggleClass('hideblock'); converterForm.toggleClass('hideblock'); adminForm.toggleClass('hideblock'); placeValueUnitShot.val(''); placeValueUnitFull.val(''); placeValueCoefficient.val(''); if (!addRuleButton.hasClass("noactive")){ addRuleButton.addClass("noactive"); }; }); buttonRuleCancel.on("click", function(){ converterForm.toggleClass('hideblock'); adminForm.toggleClass('hideblock'); adminButton.toggleClass('hideblock'); }); addRuleButton.on("click", function(){ if (!addRuleButton.hasClass("noactive")){ addRule(); adminButton.toggleClass('hideblock'); converterForm.toggleClass('hideblock'); adminForm.toggleClass('hideblock'); }; }); adminForm.on("input", function(){ if (placeValueUnitShot.val() && placeValueUnitFull.val() && (placeValueCoefficient.val() != "")) { if (addRuleButton.hasClass("noactive")){ addRuleButton.removeClass("noactive"); }; } else { if (!addRuleButton.hasClass("noactive")){ addRuleButton.addClass("noactive"); }; } }) });
db.superheroes.deleteMany({publisher:"George Lucas"})
$(document).ready(function () { insertar(); }); var insertar=function () { $(document).on('click','#buscar',function () { var buscar=$('#buscador').val(); console.log(buscar); $.ajax({ url: 'https://api.giphy.com/v1/gifs/translate?api_key=bb2006d9d3454578be1a99cfad65913d&s='+buscar, type: 'GET', dataType: 'json', data:{ } }).done(function(response) { // $("#contenedor").html(response.data.images.original.url); dibujar(response.data.images.original.url); console.log(response) }).fail(function(e) { console.error(e); }).always(function(){ }); }) } var dibujar= function (value) { $("#contenedor").html('<img src="'+value+'">'); console.log(value); }
'use strict'; app.controller('EmployeeController', ['$rootScope','$scope','$state','$timeout','roleBtnService',function($rootScope, $scope, $state, $timeout,roleBtnService) { var roleBtnUiClass = "app.employee.";//用于后台查找按钮权限 roleBtnService.getRoleBtnService(roleBtnUiClass,$scope); var url = app.url.employee.orgUnits; // 后台API路径 var data = null; // 从后台获取数据 app.utils.getData(url, function callback(dt){ data = dt; initData(); $scope.loading = false; $scope.loading_sub = false; }); $scope.reload = function(){ $timeout(function(){ $scope.init(); }, 200); }; var nodes = {}; var treeData = []; // 构造节点 function setNode(dt) { if (!nodes['id' + dt['id']]) { var node = {}; } else { return nodes['id' + dt['id']]; } node['label'] = dt.name || '没有名字'; node['data'] = dt.id || '没有数据'; node['children'] = node['children'] || []; node['onSelect'] = item_selected; node['FLongNumber'] =dt.FLongNumber; node['unitLayer'] = dt.unitLayer; node['parent']= dt.parent; if (dt['parent']) { setParentNode(node, dt['parent']); // 若存在父节点,则先构造父节点 } else { node['parent'] = null; } nodes['id' + dt['id']] = node; return node; } // 构造父节点 function setParentNode(node, id) { var len = data.length; for (var i = 0; i < len; i++) { if (data[i]['id'] === id) { var parentNode = setNode(data[i]); parentNode['children'].push(node); } } } // 列表树数据 $scope.tree_data = []; $scope.org_tree = {}; // 初始化数据并生成列表树所需的数据结构 function initData() { //data = formatData(data); var len = data.length; for (var i = 0; i < len; i++) { var node = setNode(data[i]); if (node['parent'] === null) { treeData.push(node); } } var container_a = [], container_b = [], ln = treeData.length; for(var i=0; i<ln; i++){ if(treeData[i].children.length !== 0){ treeData[i].expanded = true; container_a.push(treeData[i]); } else{ container_b.push(treeData[i]); } } treeData = container_a.concat(container_b); // 列表树数据传值 $scope.tree_data = treeData; $timeout(function(){ // 默认选中第一个节点 // $scope.org_tree.select_first_branch(); try { $scope.init(); } catch (e) { } }, 400); } var thisBranch; // 选择列表树中的一项 var item_selected = function(branch) { thisBranch=branch; if(branch.unitLayer){ $rootScope.FLongNumber = branch.FLongNumber; $rootScope.id = null; }else{ $rootScope.FLongNumber = null; $rootScope.id = branch.data; } $rootScope.ids = []; $scope.setBtnStatus(); $scope.init(); }; // 选择列表树中的一项 var tree_handler = function(branch) { $state.go('app.employee.list'); }; $scope.click = function(){}; var status_false = { only : true, single : true, locked : true, mutiple : true }; var status = { only : false, single : true, locked : true, mutiple : true }; // 添加员工(工具栏按钮) $scope.addUnit = function(){ if(!$scope.org_tree.get_selected_branch()||!(!thisBranch.unitLayer||thisBranch.unitLayer==3)){ mask.insertBefore(container); $("#msgP").html("只能在部门或者职位下添加职员!"); container.removeClass('none'); doIt = function(){ $rootScope.cancel(); }; }else{//只能在部门或者职位下添加职员 sessionStorage.removeItem("orgId"); sessionStorage.removeItem("FLongNumber"); sessionStorage.removeItem("orgName"); sessionStorage.removeItem("positionId"); sessionStorage.removeItem("positionName"); if(thisBranch.FLongNumber){//是职员 sessionStorage.setItem("orgId", thisBranch.data); sessionStorage.setItem("FLongNumber", thisBranch.FLongNumber); sessionStorage.setItem("orgName", thisBranch.label); }else{//是职位 var p = app.utils.getDataByKey(data,"id",thisBranch.parent); sessionStorage.setItem("orgId", p.id); sessionStorage.setItem("FLongNumber", p.FLongNumber); sessionStorage.setItem("orgName", p.name); sessionStorage.setItem("positionId", thisBranch.data); sessionStorage.setItem("positionName", thisBranch.label); } setStatus(status_false); $state.go('app.employee.add'); } }; // 编辑某一员工(工具栏按钮) $scope.editIt = function(){ sessionStorage.setItem("id", $rootScope.ids[0]); setStatus(status_false); $state.go('app.employee.edit'); }; var mask = $('<div class="mask"></div>'); var container = $('#dialog-container'); var dialog = $('#dialog'); var hButton = $('#clickId'); var doIt = function(){}; // 删除某一员工(工具栏按钮) $scope.removeIt = function(){ mask.insertBefore(container); $("#msgP").html("你确定要执行该操作吗?"); container.removeClass('none'); doIt = function(){ if($rootScope.ids.length !== 0){ var url = app.url.employee.api.delete; app.utils.getData(url, {"ids":$rootScope.ids}, function callback(dt){ mask.remove(); container.addClass('none'); $state.reload('app.employee.list'); }); } }; }; // 执行操作 $rootScope.do = function(){ doIt(); }; // 模态框退出 $rootScope.cancel = function(){ mask.remove(); container.addClass('none'); }; // 不操作返回 $scope.return = function(){ $rootScope.ids = []; setStatus(status); window.history.back(); }; // 查看某一职员详情(工具栏按钮) $scope.seeDetails = function(id){ sessionStorage.setItem("id",id? id:$rootScope.ids[0]); setStatus(status_false); $state.go('app.employee.details'); }; // 设置按钮的状态值 $scope.setBtnStatus = function(){ if($scope.ids.length === 0){ $scope.single = true; $scope.mutiple = true; $scope.only = false; }else if($scope.ids.length === 1){ $scope.only = false; $scope.single = false; $scope.mutiple = false; }else{ $scope.only = false; $scope.single = true; $scope.mutiple = false; } hButton.trigger('click'); // 触发一次点击事件,使所以按钮的状态值生效 }; function setStatus(param){ if(param){ $scope.only = param.only, $scope.single = param.single, $scope.mutiple = param.mutiple } //hButton.trigger('click'); } }]);
export default { "resourceType": "Questionnaire", "id": "f201", "url": "http://hl7.org/fhir/Questionnaire/f201", "status": "active", "subjectType": [ "Patient" ], "date": "2010", "item": [ { "linkId": "1", "text": "Do you have allergies?", "type": "boolean" }, { "linkId": "2", "text": "General questions", "type": "group", "item": [ { "linkId": "2.1", "text": "What is your gender?", "type": "string" }, { "linkId": "2.2", "text": "What is your date of birth?", "type": "date" }, { "linkId": "2.3", "text": "What is your country of birth?", "type": "string" }, { "linkId": "2.4", "text": "What is your marital status?", "type": "string" } ] }, { "linkId": "3", "text": "Intoxications", "type": "group", "item": [ { "linkId": "3.1", "text": "Do you smoke?", "type": "boolean" }, { "linkId": "3.2", "text": "Do you drink alchohol?", "type": "boolean" } ] } ] }
const params = new URLSearchParams(location.search); if (params.get('error')) { const errBox = document.getElementById('account-error'); errBox.textContent = params.get('error'); errBox.style.display = 'block'; }
import React, { Component } from "react"; import "../../styles/number_input.css"; class NumberInput extends Component { render() { return ( <div> <label className="option-label">{this.props.title}: </label> <input type="number" className="number-input" path={this.props.path} value={this.props.value} onChange={e => this.props.onChange(e)} min={this.props.min} max={this.props.max} interval={this.props.interval} /> </div> ); } } export default NumberInput;
function solve(word) { function isPalindrome(word) { for(let i = 0; i < word.length; i++){ if(word[i] !== word[word.length -1 - i]){ return false; } } return true; } if(isPalindrome(word)){ console.log('true'); } else { console.log('false'); } } solve('haha'); solve('racecar'); solve('unitinu');
const Sequelize = require('sequelize'); const databaseManager = require('../user_modules/database-manager'); const attributeStringMap = require('./maps/attribute-string.map'); const AttributeStringValue = require('./attribute-string-value.model'); module.exports = {}; const AttributeString = databaseManager.context.define('attributeString', { Id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true }, Name: { unique: true, allowNull: false, type: Sequelize.STRING }, Description: { allowNull: false, type: Sequelize.STRING }, Question: { allowNull: false, type: Sequelize.STRING }, ForType: { allowNull: false, type: Sequelize.ENUM("STUDENT", "HOST", "BOTH") }, MaxLength: { allowNull: true, type: Sequelize.INTEGER }, Required: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true } },{ instanceMethods: { getMap: function() { return AttributeString.getMap(); } }, }); AttributeString.Values = AttributeString.hasMany(AttributeStringValue, { foreignKey: { name: 'AttributeId', allowNull: false }, as: 'Values' }); /** * Figures out how to serialize and deserialize this model * @returns {Object} */ AttributeString.getMap = function () { return attributeStringMap; }; module.exports = AttributeString;
"use strict"; //어..음...이미지 추가 버튼 // function imgInsert() { // console.log(`text`); // const browseBtn = document.querySelector('.btn-input-img'); // const realInput = document.getElementById(`file-input-img`); // browseBtn.addEventListener('click', () => { // console.log("22323"); // realInput.click(); // }); // } // imgInsert(); // 미리보기 수정 샥제 // function handleFileSelect(event) { // let input = this; // console.log(input.files) // if (input.files && input.files.length) { // let reader = new FileReader(); // this.enabled = false // for(let i = 0; i < input.files.length; i++) { // reader.onload = (function (e) { // console.log(`test22`); // console.log(e) // $("#imgPreview").html(['<img class="thumb" src="', e.target.result, '" title="', escape(e.name), '"/>'].join('')) // }); // reader.readAsDataURL(input.files[0]); // } // } // } // $('.file-input-img').change(handleFileSelect); // $('.file-edit-icon').on('click', '.preview-de', function () { // $("#preview").empty() // $("#file").val(""); // }); // $('.preview-edit').click( function() { // $("#file").click(); // } ); let download_url_lis = []; function readInputFile(e) { let sel_files = []; sel_files = []; $('#imgPreview').empty(); let files = e.target.files; let fileArr = Array.prototype.slice.call(files); let index = 0; let i = 0 //todo : 프로그래스바 시작 fileArr.forEach(function (f) { console.log(`2`); if (!f.type.match("image/.*")) { alert("이미지 확장자만 업로드 가능합니다."); return; }; if (files.length < 11) { console.log(`3`); console.log("테스트" + files[0]); sel_files.push(f); //스토리지에 업로드 let storage = firebase.storage(); //let file=document.getElementById("file-input-img").files[0]; let files_yang = document.getElementById("file-input-img").files; let delivery_uid = document.getElementById('delivery_uid').value let user_uid = document.getElementById('user_uid').value let filename = delivery_uid + user_uid console.log("files:" + files); let storageRef = storage.ref(); filename = filename + "??" + String(i) let thisref = storageRef.child(filename).put(files[i]); i++ thisref.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed' function (snapshot) { let start = new Date().getTime(); // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log('Upload is ' + progress + '% done'); if(progress !== 100) { let loading = ` <div class="loading-img"> <i class="fas fa-spinner fa-pulse fa-5x"></i> </div> `; $('#imgPreview').append(loading); } else { const delLoading = document.querySelector(`.loading-img`); delLoading.parentNode.removeChild(delLoading); let reader = new FileReader(); reader.onload = function (e) { let html = `<li id=img_id_${index}> <img src=${e.target.result} data-file=${f.name} /> <span onclick="previewDelete(${index})">삭제</span> </li>`; $('#imgPreview').append(html); index++; }; reader.readAsDataURL(f); } switch (snapshot.state) { case firebase.storage.TaskState.PAUSED: // or 'paused' console.log('Upload is paused'); break; case firebase.storage.TaskState.RUNNING: // or 'running' console.log('Upload is running'); break; } }, function (error) { // A full list of error codes is available at // https://firebase.google.com/docs/storage/web/handle-errors switch (error.code) { case 'storage/unauthorized': // User doesn't have permission to access the object break; case 'storage/canceled': // User canceled the upload break; case 'storage/unknown': // Unknown error occurred, inspect error.serverResponse break; } }, function () { // Upload completed successfully, now we can get the download URL thisref.snapshot.ref.getDownloadURL().then(function (downloadURL) { console.log('File available at', downloadURL); //document.getElementById('downloadURL[]').value+=downloadURL // let downloadURL_reviewindex=document.getElementById('downloadURL') // downloadURL_reviewindex.innerHTML +=` // <input type="hidden" id="downloadURL${i}" name="downloadURL[] value="${downloadURL}"> // `; download_url_lis.push(downloadURL); }); }); //thisref.on 끝 } //if문 끝 }) //for each문 끝 //todo : 프로그래스바 끝 if (files.length > 11) { alert("최대 10장까지 업로드 할 수 있습니다."); }; } $('#file-input-img').on('change', readInputFile); function previewDelete(e) { const li = document.getElementById(`img_id_${e}`); li.remove(); $("#file-input-img").val(""); }
/* eslint-disable prefer-promise-reject-errors,no-console,prefer-promise-reject-errors,prefer-promise-reject-errors,no-warning-comments */ const Base = require('./base'); const {PasswordHash} = require('phpass'); let fields = [ 'id', 'user_login as login', // 'user_pass as pass', 'user_nicename as nicename', 'user_email as email', // 'user_url as url', 'user_status as status' ] module.exports = class extends Base { get relation () { return { metas: { type: think.Model.HAS_MANY, model: 'usermeta', // rModel: 'usermeta', fKey: 'user_id' } }; } /** * get password * @param {String} username [] * @param {String} salt [] * @return {String} [] */ getEncryptPassword (password) { const passwordHash = new PasswordHash(); const hash = passwordHash.hashPassword(password); return hash; } /** * check password * @param {[type]} userInfo [description] * @param {[type]} password [description] * @return {[type]} [description] */ checkPassword (userInfo, password) { const passwordHash = new PasswordHash(); return passwordHash.checkPassword(password, userInfo.user_pass); } // checkUserRole(userInfo) { // // } generateKey (userId, appKey, appSecret, status) { const data = {appKey, appSecret}; if (status) { data.status = status; } this.where({id: userId}).update(data); } /** * 查询微信注册来的用户 * @param openId * @returns {Promise.<*>} */ async getByWxApp (openId) { let user = await this.where({user_login: openId}).find() return user } /** * 根据 id 查找用户 * @param user_id * @returns {Promise.<void>} */ async getById(user_id) { const user = await this.field(fields).where({ id: user_id }).find() const meta = await this.model('usermeta').where({user_id: user_id}).select() user.metas = meta return user } /* { openId: 'oQgDx0IVqAg0b3GibFYBdtg3BKMA', nickName: '请好好说话🌱', gender: 1, language: 'en', city: 'Chaoyang', province: 'Beijing', country: 'China', avatarUrl: 'https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83ep0GdQEHK3tYdvq3DTMVhsdiaviaLg6b7CdDBLOYSWDGYOEtS7FFmvhd6CGCuQVfe4Rb0uQUlaq7XoA/0', watermark: { timestamp: 1508809460, appid: 'wxca1f2b8b273d909e' }, appId: 'S11SeYT2W' } */ async updateWechatUser (data) { // const createTime = new Date().getTime(); try { // 用户信息 await this.thenUpdate({user_nicename: data.nickName}, {user_login: data.openId}) // Meta 数据 const usermeta = this.model('usermeta') await usermeta.thenUpdate({ user_id: `${data.userId}`, meta_key: `picker_${data.appId}_wechat`, meta_value: JSON.stringify(data) }, { user_id: `${data.userId}`, meta_key: `picker_${data.appId}_wechat` }) } catch(e) { console.log(e) throw e } } /** * 添加从微信过来的用户 * * @param data * @returns {Promise.<*>} */ async saveWechatUser (data) { const createTime = new Date().getTime(); const res = await this.where({ user_login: data.openId }).thenAdd({ user_login: data.openId, // user_nicename: data.nickName, user_registered: createTime, user_status: 1 }); // Add user meta info if (!think.isEmpty(res)) { if (res.type === 'add') { // const role = think.isEmpty(data.role) ? 'subscriber' : data.role const usermeta = this.model('usermeta') await usermeta.add({ user_id: res.id, meta_key: data.appId ? `picker_${data.appId}_capabilities` : '_capabilities', meta_value: JSON.stringify({'role': 'subscriber', 'type': 'wechat'}) }, {appId: data.appId}) await usermeta.add({ user_id: res.id, // 用于标识用户类型 meta_key: `picker_${data.appId}_wechat`, meta_value: JSON.stringify(data) }) } // TODO: basi 2017.10.19 这里会有更新操作,如果同一用户授权我们服务的其它应用,就要更新关联的应用 } return res } async save (data) { if (think.isEmpty(data.id)) { // Add const createTime = new Date().getTime(); const encryptPassword = this.getEncryptPassword(data.user_pass); const res = await this.where({ user_login: data.user_login, // user_phone: data.user_phone, user_email: data.user_email, _logic: 'OR' }).thenAdd({ user_login: data.user_login, user_email: data.user_email, user_phone: data.user_phone, user_nicename: data.user_nicename, user_pass: encryptPassword, user_registered: createTime, user_status: 1 }); if (!think.isEmpty(res)) { if (res.type === 'add') { const role = think.isEmpty(data.role) ? 'subscriber' : data.role const usermeta = this.model('usermeta') await usermeta.add({ user_id: res.id, meta_key: data.appId ? `picker_${data.appId}_capabilities` : '_capabilities', meta_value: JSON.stringify({'role': role, 'type': 'team'}) }, {appId: data.appId}) // 后续这里的用户简介可以处理与 resume 模型关联 if (!think.isEmpty(data.summary)) { await usermeta.save(res.id, { 'resume': JSON.stringify({"summary": data.summary}) }) } if (!think.isEmpty(data.avatar)) { await usermeta.save(res.id, { 'avatar': data.avatar }) } } } } else { // Update const info = await this.where({id: data.id}).find(); if (think.isEmpty(info)) { return Promise.reject(new Error('UESR_NOT_EXIST')); } let password = data.user_pass; if (password) { password = this.getEncryptPassword(password); } let updateData = {}; // ['display_name', 'type', 'status'].forEach(item => { // if (data[item]) { // updateData[item] = data[item]; // } // }); updateData = data if (password) { updateData.user_pass = password; } // eslint-disable-next-line prefer-promise-reject-errors if (think.isEmpty(updateData)) { return Promise.reject('DATA_EMPTY'); } if (!info.email && data.email) { const count = await this.where({email: data.email}).count('email'); if (!count) { updateData.email = data.email; } } updateData.last_login_time = new Date().getTime(); // updateData.last_login_ip = ip; const res = await this.where({id: data.id}).update(updateData); if (!think.isEmpty(res)) { const role = think.isEmpty(data.role) ? 'subscriber' : data.role const usermeta = this.model('usermeta') await usermeta.add({ user_id: res.id, meta_key: data.appId ? `picker_${data.appId}_capabilities` : '_capabilities', meta_value: JSON.stringify({'role': role, 'type': 'team'}) }, {appId: data.appId}) // 后续这里的用户简介可以处理与 resume 模型关联 if (!think.isEmpty(data.summary)) { await usermeta.save(res.id, { 'resume': JSON.stringify({"summary": data.summary}) }) } if (!think.isEmpty(data.avatar)) { await usermeta.save(res.id, { 'avatar': data.avatar }) } } } } /** * 添加用户 * @param {[type]} data [description] * @param {[type]} ip [description] */ async addUser (data) { const createTime = new Date().getTime(); const encryptPassword = this.getEncryptPassword(data.user_pass); const res = await this.where({ user_login: data.user_login, // user_phone: data.user_phone, user_email: data.user_email, _logic: 'OR' }).thenAdd({ user_login: data.user_login, user_email: data.user_email, user_phone: data.user_phone, user_nicename: data.user_nicename, user_pass: encryptPassword, user_registered: createTime, user_status: 1 }); // Add user meta info if (!think.isEmpty(res)) { if (res.type === 'add') { const role = think.isEmpty(data.role) ? 'subscriber' : data.role const usermeta = this.model('usermeta') await usermeta.add({ user_id: res.id, meta_key: data.appid ? `picker_${data.appid}_capabilities` : '_capabilities', meta_value: JSON.stringify({'role': role, 'type': 'team'}) }, {appId: this.appId}) // 后续这里的用户简介可以处理与 resume 模型关联 if (!think.isEmpty(data.summary)) { await usermeta.save(res.id, { 'resume': JSON.stringify({"summary": data.summary}) }) } if (!think.isEmpty(data.avatar)) { await usermeta.save(res.id, { 'avatar': data.avatar }) } } } return res } async addOrgUser (data) { const createTime = new Date().getTime(); const encryptPassword = this.getEncryptPassword(data.user_pass); const res = await this.where({ user_login: data.user_login, // user_phone: data.user_phone, user_email: data.user_email, _logic: 'OR' }).thenAdd({ user_login: data.user_login, user_email: data.user_email, user_phone: data.user_phone, user_nicename: data.user_nicename, user_pass: encryptPassword, user_registered: createTime, user_status: 1 }); // Add user meta info if (!think.isEmpty(res)) { if (res.type === 'add') { const role = think.isEmpty(data.role) ? 'subscriber' : data.role const usermeta = this.model('usermeta') await usermeta.add({ user_id: res.id, meta_key: `org_${data.org_id}_capabilities`, meta_value: JSON.stringify({'role': role, 'type': 'org'}) }, {appId: this.appId}) // 后续这里的用户简介可以处理与 resume 模型关联 if (!think.isEmpty(data.summary)) { await usermeta.save(res.id, { 'resume': JSON.stringify({"summary": data.summary}) }) } if (!think.isEmpty(data.avatar)) { await usermeta.save(res.id, { 'avatar': data.avatar }) } } } return res } /** * 保存用户信息 * @param {[type]} data [description] * @return {[type]} [description] */ async saveUser (data, ip) { const info = await this.where({id: data.id}).find(); if (think.isEmpty(info)) { return Promise.reject(new Error('UESR_NOT_EXIST')); } let password = data.password; if (password) { password = this.getEncryptPassword(password); } const updateData = {}; ['display_name', 'type', 'status'].forEach(item => { if (data[item]) { updateData[item] = data[item]; } }); if (password) { updateData.password = password; } // eslint-disable-next-line prefer-promise-reject-errors if (think.isEmpty(updateData)) { return Promise.reject('DATA_EMPTY'); } if (!info.email && data.email) { const count = await this.where({email: data.email}).count('email'); if (!count) { updateData.email = data.email; } } updateData.last_login_time = think.datetime(); updateData.last_login_ip = ip; return this.where({id: data.id}).update(updateData); } /** * 根据用户ID获取用户显示名字 * @param integer $uid 用户ID * @return string 用户昵称 */ async displayName (uid) { uid = uid || 0; // eslint-disable-next-line no-warning-comments // TODO 缓存处理后续 let name = ''; const info = await this.field('display_name').find(uid); name = info.display_name; return name; } // async getUserMeta(key) async getLikedPost (appid, post_id) { const userMeta = this.model('usermeta') const data = await userMeta.where(`meta_value ->'$.post_id' = '${post_id}' and meta_key = 'picker_${appid}_liked_posts'`).select() } async likedPost (appid, post_id) { const userMeta = this.model('usermeta') const data = await userMeta.where(`meta_value ->'$.post_id' = '${post_id}' and meta_key = 'picker_${appid}_liked_posts'`).select() } /** * 添加新喜欢的人员 * @param user_id * @param post_id * @returns {Promise.<void>} */ async newLike (user_id, app_id, post_id) { const userMeta = this.model('usermeta') const result = await userMeta.where({ user_id: user_id, meta_key: `picker_${app_id}_liked_posts` }).find() let likeCount = 0 if (!think.isEmpty(result)) { if (!think.isEmpty(result.meta_value)) { likeCount = JSON.parse(result.meta_value).length const iLike = await think._.find(JSON.parse(result.meta_value), ['post_id', post_id]) if (!iLike) { await userMeta.where({ user_id: user_id, meta_key: `picker_${app_id}_liked_posts` }).update({ 'user_id': user_id, 'meta_key': `picker_${app_id}_liked_posts`, 'meta_value': ['exp', `JSON_ARRAY_APPEND(meta_value, '$', JSON_OBJECT('post_id', '${post_id}','date', '${new Date().getTime()}'))`] }) likeCount++ } } } else { // 添加 const res = await userMeta.add({ user_id: user_id, meta_key: `picker_${app_id}_liked_posts`, meta_value: ['exp', `JSON_ARRAY(JSON_OBJECT('post_id', '${post_id}', 'date', '${new Date().getTime()}'))`] }) if (res > 0) { likeCount++ } } } /** * UnLike post * @param user_id * @param post_id * @returns {Promise<number>} */ async unLike (user_id, app_id, post_id) { console.log(user_id + ':' + app_id + ':' + post_id) // const res = await this.where(`user_id = '${user_id}' AND meta_key = 'picker_${app_id}_liked_posts' AND JSON_SEARCH(meta_value, 'one', ${post_id}) IS NOT NULL`).update({ // 'meta_value': ['exp', `JSON_REMOVE(meta_value, SUBSTRING_INDEX(REPLACE(JSON_SEARCH(meta_value, 'one', '${post_id}', NULL, '$**.post_id'), '"', ''), '.', 1))`] // } // ) // return res } }
import React, { Component } from 'react'; import { Text, View, ScrollView, TouchableOpacity, Linking, Alert } from 'react-native'; import { Avatar, Rating, Divider } from 'react-native-elements'; import PhoneCall from 'react-native-phone-call'; import { Popup } from 'react-native-map-link'; import colors from '../../constants/Colors'; import styles from '../../styles/customer/Style_AboutPage'; import ViewMoreText from 'react-native-view-more-text'; import { Collapse, CollapseHeader, CollapseBody } from 'accordion-collapse-react-native'; import MapView from 'react-native-maps'; import { AntDesign, FontAwesome, MaterialCommunityIcons } from '@expo/vector-icons'; import database from '../../database'; import { clockRunning } from 'react-native-reanimated'; class AboutPage extends Component { constructor(props) { super(props); this.state = { isPopupVisble: false, }; this.renderViewMore = this.renderViewMore.bind(this); this.renderViewLess = this.renderViewLess.bind(this); } renderViewMore(onPress) { return ( <Text onPress={onPress} style={{ color: colors.blue, opacity: 0.9, fontSize: 12 }}> View more </Text> ) } renderViewLess(onPress) { return ( <Text onPress={onPress} style={{ color: colors.blue, opacity: 0.9, fontSize: 12 }}> View less </Text> ) } prettyAvailability(availability) { var prettyAvailability = ['Closed', 'Closed', 'Closed', 'Closed', 'Closed', 'Closed', 'Closed']; availability.map(item => { switch(item.dow) { case 'Sunday': prettyAvailability[0] = `${item.starttime.substring(0, 5)} - ${item.endtime.substring(0, 5)}`; break; case "Monday": prettyAvailability[1] = `${item.starttime.substring(0, 5)} - ${item.endtime.substring(0, 5)}`; break; case 'Tuesday': prettyAvailability[2] = `${item.starttime.substring(0, 5)} - ${item.endtime.substring(0, 5)}`; break; case 'Wednesday': prettyAvailability[3] = `${item.starttime.substring(0, 5)} - ${item.endtime.substring(0, 5)}`; break; case 'Thursday': prettyAvailability[4] = `${item.starttime.substring(0, 5)} - ${item.endtime.substring(0, 5)}`; break; case 'Friday': prettyAvailability[5] = `${item.starttime.substring(0, 5)} - ${item.endtime.substring(0, 5)}`; break; case 'Saturday': prettyAvailability[6] = `${item.starttime.substring(0, 5)} - ${item.endtime.substring(0, 5)}`; break; } }); return prettyAvailability; } renderOpeningHours() { const businessData = this.props.businessData.businessDetails; const prettyAvailability = this.prettyAvailability(businessData.availability); return ( <View> <Collapse isCollapsed={this.state.isCollapsed} onToggle={isCollapsed => this.setState({ isCollapsed })} > <CollapseHeader style={[styles.rowItems, styles.leftAlign, styles.infoRowsContainer]}> <View style={styles.iconsCircle}> <FontAwesome name="clock-o" size={24} color={colors.blue} style={{ marginLeft: 1 }} /> </View> <Text style={styles.iconsText}>Open - Closes</Text> <View style={{ paddingLeft: 10 }}> {this.state.isCollapsed === true ? ( <FontAwesome name="chevron-up" size={16} color={'grey'} /> ) : ( <FontAwesome name="chevron-down" size={16} color={'grey'} /> )} </View> </CollapseHeader> <CollapseBody style={{ marginBottom: 5, marginTop: -8 }}> <View style={[styles.rowItems, styles.hoursTextContainer]}> <Text style={styles.daysText}>Sunday</Text> <Text style={styles.hoursText}>{prettyAvailability[0]}</Text> </View> <View style={[styles.rowItems, styles.hoursTextContainer]}> <Text style={styles.daysText}>Monday</Text> <Text style={styles.hoursText}>{prettyAvailability[1]}</Text> </View> <View style={[styles.rowItems, styles.hoursTextContainer]}> <Text style={styles.daysText}>Tuesday</Text> <Text style={styles.hoursText}>{prettyAvailability[2]}</Text> </View> <View style={[styles.rowItems, styles.hoursTextContainer]}> <Text style={styles.daysText}>Wednesday</Text> <Text style={styles.hoursText}>{prettyAvailability[3]}</Text> </View> <View style={[styles.rowItems, styles.hoursTextContainer]}> <Text style={styles.daysText}>Thursday</Text> <Text style={styles.hoursText}>{prettyAvailability[4]}</Text> </View> <View style={[styles.rowItems, styles.hoursTextContainer]}> <Text style={styles.daysText}>Friday</Text> <Text style={styles.hoursText}>{prettyAvailability[5]}</Text> </View> <View style={[styles.rowItems, styles.hoursTextContainer]}> <Text style={styles.daysText}>Saturday</Text> <Text style={styles.hoursText}>{prettyAvailability[6]}</Text> </View> </CollapseBody> </Collapse> </View> ) } render() { const businessData = this.props.businessData.businessDetails; return ( <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}> <View> <Text style={styles.heading}>{businessData.business.name}</Text> {/* <Text style={styles.category}>{businessData.business.category}</Text> */} <View style={{ flexDirection: 'row' }}> <Rating style={styles.rating} imageSize={22} readonly={true} startingValue={businessData.business.rating === null ? 0 : Number(businessData.business.rating)} ratingColor={'#FED56B'} type={'custom'} /> <Text style={{ color: 'grey', fontSize: 12, marginLeft: 4, marginTop: 3 }}>({businessData.business.ratingcount})</Text> </View> <View style={[{ flexDirection: 'row' }, styles.managerWordContainer]}> <Avatar containerStyle={styles.managerAvatar} rounded size={50} source={{ uri: businessData.business.avatar }} /> <View style={styles.managerTextContainer}> <ViewMoreText numberOfLines={3} renderViewMore={this.renderViewMore} renderViewLess={this.renderViewLess} > <Text adjustsFontSizeToFit style={styles.managerText}> {businessData.business.description} </Text> </ViewMoreText> </View> </View> <View style={styles.dividerContainer}> <Divider style={styles.divider} /> </View> <TouchableOpacity style={[styles.rowItems, styles.leftAlign, styles.infoRowsContainer]} onPress={() => { const args = { number: businessData.business.phone, prompt: false } PhoneCall(args).catch(console.error) }} > <View style={styles.iconsCircle}> <FontAwesome name="phone" size={24} color={colors.blue} style={{ marginLeft: 1 }} /> </View> <Text style={styles.iconsText}>Call</Text> </TouchableOpacity> <TouchableOpacity style={[styles.rowItems, styles.leftAlign, styles.infoRowsContainer]} onPress={() => { Linking.openURL(businessData.business.website) }} > <View style={styles.iconsCircle}> <FontAwesome name="globe" size={24} color={colors.blue} style={{ marginLeft: 2 }} /> </View> <Text style={styles.iconsText}>Website</Text> </TouchableOpacity> {this.renderOpeningHours()} {/* <View style={[styles.rowItems, styles.leftAlign, styles.infoRowsContainer]}> <View style={styles.iconsCircle}> <FontAwesome name="tags" size={23} color={colors.blue} style={{ marginLeft: 3 }} /> </View> <Text style={styles.iconsText}> { businessData.tags[0].tag + ', ' + businessData.tags[1].tag + ', ' + businessData.tags[2].tag} </Text> </View> */} <TouchableOpacity style={[styles.rowItems, styles.leftAlign, styles.infoRowsContainer]} onPress={() => this.setState({ isPopupVisble: true })} > <View style={styles.iconsCircle}> <FontAwesome name="map-marker" size={24} color={colors.blue} style={{ marginLeft: 1 }} /> </View> <Text style={styles.iconsText}>{businessData.business.street}, {businessData.business.city}.</Text> </TouchableOpacity> <Popup isVisible={this.state.isPopupVisble} onCancelPressed={() => this.setState({ isPopupVisble: false })} onAppPressed={() => this.setState({ isPopupVisble: false })} onBackButtonPressed={() => this.setState({ isPopupVisble: false })} modalProps={{ animationIn: 'slideInUp' }} appsWhiteList={[]} options={{ alwaysIncludeGoogle: true, latitude: businessData.business.coordinates.x, longitude: businessData.business.coordinates.y, title: this.props.businessData.Name, dialogTitle: `${businessData.business.street}, ${businessData.business.city}`, cancelText: 'Cancel' }} /> <View style={styles.mapContainer}> <MapView style={styles.map} region={{ latitude: businessData.business.coordinates.x, latitudeDelta: 0.002, longitude: businessData.business.coordinates.y, longitudeDelta: 0.002 }} provider={'google'} zoomTapEnabled={false} > <MapView.Marker coordinate={{ latitude: businessData.business.coordinates.x, longitude: businessData.business.coordinates.y, }} /> </MapView> </View> </View> </ScrollView> ); } } export default AboutPage;
// definisco la variabile che conterrà gli elementi // creo il ciclo contenente i box numerati // inserisco le condizioni legate ai multipli const contenitore = document.querySelector(".row"); for (let i = 1; i <= 100; i++) { const box = document.createElement("div"); box.className = "box"; box.innerHTML = i; contenitore.append(box); // condizioni if (!(i % 3) && !(i % 5)) { box.classList.add("comuni"); } else if (!(i % 3)) { box.classList.add("per-3"); } else if (!(i % 5)) { box.classList.add("per-5"); } }
$(function() { $(document).ready(function(){ $('body').on('click', '.show-reply', function(){ var par_id = $(this).attr('id'), token = $('#token').val(), cur = $('#cur').val(); $('#' + par_id + '').prop('disabled', true); $.ajax({ type: 'POST', url: '/writer/web/ajax/comments', data: ({parent : par_id, token : token, cur : cur}), dataType: "json", success: function(comments, status) { $.each(comments, function(i, html) { $('#' + par_id + '').parent().append(comments[i].html); }) $('#' + par_id + '').remove(); }, error : function(result, status, error){ $('#' + par_id + '').prop('disabled', false); } }); }); $('body').on('click', '.comment-signal', function(){ var cId = $(this).data('id'), token = $('#token').val(), cur = $('#cur').val(), $but = $('#signal-' + cId + ''); $but.prop('disabled', true); $.ajax({ type: 'POST', url: '/writer/web/ajax/signal', data: ({signal : cId, token : token, cur : cur}), dataType: "json", success: function(message, status) { $('#comment-' + cId +'').append('<div class="alert alert-info flag-message">' + message + '</div>').delay(4000).queue( function(){ $('.flag-message').fadeOut( 2000 ); }); $but.replaceWith('<span class="signal-off"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i></span>'); }, error : function(message, status, error){ $but.prop('disabled', false); } }); }); $('body').on('click', '.comment-reply', function(e){ e.preventDefault(); var $form = $('#form-comment'), $this = $(this), parent_id = $this.data('id'), $comment = $('#comment-' + parent_id); $form.find('h4').text('Répondre à un commentaire'); $('#respond_to_id').val(parent_id); $this.after($form); }); }); });
var socket = io(); socket.on('connect', function () { console.log('Connected to the server !'); }); socket.on('disconnect', function () { //console.log('Disconnected from to the server !'); }); socket.on('newMessage', function (Data) { var formatedTime = moment(Data.createdAt); var template = $('#message-template').html(); var html = Mustache.render(template, { text: Data.content, from: Data.from, createdAt: formatedTime.format('h:mm a') }); $('#message').append(html); }); socket.on('login', function(data) { console.log("Admin message", data); }); socket.on('userJoined', function(data) { console.log("Admin message", data); }); socket.on('newLocationMessage', function(data) { var formatedTime = moment(data.createdAt); var template = $('#location-message-template').html(); var html = Mustache.render(template, { text: data.content, url: data.from, createdAt: formatedTime.format('h:mm a') }); $html.appendTo($('#message')); }); $('#message-form').on('submit', function(e) { e.preventDefault(); var messageTextBox = $("form input[name=message"); socket.emit('createMessage', { from: 'User', body: messageTextBox.val() }, function() { messageTextBox.val(''); }); }); var locationButton = $('#send-location'); locationButton.on('click', function(){ if(!navigator.geolocation){ return alert('Geolocation not supported by your browser.'); } locationButton.attr('disabled','disabled').text('Sending location...'); navigator.geolocation.getCurrentPosition(function(position){ socket.emit('createLocationMessage', { longitude: position.coords.longitude, latitude: position.coords.latitude }); locationButton.removeAttr('disabled').text('Send location'); },function(){ alert('Unable to fetch location'); locationButton.removeAttr('disabled').text('Send location'); }); });
import React from 'react'; import PropTypes from 'prop-types'; //darkMode -> colorMode const Module = props => ( <div className={`box ${props.colorMode}`}> <h1 className="title">{props.title}</h1> <p>{props.content}</p> <div> {props.menu.map(i => <a href={i} key={i}>{i}</a>)} </div> </div> ); Module.defaultProps = { menu: [] } Module.propTypes = { title: PropTypes.string.isRequired, //menu: PropTypes.arrayOf(PropTypes.string).isRequired } // PropsDemo -> Module // This Class component also can have props export class PropsDemo extends React.Component { render() { return <div> <h1 className="subtitle"> {this.props.header} </h1> <Module title="Dark" content="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." menu={['home', 'catalog', 'search']} /> <Module colorMode="dark-mode" title="Dark" content="Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." /> <Module colorMode="high-contrast" title="Dark" content="Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur."/> </div>; } }
import fs from 'fs' import express from 'express' import Schema from './data/schema' import GraphQLHTTP from 'express-graphql' import { MongoClient } from 'mongodb' import { graphql } from 'graphql' import { introspectionQuery } from 'graphql/utilities' const app = express() app.use(express.static('public')) console.log(process.env.MONGO_URL) ;(async () => { const db = await MongoClient.connect(process.env.MONGO_URL) const schema = Schema(db) app.use( '/graphql', GraphQLHTTP({ schema, graphiql: true, }) ) app.listen(3000, () => console.log('listening on port 3000')) // Generate schema.json const json = await graphql(schema, introspectionQuery) fs.writeFile( './data/schema.json', JSON.stringify(json, null, 2), err => { if (err) throw err console.log('JSON schema created') } ) })()
import React, { Component } from 'react'; import { View, ScrollView, Text, Dimensions } from 'react-native'; import { Card, CardSection, Button } from './common'; import { noteToObjet, gammeToObjet } from './GammesList'; import { renderPositions } from './PositionsList'; import PositionsList from './PositionsList'; import styles from './Accueil'; const { width } = Dimensions.get('window'); class PositionView extends Component { render() { const { noteparent, typeAccord} = this.props; console.log('coucou1', noteparent, typeAccord); const note = noteToObjet(noteparent); console.log('coucou2', note, typeAccord); //Ici on fera return renderMancheGuitare(gamme, note); /*return render_view(note, gamme);*/ return ( <View style={{ width, flex: 1, flexDirection: 'column', justifyContent: 'flex-start', //alignItems: 'center' }} > <Text style={{ paddingTop: 10, fontSize: width / 12, fontWeight: 'bold', textAlign: 'center', color: '#CCCCCC' }} > ❸ </Text> <Card> <CardSection style={styles.gammesListLabelContainerStyle}> <Text style={{ fontSize: 16, fontWeight: 'bold', textAlign: 'center', //paddingLeft: 20, alignSelf: 'stretch', color: '#007aff' }}> {"Gammes existantes pour la note et l'accord selectionnés"} </Text> </CardSection> <ScrollView> <GammesList note={this.props.note} accordType={this.props.typeAccord}/> </ScrollView> <View style={{ justifyContent: 'center', flexDirection: 'row', paddingLeft: 3, paddingRight: 3 }}> <Text style={{ color: '#CCCCCC', fontWeight: 'bold', textAlign: 'center', paddingTop: 5, paddingBottom: 5 }} > Cliquez sur une gamme pour afficher ses positions </Text> </View> </Card> </View> ); } } const mapStateToProps = (state) => { console.log(state); return { typeAccordparent: typeAccordToObjet(state.accords.typeAccord), noteparent: noteToObjet(state.accords.note) }; }; export default GammeView;
import api from '../api'; import config from '../config'; // TODO: ChatStore? as a child store to the main one? export default class ChatClient { constructor(socket, data) { this.socket = socket; this.isConnected = true; this.rooms = data.rooms; // TODO: move this to store somehow :/ ? // this.users = [] ? socket.on('messages', payload => this._onMessageReceived(payload)); socket.on('rooms', payload => this._onRoomMessageReceived(payload)); } sendMessage(payload) { if(!this._ensureIsConnected()) { return; } this.socket.emit('messages', { action: 'create', room: payload.room, sender: payload.sender, message: payload.message }); } createRoom(roomName) { if(!this._ensureIsConnected()) { return; } this.socket.emit('rooms', { action: 'create', room: { name: roomName } }); } disconnect() { if(!this.isConnected) { console.log("Disconnecting even though already disconnected"); } // todo: calling this ensures that one user can't be connected to server // on multiple web sockets. however, this might not always be called (?) // so the check should definitely be done server-side too this.socket.disconnect(); } isConnected() { return this.isConnected; } _ensureIsConnected() { if(!this.isConnected) { console.error("Trying to use ChatClient but client is not connected"); return false; } return true; } _onMessageReceived(payload) { if(payload.action !== 'create') { return; } const room = this.rooms.find(room => room.name === payload.room); if(!room) { console.error("Message received, but room was not found", payload.room, payload.message); return; } room.messages.push({ text: payload.message, sender: payload.sender, timestamp: payload.timestamp }); } _onRoomMessageReceived(payload) { if(payload.action === 'create') { this.rooms.push(payload.room); } // else if(payload.action === 'delete') // todo? } static async openConnection() { const result = await api.openConnection(); if(result.success) { const socket = io.connect(config.SERVER_URL); const client = new ChatClient(socket, { rooms: result.payload.rooms }); const waitForConnect = () => { return new Promise((resolve, reject) => { socket.on('connect_error', err => reject(err)); socket.on("connect", () => { resolve({ success: true, payload: { chatClient: client, user: result.payload.user }}); }); }); }; try { return await waitForConnect(); } catch(err) { /* return fail below */ } } // todo: figure out precise reason why fail? return { success: false, error: { type: "auth", message: "Could not open connection" } }; } };
import style from './style.module.css' const AboutPage = () => { return ( <h1> This is About Page </h1> ) } export default AboutPage;
const assert = require('assert'); const sinon = require('sinon'); const { stream } = require('logtify')({}); const serializeError = require('serialize-error'); const Kafka = require('../src/index.js'); const { Message } = stream; describe('Kafka plugin', () => { before(() => { delete process.env.KAFKA_HOST; delete process.env.KAFKA_TOPIC; }); afterEach(() => { delete process.env.KAFKA_HOST; delete process.env.KAFKA_TOPIC; delete process.env.KAFKA_LOGGING; delete process.env.MIN_LOG_LEVEL; delete process.env.MIN_LOG_LEVEL_KAFKA; delete process.env.KAFKA_CONNECT_TIMEOUT; delete process.env.KAFKA_REQUEST_TIMEOUT; }); it('should return configs and a constructor', () => { const kafkaPackage = Kafka(); assert.equal(typeof kafkaPackage, 'object'); assert.deepEqual(kafkaPackage.config, { KAFKA_HOST: undefined, KAFKA_TOPIC: undefined }); assert.equal(typeof kafkaPackage.class, 'function'); assert(kafkaPackage.class, Kafka.KafkaSubscriber); }); it('should return given configs and a constructor', () => { const configs = { KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic' }; const kafkaPackage = Kafka(configs); assert.equal(typeof kafkaPackage, 'object'); assert.deepEqual(kafkaPackage.config, configs); assert.equal(typeof kafkaPackage.class, 'function'); }); it('should not throw if no settings are given', () => { const kafka = new Kafka.KafkaSubscriber({}); assert.equal(kafka.kafkaClient, undefined); assert.equal(kafka.kafkaSubscriber, undefined); }); it('should expose its main functions', () => { const kafka = new Kafka.KafkaSubscriber({}); assert.equal(typeof kafka, 'object'); assert.equal(kafka.name, 'KAFKA'); assert.equal(typeof kafka.cleanup, 'function'); assert.equal(typeof kafka.isEnabled, 'function'); assert.equal(typeof kafka.handle, 'function'); }); it('should not be initialized if no url is provided', () => { const logger = stream.adapters.get('logger'); const spy = sinon.spy(logger, 'warn'); const kafka = new Kafka.KafkaSubscriber({ KAFKA_TOPIC: 'testTopic' }); assert(spy.calledWith('Kafka logtify module is not active due to a missing KAFKA_HOST and/or KAFKA_TOPIC')); assert.equal(kafka.kafkaClient, undefined); assert.equal(kafka.kafkaProducer, undefined); assert.equal(kafka.ready, false); spy.restore(); }); it('should not be initialized if no topic was provided', () => { const logger = stream.adapters.get('logger'); const spy = sinon.spy(logger, 'warn'); const kafka = new Kafka.KafkaSubscriber({ KAFKA_HOST: 'test' }); assert(spy.calledWith('Kafka logtify module is not active due to a missing KAFKA_HOST and/or KAFKA_TOPIC')); assert.equal(kafka.kafkaClient, undefined); assert.equal(kafka.kafkaProducer, undefined); assert.equal(kafka.ready, false); spy.restore(); }); it('should be initialized if all configs were provided', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_TOPIC: 'testTopic', KAFKA_HOST: 'test' }); assert.equal(typeof kafka.kafkaClient, 'object'); assert.equal(typeof kafka.kafkaProducer, 'object'); }); it('should be ready if al configs provided [env]', () => { process.env.KAFKA_HOST = 'test'; process.env.KAFKA_TOPIC = 'testTopic'; const subscriber = Kafka({}); const kafka = new Kafka.KafkaSubscriber(subscriber.config); assert.equal(typeof kafka.kafkaClient, 'object'); assert.equal(typeof kafka.kafkaProducer, 'object'); }); it('should indicate if it is switched on/off [settings]', () => { let kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: true }); assert.equal(kafka.isEnabled(), true); kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: false }); assert.equal(kafka.isEnabled(), false); kafka = new Kafka.KafkaSubscriber(null); assert.equal(kafka.isEnabled(), true); }); it('should indicate if it is switched on/off [envs]', () => { const kafka = new Kafka.KafkaSubscriber(null); assert.equal(kafka.isEnabled(), true); process.env.KAFKA_LOGGING = true; assert.equal(kafka.isEnabled(), true); process.env.KAFKA_LOGGING = false; assert.equal(kafka.isEnabled(), false); }); it('should indicate if it is switched on/off [envs should have more privilege]', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: true }); assert.equal(kafka.isEnabled(), true); process.env.KAFKA_LOGGING = false; assert.equal(kafka.isEnabled(), false); process.env.KAFKA_LOGGING = undefined; assert.equal(kafka.isEnabled(), true); }); it('should not break down if null is notified', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: true, KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic' }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; kafka.handle(null); }); it('should log message if KAFKA_LOGGING = true', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: true, KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic' }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const message = new Message(); kafka.handle(message); assert(spy.called); spy.restore(); }); it('should not log message if KAFKA_LOGGING = false', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: false, KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic' }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const message = new Message(); kafka.handle(message); assert(!spy.called); spy.restore(); }); it('should accept additional settings parameters as one of the settings', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: false, KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic', KAFKA_CONNECT_TIMEOUT: 1000, KAFKA_REQUEST_TIMEOUT: 1000 }); assert.equal(kafka.kafkaClient.options.connectTimeout, 1000); assert.equal(kafka.kafkaClient.options.requestTimeout, 1000); }); it('should accept additional settings parameters as one of the settings [env]', () => { process.env.KAFKA_CONNECT_TIMEOUT = 1000; process.env.KAFKA_REQUEST_TIMEOUT = 1000; const kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: false, KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic' }); assert.equal(kafka.kafkaClient.options.connectTimeout, 1000); assert.equal(kafka.kafkaClient.options.requestTimeout, 1000); }); it('should not log if message level < MIN_LOG_LEVEL [settings]', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: true, KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic', MIN_LOG_LEVEL: 'error' }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const message = new Message(); kafka.handle(message); assert(!spy.called); spy.restore(); }); it('should not log if message level < MIN_LOG_LEVEL [envs]', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_LOGGING: true, KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic' }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; process.env.MIN_LOG_LEVEL = 'warn'; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const message = new Message(); kafka.handle(message); assert(!spy.called); spy.restore(); }); it('should log if message level >= MIN_LOG_LEVEL_KAFKA but < MIN_LOG_LEVEL [envs]', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic', KAFKA_LOGGING: true }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const message = new Message('warn'); process.env.MIN_LOG_LEVEL = 'error'; process.env.MIN_LOG_LEVEL_KAFKA = 'warn'; kafka.handle(message); assert(spy.called); spy.restore(); }); it('should log if message level = MIN_LOG_LEVEL [envs]', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic', KAFKA_LOGGING: true }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const message = new Message('error'); process.env.MIN_LOG_LEVEL = 'error'; kafka.handle(message); assert(spy.called); spy.restore(); }); it('should log if message level > MIN_LOG_LEVEL [envs]', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic', KAFKA_LOGGING: true }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const message = new Message('error'); process.env.MIN_LOG_LEVEL = 'warn'; kafka.handle(message); assert(spy.called); spy.restore(); }); it('should correctly process a message', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic', KAFKA_LOGGING: true, JSONIFY: true }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const message = new Message('error', 'Hello world', { hello: 'world', one: 1, two: '2' }); kafka.handle(message); assert(spy.called); assert.deepEqual(spy.args[0][0], [{ topic: 'testTopic', messages: { level: 'error', text: 'Hello world', prefix: { timestamp: '', environment: '', logLevel: '', reqId: '', isEmpty: true }, metadata: { instanceId: message.payload.meta.instanceId, hello: 'world', one: 1, two: '2' } }, partition: 0, attributes: 0 }]); spy.restore(); }); it('should correctly handle error sent as a message [msg body]', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic', KAFKA_LOGGING: true, JSONIFY: true }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const error = new Error('Sprint plan was modified'); const message = new Message('error', error, { hello: 'world', one: 1, two: '2' }); kafka.handle(message); assert(spy.called); assert.deepEqual(spy.args[0][0], [{ topic: 'testTopic', messages: { level: 'error', text: message.payload.text, prefix: { timestamp: '', environment: '', logLevel: '', reqId: '', isEmpty: true }, metadata: { error: serializeError(error), instanceId: message.payload.meta.instanceId, hello: 'world', one: 1, two: '2' } }, partition: 0, attributes: 0 }]); spy.restore(); }); it('should correctly handle error sent as a message metadata [msg body]', () => { const kafka = new Kafka.KafkaSubscriber({ KAFKA_HOST: 'test', KAFKA_TOPIC: 'testTopic', KAFKA_LOGGING: true, JSONIFY: true }); // setting manually because there is no broker and 'ready' even will never be fired kafka.ready = true; const spy = sinon.spy(kafka.kafkaProducer, 'send'); const error = new Error('Sprint plan was modified'); const message = new Message('error', 'OMG!!!', { error, hello: 'world', one: 1, two: '2' }); kafka.handle(message); assert(spy.called); assert.deepEqual(spy.args[0][0], [{ topic: 'testTopic', messages: { level: 'error', text: 'OMG!!!', prefix: { timestamp: '', environment: '', logLevel: '', reqId: '', isEmpty: true }, metadata: { error: serializeError(error), instanceId: message.payload.meta.instanceId, hello: 'world', one: 1, two: '2' } }, partition: 0, attributes: 0 }]); spy.restore(); }); });
import { FETCHING_PATIENT, FETCHING_PATIENT_SUCCESS, FETCHING_PATIENT_FAILURE, REMOVE_FETCHING_PATIENT, UPDATE_CONDITION_INPUT, UPDATE_ASSESSMENT_INPUT, TOGGLE_BADGE, FETCHING_ADD_PATIENT_FORM_SUCCESS, UPDATE_ADD_PATIENT_FORM_VALUE, } from './types'; import { fetchPatient, fetchAddPatientForm, } from '../services/api/patient'; const fetchingPatient = () => { return { type: FETCHING_PATIENT, } } const fetchingPatientSuccess = (patientId, patient, timestamp) => { return { type: FETCHING_PATIENT_SUCCESS, patientId, patient, timestamp, } } const fetchingPatientFailure = (message, error) => { console.warn(error); return { type: FETCHING_PATIENT_FAILURE, error: `Error fetching ${message}`, } } export const removeFetchingPatient = () => { return { type: REMOVE_FETCHING_PATIENT, } } export const fetchAndHandlePatient = (patientId) => { return function (dispatch) { dispatch(fetchingPatient()) return fetchPatient(patientId) .then((patient) => dispatch(fetchingPatientSuccess(patientId, patient, Date.now()))) .catch((error) => dispatch(fetchingPatientFailure(`patientId: ${patientId}`, error))) } } export const updateConditionInput = (conditionId, input) => { return { type: UPDATE_CONDITION_INPUT, conditionId, input, } } export const updateAssessmentInput = (assessmentId, assessmentType, input) => { return { type: UPDATE_ASSESSMENT_INPUT, assessmentType, assessmentId, input, } } export const toggleBadge = (badgeId, assessmentId, assessmentType) => { return { type: TOGGLE_BADGE, assessmentType, assessmentId, badgeId, } } const fetchingAddPatientFormSuccess = (addPatientForm) => { return { type: FETCHING_ADD_PATIENT_FORM_SUCCESS, addPatientForm, } } export const fetchingAddPatientForm = (uid) => { return dispatch => { dispatch(fetchingPatient()) return fetchAddPatientForm(uid) .then(addPatientForm => dispatch(fetchingAddPatientFormSuccess(addPatientForm))) .catch(error => dispatch(fetchingPatientFailure(`addPatientForm for user ${uid}`, error))) } } export const updateAddPatientFormValue = (sectionType, inputId, value) => { return { type: UPDATE_ADD_PATIENT_FORM_VALUE, sectionType, inputId, value, } }
/** * Created by Niki on 18/9/16. */ $(function () { // $("#outbox").one("click", function () { var senderJS = $('#user').text(); $.ajax({ url: 'assets/pdos/outgoing.php', method: 'POST', dataType: 'json', data: {senderphp: senderJS}, success: function (response) { var html = ''; for (var i in response) { html += '<tr>' + '<td>' + response[i].receiver + '</td>' + '<td>' + response[i].subject + '</td>' + '<td>' + response[i].date + '</td>' + '</tr>'; } $('#tbody-out').append(html); $('body').on('click', '#tbody-out td', function () { var listIndex = parseInt($(this).parent('tr').index()); if (listIndex != 0) { alert(response[listIndex - 1].message); } }); }, error: function (response) { alert("fail outgoing"); } }); //}); });
import React from 'react' import {ContextProvider} from "../Global/Context" import {db} from "../config" const Comments=(props)=> { const {loader, user, publishComment} = React.useContext(ContextProvider) const [state, setState]= React.useState('') const [comments, setComments]= React.useState([]) const postComment =e =>{ e.preventDefault(); publishComment({ id:props.id, Comment:state, }) setState("") } React.useEffect(()=>{ db.collection("posts").doc(props.id).collection("comments").orderBy("currentTime", "desc").onSnapshot(snp=>{ setComments(snp.docs.map(doc=>doc.data())) }) },[]) return ( <div className="comments"> {comments.map(comment => ( <div className="comments__container" key={comment.id}> <div className="comments__container-name">{comment.username}</div> <div className="comments__container-msg">{comment.comment}</div> </div> ))} <div className="comments__section"> {!loader && user ?(<form onSubmit={postComment}> <input type="text" className="comment__input" onChange={(e)=> setState(e.target.value)} value={state} placeholder="Add a comments..." required/> </form>) :("")} </div> </div> ) } export default Comments
const express = require('express'); const bodyParser = require('body-parser'); const helper = require('../helpers/github.js'); const getRepos = helper.getReposByUsername; const db = require('../database/index.js'); let app = express(); app.use(express.static(__dirname + '/../client/dist')); app.use(express.json()); app.use(bodyParser.urlencoded({extended: true})); app.post('/repos', function (req, res) { // TODO - your code here! // This route should take the github username provided // and get the repo information from the github API, then getRepos('hackreactor', (err, results) => { if (err) console.log("ERRRR"); else { console.log('posting to DB'); console.log(results); db.save(results, (err, results) => { console.log(results); }); } }) res.send('hi') }); app.get('/repos', function (req, res) { // TODO - your code here! // This route should send back the top 25 repos // db.get('hackreactor', console.log); res.send('hello') }); let port = 1128; app.listen(port, function() { console.log(`listening on port ${port}`); });
import { sortTeams } from "../utils/aux.js"; import { scoreGoals } from "../utils/aux.js"; import { playMatch } from "../utils/aux.js"; export default class Group { constructor(name, teams = [], config = {}) { this.name = name; this.schedule = []; this.setup(config); this.setupTeams(teams); this.setup(config); } setup(config) { const defaultConfig = { numberOfTeams: 4, pointsPerWin: 3, pointsPerDraw: 1, pointsPerLoss: 0, matchDays: 3, rounds: 1 } this.config = Object.assign(defaultConfig, config) } setupTeams(teamNames) { this.teams = []; for (const teamName of teamNames) { const team = this.customizeTeam(teamName); this.teams.push(team); } } customizeTeam(teamName) { return { name: teamName, group: this.name, points: 0, wins: 0, draws: 0, lost: 0, goalsFor: 0, goalsAgainst: 0, goalsDiff: 0 } } setupSchedule() { this.initSchedule(); this.setLocalTeams(); this.setVisitorTeams(); this.setLastTeam(); } initSchedule() { const numberOfMatchDays = this.teams.length - 1; const matchesPerMatchDay = this.teams.length / 2; for (let i = 0; i < numberOfMatchDays; i++) { const matchDay = []; for (let j = 0; j < matchesPerMatchDay; j++) { const match = { local: 'local', visitor: 'visitor' }; matchDay.push(match); } this.schedule.push(matchDay) } } setLocalTeams() { const teamNames = this.teams.map(team => team.name); let teamIndex = 0; const maxLocalTeams = this.teams.length - 2; this.schedule.forEach((matchDay, matchDayIndex) => { matchDay.forEach((match , matchIndex) => { match.local = teamNames[teamIndex]; teamIndex++; if (teamIndex > maxLocalTeams) { teamIndex = 0; } }) }) } setVisitorTeams() { const numberOfMatchDays = this.teams.length - 1; const matchesPerMatchDay = this.teams.length / 2; const teamNames = this.teams.map(team => team.name); let index = this.teams.length - 2; for (let i=0; i < numberOfMatchDays; i++) { for (let j=1; j < matchesPerMatchDay; j++) { this.schedule[i][j].visitor = teamNames[index]; index--; } } for (let i=0; i < this.schedule.length; i++){ if ((this.schedule[i][0]) && (i % 2 === 0)); { this.schedule[i][0].visitor = this.schedule[i][0].local; } } } setLastTeam() { const numberOfMatchDays = this.teams.length - 1; const teamNames = this.teams.map(team => team.name); const index = this.teams.length - 1; for (let i = 0; i < numberOfMatchDays; i++) { if (i % 2 === 0) { this.schedule[i][0].visitor = teamNames[index]; } else { this.schedule[i][0].local = teamNames[index]; } } } showGroupSchedule() { console.log(`\nGroup ${this.name}`); console.log('-------'); const teamNames = this.teams.map(team => team.name); for (const teamName of teamNames) { console.log(teamName); } for (let i = 0; i < this.schedule.length; i++) { console.log(`\nMatchday ${i + 1}\n`); for (let j = 0; j < 2; j++) { console.log(`${this.schedule[i][j]['local']} vs. ${this.schedule[i][j]['visitor']}`); } } } playMatchDay(matchDay, match) { const local = this.schedule[matchDay][match]['local']; const visitor = this.schedule[matchDay][match]['visitor']; const localGoals = scoreGoals(); const visitorGoals = scoreGoals(); const winner = playMatch(local, visitor, localGoals, visitorGoals); this.updateTeams(local, visitor, localGoals, visitorGoals, winner); const result = `${local} ${localGoals} - ${visitor} ${visitorGoals} --> ${winner || 'It\'s a draw'}`; return result; } updateTeams(local, visitor, localGoals, visitorGoals, winner) { this.teams.forEach(team => { if (team.name === local) { team.goalsFor += localGoals team.goalsAgainst += visitorGoals team.goalsDiff += localGoals - visitorGoals; switch (winner) { case local: team.wins += 1; team.points += this.config.pointsPerWin; break; case visitor: team.lost += 1; team.points += this.config.pointsPerLoss; break; default: team.draws += 1; team.points += this.config.pointsPerDraw; } } if (team.name === visitor) { team.goalsFor += visitorGoals; team.goalsAgainst += localGoals; team.goalsDiff += visitorGoals - localGoals; switch (winner) { case local: team.lost += 1; team.points += this.config.pointsPerLoss; break; case visitor: team.wins += 1; team.points += this.config.pointsPerWin; break; default: team.draws += 1; team.points += this.config.pointsPerDraw; } } }) } showMatchDayResults() { sortTeams(this.teams); console.table(this.teams); } }
import React from 'react'; import styled, { css } from 'react-emotion'; import { PlaceIcon } from 'mdi-react'; const MapMarker = ({ name, date }) => { const Container = styled('div')` display: flex; width: ; flex-direction: column; align-items: center; justify-content: center; margin-top: -70px; ` const Info = styled('div')` background-color: white; display: flex; flex-direction: column; align-items: center; justify-content: center; border-radius: 10px; padding-top: 5px; padding-left: 5px; padding-right: 5px; padding-bottom: 10px; ` const titleStyle = css` font-weight: 600; font-size: 1.5em; display: inline; ` const dateStyle = css` font-size: 1em; display: inline; ` const iconStyle = css` color: red; margin-top: -15px; ` return ( <Container> <Info> <span className={ titleStyle }>{ name }</span> <span className={ dateStyle }>{ date }</span> </Info> <PlaceIcon className={iconStyle} size={50} /> </Container> ); } export default MapMarker
'use strict'; module.exports = function(Expense) { Expense.observe('access', async (ctx) => { console.log('expense access') }) };
function solve(input) { const materials = { fragments:0, motes:0, shards:0 }; const trashes = {}; let result = ''; const tokens = input.split(' '); for (let i = 0; i < tokens.length; i+=2) { const value = +tokens[i]; const material = tokens[i + 1].toLowerCase(); if (material === 'motes' || material === 'shards' || material === 'fragments') { materials[material] += value; } else { if (!trashes.hasOwnProperty(material)) { trashes[material] = value; } else { trashes[material] += value; } } if (materials[material] >= 250) { if (material === 'shards') { result = 'Shadowmourne obtained!'; materials[material] -= 250; break; } else if (material === 'fragments') { result = 'Valanyr obtained!'; materials[material] -= 250; break; } else if (material === 'motes') { result = 'Dragonwrath obtained!'; materials[material] -= 250; break; } } } let sortedMaterials = Object.entries(materials) .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); let sortedTrash = Object.keys(trashes) .sort((a, b) => a.localeCompare(b)); console.log(result); for (const [k, v] of sortedMaterials) { console.log(`${k}: ${v}`); } for (const trash of sortedTrash) { console.log(`${trash}: ${trashes[trash]}`); } } solve('123 silver 6 shards 8 shards 5 motes 9 fangs 75 motes 103 MOTES 8 Shards 86 Motes 7 stones 19 silver');
var controllers = angular.module('starter.controllers', ['ionic']) var services = angular.module('starter.services', [])
import React from "react"; import PropTypes from "prop-types"; import { makeStyles } from "@material-ui/core/styles"; import AppBar from "@material-ui/core/AppBar"; import Tabs from "@material-ui/core/Tabs"; import Tab from "@material-ui/core/Tab"; import Box from "@material-ui/core/Box"; import Container from "@material-ui/core/Container"; import Search from "./Search"; import MainPage from "../MainPage/MainPage"; import GoodsPage from "../GoodsPage/GoodsPage"; import AboutPage from "../AboutPage/AboutPage"; import DelivePayPage from "../DelivePayPage/DelivePayPage"; import NewsPage from "../NewsPage/NewsPage"; import ContactsPage from "../ContactsPage/ContactsPage"; import { Link, BrowserRouter, Route, Switch } from "react-router-dom"; import Category from "../Category/Category"; import Details from "../DetailsPage/Details"; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, backgroundColor: theme.palette.background.paper, }, })); export default function NavTabs() { const containers = { categories: [ { id: "medicine", name: "Тара для медицины", number: "72", image: "http://tara.kh.ua/wp-content/uploads/2019/07/Tara-dlya-medicziny-i-kosmetiki.jpg", description: "Применяется для упаковки: таблеток, витаминов, порошков, мазей, кремов, бальзамов, гелей, красок, спортивного питания, чистящих средств.", subCategories: [ { subId: "slamCap", subName: "С крышкой захлопкой", subNumber: "24", subImage: "http://tara.kh.ua/wp-content/uploads/2019/08/Tara-dlya-medicziny-i-kosmetiki-300x300.jpg", }, { subId: "scruwCap", subName: "С винтовой крышкой", subNumber: "35", subImage: "http://tara.kh.ua/wp-content/uploads/2019/08/Tara-dlya-medicziny-i-kosmetiki-1-300x300.jpg", }, { subId: "powderJar", subName: "Баночки под присыпку", subNumber: "5", subImage: "http://tara.kh.ua/wp-content/uploads/2019/08/Banka-dlya-prisypki-300x300.jpg", }, { subId: "bottle", subName: "бутылки под ПЭТ крышку", subNumber: "7", subImage: "http://tara.kh.ua/wp-content/uploads/2019/08/Tara-dlya-medicziny-i-kosmetiki-2-300x300.jpg", }, { subId: "testJar", subName: "Контейнеры для анализов", subNumber: "2", subImage: "http://tara.kh.ua/wp-content/uploads/2019/08/Kontejnery-laboratornye-300x300.jpg", }, ], }, { id: "makeup", name: "Тара для косметики", number: "133", image: "http://tara.kh.ua/wp-content/uploads/2019/07/Tara-dlya-kosmetiki.jpg", subCategories: [ { subId: "makeup1", subName: "makeup", subNumber: "24", subImage: "http://tara.kh.ua/wp-content/uploads/2019/08/Tara-dlya-medicziny-i-kosmetiki-300x300.jpg", }, { subId: "makeup2", subName: "makeup", subNumber: "35", subImage: "http://tara.kh.ua/wp-content/uploads/2019/08/Tara-dlya-medicziny-i-kosmetiki-1-300x300.jpg", }, ], }, { id: "nutrition", name: "Тара для спортивного питания", number: "23", image: "http://tara.kh.ua/wp-content/uploads/2019/07/Tara-dlya-sportivnogo-pitaniya.jpg", }, { id: "jar", name: "Баночки", number: "", image: "http://tara.kh.ua/wp-content/uploads/2019/07/Obshhaya.jpg", }, { id: "busket", name: "Вёдра", number: "25", image: "http://tara.kh.ua/wp-content/uploads/2019/07/Plastikovye-vyodra.jpg", }, { id: "dish", name: "Судки", number: "20", image: "http://tara.kh.ua/wp-content/uploads/2019/07/Sudki.jpg", }, ], }; const classes = useStyles(); const [value, setValue] = React.useState(0); const handleChange = (event, newValue) => { setValue(newValue); }; const { categories } = containers; const { categories: { ...subCategories } } = containers; // const { // subCategories: { ...subSubCategories } // } = categories; return ( <BrowserRouter> <div className={classes.root}> <AppBar position="static"> <Container> <Tabs variant="fullWidth" value={value} onChange={handleChange} aria-label="nav tabs example" > <Tab label="Главная" component={Link} to="/main" /> <Tab label="Продукция" component={Link} to="/goods" /> <Tab label="О нас" component={Link} to="/about" /> <Tab label="Доставка и оплата" component={Link} to="/delivepay" /> <Tab label="Новости" component={Link} to="/news" /> <Tab label="Контакты" component={Link} to="/contacts" /> <Box display="flex" alignItems="center"> <Search /> </Box> </Tabs> </Container> </AppBar> <Switch> <Route exact path="/" render={(props) => <MainPage {...props} containers={containers} />} /> <Route path="/main" render={(props) => <MainPage {...props} containers={containers} />} /> <Route path="/goods" render={(props) => <GoodsPage {...props} containers={containers} />} /> <Route path="/delivepay" render={(props) => ( <DelivePayPage {...props} containers={containers} /> )} /> <Route path="/news" render={(props) => <NewsPage {...props} containers={containers} />} /> <Route path="/about" render={(props) => <AboutPage {...props} containers={containers} />} /> <Route path="/contacts" render={(props) => ( <ContactsPage {...props} containers={containers} /> )} /> <Route exact path="/categories/:id" render={(props) => { const category = categories.find( ({ id }) => id === props.match.params.id ); return <Category {...props} {...category} />; }} /> <Route path="/categories/:id/:subId" render={(props) => { const category = categories.find( ({ id }) => id === props.match.params.id ); const { subCategories } = category; const subCategory = subCategories.find( ({ subId }) => subId === props.match.params.subId ); const sliderCategories = subCategories.slice(0, 4); return <Details subCategory={subCategory} sliderCategories={sliderCategories}/>; }} /> </Switch> </div> </BrowserRouter> ); }
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { setAddress } from '../ducks/propertyReducer'; import { Link } from 'react-router-dom'; class Wiz2 extends Component { constructor() { super(); this.state = { street: '', city: '', state: '', zip: '' } this.handleClick = this.handleClick.bind(this); } handleInput(field, input) { let tempField = {}; tempField[field] = input; this.setState(tempField); } handleClick() { this.props.setAddress({ street: this.state.street, city: this.state.city, state: this.state.state, zip: this.state.zip, }); } render() { return( <div> <p>Address</p> <input placeholder={this.props.address.street} onChange={(e) => this.handleInput('street', e.target.value)}/> <p>City</p> <input placeholder={this.props.address.city} onChange={(e) => this.handleInput('city', e.target.value)}/> <p>State</p> <input placeholder={this.props.address.state} onChange={(e) => this.handleInput('state', e.target.value)}/> <p>Zip</p> <input placeholder={this.props.address.zip} onChange={(e) => this.handleInput('zip', e.target.value)}/> <Link to='/wizard/1'><button>Previous Step</button></Link> <Link to='/wizard/3'><button onClick={this.handleClick}>Next Step</button></Link> </div> ) } } function mapStateToProps(state) { return { address: state.address } } export default connect(mapStateToProps, { setAddress })(Wiz2);
import React from 'react' import '../index.css' import styled from 'styled-components' function Header() { return ( <Nav> <Logo src="/images/logo.svg"/> <NavMenu> <a> <img src="/images/home-icon.svg"/> <span>HOME</span> </a> <a> <img src="/images/search-icon.svg"/> <span>SEARCH</span> </a> <a> <img src="/images/watchlist-icon.svg"/> <span>WATCHLIST</span> </a> <a> <img src="/images/original-icon.svg"/> <span>ORGINALS</span> </a> <a> <img src="/images/movie-icon.svg"/> <span>MOVIES</span> </a> <a> <img src="/images/series-icon.svg"/> <span>SERIES</span> </a> </NavMenu> <UserImg src="https://www.workingdads.co.uk/wp-content/uploads/2018/12/Duncan-Fisher-220x220.jpeg"/> </Nav> ) } export default Header const Nav=styled.nav ` height:70px; background-color:#090b13; display:flex; align-items:center; padding:0 36px; ` const Logo=styled.img ` width:80px; cursor:pointer; ` const NavMenu =styled.div ` display:flex; flex:1; margin-left:25px; align-items:center; a{ display:flex; align-items:center; padding:0 12px; cursor:pointer; img{ height:20px; } span{ font-size:13px; letter-spacing:1.42px; position:relative; &:after{ content:""; height:2px; background:white; position:absolute; left:0; right:0; bottom:-6px; opacity:0; transform:scaleX(0); transform-origin:left center; transition:all 250ms cubic-bezier(0.25,0.46,0.45,0.95) 0s; } } &:hover{ span:after{ opacity:1; transform:scaleX(1); } } } ` const UserImg=styled.img ` height:48px; width:48px; border-radius:50%; cursor:pointer; `
// EXAMPLE 3. READ AND WRITE FILES ASYNCHRONOUSLY WITH PROMISES var Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs')); var text = 'Hello Faster World with Promises' // Same as example2 but using promises to avoid callback hell fs.mkdirAsync('./example3') .catch(err => console.log('directory already exists')) .then(() => fs.writeFileAsync('./example3/readme.txt', text)) .then(() => fs.readFileAsync('./example3/readme.txt', 'utf8')) .then((data) => console.log(data)) .catch(err => console.log(err)); // This runs immediately as above code is asynchronous console.log('...rest of code');
module.exports = function () { 'use strict'; var qs = require('qs') , url = require('url'); return function (req) { return ~req.url.indexOf('?') ? qs.parse(url.parse(req.url).query) : {}; }; }();
/* * File: app/view/UserOperLog.js * * This file was generated by Sencha Architect version 3.2.0. * http://www.sencha.com/products/architect/ * * This file requires use of the Ext JS 4.2.x library, under independent license. * License of Sencha Architect does not include license for Ext JS 4.2.x. For more * details see http://www.sencha.com/license or contact license@sencha.com. * * This file will be auto-generated each and everytime you save your project. * * Do NOT hand edit this file. */ Ext.define('platform.system.view.UserOperLog', { extend: 'Ext.grid.Panel', requires: [ 'platform.system.view.DateTegion', 'Ext.button.Button', 'Ext.form.Panel', 'Ext.grid.column.Column', 'Ext.grid.View', 'Ext.selection.CheckboxModel', 'Ext.toolbar.Paging', 'Ext.form.field.ComboBox' ], title: '用户管理日志', forceFit: true, initComponent: function() { var me = this; Ext.applyIf(me, { dockedItems: [ { xtype: 'toolbar', dock: 'top', height: '', items: [ { xtype: 'button', iconCls: 'icon-search', text: '查询', listeners: { afterrender: { fn: me.onBtnSearchAfterRender, scope: me }, click: { fn: me.onBtnSearchClick, scope: me } } }, { xtype: 'button', iconCls: 'icon-file', text: '导出', listeners: { click: { fn: me.onButtonClick, scope: me } } } ] }, { xtype: 'form', dock: 'top', layout: 'column', header: false, title: '查询条件', listeners: { beforerender: { fn: me.onFormBeforeRender, scope: me } }, items: [ { xtype: 'textfield', margin: 5, width: 270, fieldLabel: '功能名称', labelAlign: 'right', labelWidth: 60, name: 'name' }, { xtype: 'DateTegion', label: '日志时间', margin: 5 } ] }, { xtype: 'pagingtoolbar', dock: 'bottom', width: 360, afterPageText: '页,共 {0} 页', beforePageText: '第', displayInfo: true, displayMsg: '第 {0} - {1} 行,共 {2} 行', listeners: { beforerender: { fn: me.onPagingtoolbarBeforeRender, single: true, scope: me } }, items: [ { xtype: 'combobox', width: 120, fieldLabel: '每页行数', labelAlign: 'right', labelWidth: 60, name: 'pageSize', listeners: { beforerender: { fn: me.onpageSizeBeforRender, single: true, scope: me }, change: { fn: me.onComboboxChange, scope: me } } } ] } ], columns: [ { xtype: 'gridcolumn', width: 150, dataIndex: 'name', text: '功能名称' }, { xtype: 'gridcolumn', width: 150, dataIndex: 'username', text: '被操作用户' }, { xtype: 'gridcolumn', width: 150, dataIndex: 'orgName', text: '机构名称' }, { xtype: 'gridcolumn', width: 150, dataIndex: 'createUsername', text: '操作用户' }, { xtype: 'gridcolumn', width: 150, dataIndex: 'checkUsername', text: '复核用户' }, { xtype: 'gridcolumn', width: 148, dataIndex: 'createTimeStr', text: '日志时间' }, { xtype: 'gridcolumn', width: 150, dataIndex: 'memo', text: '备注' } ], selModel: Ext.create('Ext.selection.CheckboxModel', { }), listeners: { afterrender: { fn: me.onGridpanelAfterRender, scope: me } } }); me.callParent(arguments); }, onBtnSearchAfterRender: function(component, eOpts) { Common.hidden({params : {url:'/system/log/userLogList'},component:component}); }, onBtnSearchClick: function(button, e, eOpts) { this.loadGrid(); }, onButtonClick: function(button, e, eOpts) { try { //alert(JSON.stringify(params)); {"name":"aa","orgid":"bb"} var me=this; var strParam=Common.paramStr(me.form.getForm().getValues()); window.open(ctxp+'/system/log/exportLog?'+encodeURI(encodeURI(strParam))); //location.href = ctxp+'/system/log/exportLog?'+encodeURI(encodeURI(strParam)); } catch (error) { Common.show({title:'操作提示',html:error.toString()}); } }, onFormBeforeRender: function(component, eOpts) { this.form = component; }, onGridpanelAfterRender: function(component, eOpts) { this.loadGrid(); }, onPagingtoolbarBeforeRender: function(component, eOpts) { this.pagingToolbar = component; }, onpageSizeBeforRender: function(component, eOpts) { this.pageSize = component; Common.bindPageSize(component); }, onComboboxChange: function(field, newValue, oldValue, eOpts) { this.loadGrid(); }, loadGrid: function() { try{ var me=this; var params = me.form.getForm().getValues(); Common.loadStore({ component:this, url:ctxp + '/system/log/userLogList', pageSize:this.pageSize.getValue(), fields: ['id', 'name', 'username','createUsername','orgName','checkUsername','memo', 'createTime','createTimeStr','url','argsJson','proceed'], params:params }); }catch(ex){ Common.show({title:'信息提示',html:ex.toString()}); } }, paramstr: function(jsonobj) { var rst=''; for(var key in jsonobj){ var vv=jsonobj[key]; if("undefined"==typeof(vv)){ vv=''; } rst=rst+ '&' + key + '=' + vv; } return rst; } });
import React, {Component} from "react"; import "./Testimonial.scss"; class Testimonial extends Component { render () { return ( <div class="oneTestimonial"> <img className='testimonialImage' src={require(`${this.props.image}`)} alt={""} /> <h1 className='testimonialName'>{this.props.name}<span>{this.props.job}</span></h1> <p className='testimonialText'>{this.props.text}</p> </div> ); } } export default Testimonial;
const requestURL = "https://byui-cit230.github.io/weather/data/towndata.json"; fetch(requestURL) .then(function (response) { return response.json(); }) .then(function (jsonObject) { //console.table(jsonObject); // temporary checking for valid response and data parsing const towns = jsonObject["towns"]; const southern = towns.filter( (town) => town.name == "Preston" || town.name == "Fish Haven" || town.name == "Soda Springs" ); southern.forEach((town) => { let eachTown = document.createElement("article"); let townData = document.createElement("div"); let tname = document.createElement("h2"); let tmotto = document.createElement("h3"); let founded = document.createElement("p"); let population = document.createElement("p"); let rainfall = document.createElement("p"); let image = document.createElement("img"); eachTown.appendChild(townData); tname.innerHTML = town.name; townData.appendChild(tname); tmotto.innerHTML = town.motto; townData.appendChild(tmotto); founded.innerHTML = "Year Founded: " + town.yearFounded; townData.appendChild(founded); population.innerHTML = "Population: " + town.currentPopulation; townData.appendChild(population); rainfall.innerHTML = "Annual Rain Fall: " + town.averageRainfall; townData.appendChild(rainfall); image.setAttribute("src", "images/" + town.photo); image.setAttribute("alt", town.name + ": " + town.motto); image.setAttribute("class", "townimages") eachTown.appendChild(image); document.querySelector("section.towndetails").appendChild(eachTown); eachTown.setAttribute("class", "townArticles"); townData.setAttribute("class", "townSections"); }); });
require('jquery-validation'); var $form = $('form[name="client"]'); $form.validate({ rules:{ "client[firstName]":{required: true, maxlength: 30}, "client[lastName]":{required: true, maxlength: 30}, "client[company]":{required: true, maxlength: 50}, "client[password]":{required: true, maxlength: 30}, "client[clientInfo][siret]":{required: true, maxlength: 14, minlength:14, number: true}, "client[clientInfo][address]":{required: true, maxlength: 50}, "client[clientInfo][postalCode]":{required: true, maxlength: 5, minlength:5, number: true}, "client[clientInfo][city]":{required: true, maxlength: 50}, "client[clientInfo][companyType]":{required: true, maxlength: 50}, }, messages: { "client[firstName]" : { required:"Ce champ est requis", }, "client[lastName]" : { required:"Ce champ est requis", }, "client[company]" : { required:"Ce champ est requis", }, "client[password]" : { required:"Ce champ est requis", }, "client[clientInfo][siret]" : { required:"Ce champ est requis", minlength:"Merci d’insérer 14 caractères maximum", maxlength:"Merci d’insérer au moins 14 caractères" }, "client[clientInfo][address]":{ required:"Ce champ est requis", maxlength:"Merci d’insérer au moins 50 caractères" }, "client[clientInfo][postalCode]":{ required:"Ce champ est requis", maxlength:"Merci d’insérer au moins 5 caractères" }, "client[clientInfo][city]":{ required:"Ce champ est requis", }, "client[clientInfo][companyType]":{ required:"Ce champ est requis", maxlength:"Merci d’insérer au moins 50 caractères" } } });
define(function() { 'use strict'; var Student = (function() { function Student(firstName, lastName, age, mark) { if (validateData(firstName, "string")) { this._firstName = firstName; } if (validateData(lastName, "string")) { this._lastName = lastName; } if (validateData(age, "number")) { this._age = age; } if (validateData(mark, "number")) { this._mark = mark; } } Student.prototype.getFirstName = function () { var firstName = this._firstName; return firstName; }; Student.prototype.getLastName = function () { var lastName = this._lastName; return lastName; }; Student.prototype.getAge = function () { var age = this._age; return age; }; Student.prototype.getMark = function () { var mark = this._mark; return mark; }; function validateData(item, type) { if (typeof item === type || isFinite(item)) { return true; } else { throw new Error(item + " must be a " + type + " variable"); } } return Student; })(); return Student; });
const passport = require('passport') module.exports = function(){ const _getRedirectUrl = (req) => { return req.user.role === 'admin' ? '/admin/orders' : '/customer/orders' } return{ login(req,res){ res.render('auth/login') }, postLogin(req, res, next) { const { email, password } = req.body // Validate request if(!email || !password) { req.flash('error', 'All fields are required') return res.redirect('/login') } passport.authenticate('local', (err, user, info) => { if(err) { console.log('error') req.flash('error', info.message ) return next(err) } if(!user) { console.log('error1') req.flash('error', info.message ) return res.redirect('/login') } req.logIn(user, (err) => { if(err) { console.log('error2') req.flash('error', info.message ) return next(err) } return res.redirect(_getRedirectUrl(req)) }) })(req, res, next) }, postLogout(req, res, next){ req.logout() return res.redirect('/') }, register(req,res){ res.render('auth/register') }, async postRegister(req,res){ const {name,email,password} = req.body const User = require('../../app/models/user') if(!name || !email || !password){ req.flash('error','All fields are required') return res.redirect('/register') } //email exist ?? User.exists({email: email},(err,result)=>{ if(result){ req.flash('error','email already taken') return res.redirect('/register') } }) //haashing a password const bcrypt = require('bcrypt') const hashPassword = await bcrypt.hash(password,10) //create a user let user = new User({ name , email , password : hashPassword }) user.save().then((user) => { //login return res.redirect('/') }).catch((err) => { req.flash('error', 'Something wenr wrong') return res.redirect('/register') }) } } }
/* * The MIT License (MIT) * Copyright (c) 2019. Wise Wild Web * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @author : Nathanael Braun * @contact : n8tz.js@gmail.com */ import {create, get, query, remove, save} from 'App/db'; import debounce from 'debounce' import is from 'is' import React from 'react' import xxhashjs from 'xxhashjs' var H = xxhashjs.h64(0) // seed = 0xABCD function mkQueryH( query ) { //return JSON.stringify(query) return H.update(JSON.stringify(query)).digest().toString(32) } /** * base data provider * - centralize record update & dispatch * */ export default class DataProvider { static actions = { db_save( record, cb ) { save(record) .then( ( data ) => { cb && cb(null, data.result); this.pushRemoteRecord(record) }, ( err ) => { if ( err ) { cb && cb(err) } } ); }, db_preview( record, cb ) { this.pushRecordPreview(record); }, db_clearPreview( id, noRefresh ) { this.clearRecordPreview(id, noRefresh) }, db_create( record, cb ) { create(record) .then( ( data ) => { cb && cb(data); this.pushRemoteRecord(record) this.flushAndReload() }, ( err ) => { if ( err ) { cb && cb(err) } } ); }, db_remove( record, cb ) { remove(record) .then( ( data ) => { cb && cb(data); this.clearRecord(record.id) this.flushAndReload() }, ( err ) => { if ( err ) { cb && cb(err) } } ); } }; data = { ___aliases___ : {}, ___recToQuery___: {}, ___hToQuery___ : {} }; constructor() { //super(...arguments); //this.retain("keepAlive"); } // data cache // recently updated records & queries updatedRecords = {}; /** * Get record by Id if available * @param etty * @param id * @returns {*} */ getRecord( id, etty ) { return this.data && this.data[id] || this.data.___aliases___[etty] && this.data.___aliases___[etty][id] && this.data[this.data.___aliases___[etty][id]]; } /** * Get query results if available * @param query * @returns {*} */ getQuery( query, hash ) { hash = hash || mkQueryH(query); return query && this.data && this.data[hash]; } overidedRecords = {}; retrieve( path ) { let eid = path.join('.').split('µ'); if ( this.data.___aliases___[eid[0]] && this.data.___aliases___[eid[0]][eid[1]] ) return this.data[this.data.___aliases___[eid[0]][eid[1]]]; return this.data[path[1]]; } pushRecordPreview( record ) { if ( !this.overidedRecords[record._id] ) this.overidedRecords[record._id] = this.data[record._id]; this.pushRemoteRecord(record); } clearRecordPreview( id, noRefresh ) { let realRec = this.overidedRecords[id]; delete this.overidedRecords[id]; !noRefresh && realRec && this.pushRemoteRecord(realRec); } clearRecord( id, noRefresh ) { delete this.data[id]; } /** * Update record in the store & dispatch it to the listeners * @param etty * @param id * @param rec */ pushRemoteRecord( rec ) { this.data[rec._id] = rec; this.updatedRecords[rec._id] = rec; if ( rec._alias && this.watchersByEttyId[rec._alias] ) { this.watchersByEttyId[rec._id] = this.watchersByEttyId[rec._id] || []; this.watchersByEttyId[rec._id].push(...this.watchersByEttyId[rec._alias]) delete this.watchersByEttyId[rec._alias]; this.data.___aliases___[rec._cls] = this.data.___aliases___[rec._cls] || {}; this.data.___aliases___[rec._cls][rec._alias] = rec._id; } this.dispatchUpdates(); if ( this.data.___recToQuery___[rec._id] ) { this.data.___recToQuery___[rec._id].forEach( h => { this.data[h].items = this.data[h].items.map(r => (r._id === rec._id ? rec : r)); this.pushRemoteQuery(null, this.data[h], h, true) } ) } } /** * Update query results in the store & dispatch it to the listeners * @param etty * @param id * @param rec */ pushRemoteQuery( query, results, hash, noMap ) { hash = hash || mkQueryH(query); this.data[hash] = results; this.updatedRecords[hash] = results; //this.data.___hToQuery___[hash] = query; this.data.___recToQuery___[hash] = results.items.map(r => r._id); !noMap && results.items.forEach( record => { record && this.pushRemoteRecord(record); this.data.___recToQuery___[record._id] = this.data.___recToQuery___[record._id] || []; !this.data.___recToQuery___[record._id].includes(hash) && this.data.___recToQuery___[record._id].push(hash); } ) if ( !noMap && results.refs ) { Object.keys(results.refs) .forEach( id => this.pushRemoteRecord(results.refs[id]) ) } this.dispatchUpdates(); } /** * Order API call to update/get a record * @param etty * @param id */ syncRemoteRecord( etty, id ) { //if ( !this.state ) { // this.pushRemoteRecord(etty, id, {}) // return console.error("DataProvider: Unknown data type '" + etty + "'") //} //if ( !this.state.query ) { // this.pushRemoteRecord(etty, id, {}) // return console.error("DataProvider: No query API for data type '" + etty + "'") //} //this.dispatch('setLoading'); //this.wait(); get(etty, id, ( err, data ) => { //this.release() if ( err ) { //this.pushRemoteRecord(etty, id, {}) return console.error("DataProvider: get fail '", etty, err); } else this.pushRemoteRecord(data) } ); } /** * Order API call to update/get a query result * @param query */ syncRemoteQuery( queryData, hash ) { //console.info("! query : ", hash, queryData) //this.wait() query(queryData, ( err, data ) => { //this.release() if ( err ) { this.pushRemoteQuery(queryData, { items: [], total: 0, length: 0 }) return console.error("DataProvider: query fail '", queryData.etty, err); } else { this.pushRemoteQuery(queryData, data, hash) } }) } /** * re dld all active queries & records (when remove create or update query success) * ( @todo: need optims ) * @param types */ flushAndReload( types ) { types = types && ( is.string(types) && [types] || types ) || Object.keys(this.data); //types.forEach( // etty => { // if ( etty !== "__queries" ) // this.activeRecords && // Object.keys(this.activeRecords) // .map( // id => this.syncRemoteRecord(etty, id) // ) // } //) Object.keys(this.activeQueries).forEach( id => { this.syncRemoteQuery(this.activeQueries[id], id) } ) } /** * Dispatch last updates to listeners * @type {debounced} */ dispatchUpdates = debounce(() => { let updates = this.updatedRecords, watchers = this.watchersByEttyId; Object .keys(updates) .forEach( id => { if ( watchers && watchers[id] ) watchers[id] .forEach( watcher => watcher(updates[id]) ) } ) this.updatedRecords = {}; }, 50); _scrapStack = []; /** * Order auto clean of not used data * @param etty * @param id */ scrapIt( etty, id ) { this._scrapStack.push( { etty, id, dt: Date.now() } ) if ( !this._scraperTm ) { this._scraperTm = setTimeout(this._autoClean) } } _autoClean = () => { //let watchers = this.watchersByEttyId, // data = this.data, // item, // toClean = this._scrapStack, // dtLimit = Date.now() - 1000 * 60; // 1mn ttl for unused items // //while ( toClean.length ) { // item = toClean[0]; // if ( watchers[item.id] // && watchers[item.id].length )// was put in scrap then réused, remove from scrap list // toClean.shift() // else if ( item.dt < dtLimit ) {// timeout: delete it // console.log("clean", item) // delete data[item.id]; // toClean.shift() // } // else break; //} // //if ( toClean.length ) // this._scraperTm = setTimeout(this._autoClean, 5000);// clean interval //else // this._scraperTm = null; }; watchersByEttyId = {}; activeQueries = {}; activeRecords = {}; /** * Add new record listener & query it if not available * @param etty * @param id * @param watcher */ bindRecord( etty, id, watcher ) { let refs = this.watchersByEttyId, newRequest, noData = !this.data || !this.data[id]; refs = refs || {}; newRequest = !refs[id]; refs[id] = refs[id] || []; refs[id].push(watcher); if ( newRequest ) { this.activeRecords = this.activeRecords || {}; this.activeRecords[id] = id; } //console.info("! watch record : ", id) // + socket watch record (debounced) if ( newRequest ) { if ( noData ) this.syncRemoteRecord(etty, id); else watcher(this.data[id]) } else !noData && watcher(this.data[id]) return etty + 'µ' + id; } unBindRecord( etty, id, watcher ) { let refs = this.watchersByEttyId; refs = refs || {}; refs[id] = refs[id] || []; let i = refs[id].indexOf(watcher); if ( i != -1 ) refs[id].splice(i, 1); if ( !refs[id].length ) { delete refs[id]; if ( this.activeRecords ) delete this.activeRecords[id]; this.scrapIt(etty, id); } //console.info("! unwatch record : ", id) // - socket watch record if no more watchers } /** * Add new query listener & query it if not available * @param etty * @param id * @param watcher */ bindQuery( query, watcher ) { let refs = this.watchersByEttyId, hash = mkQueryH(query), etty = query.etty, newRequest, noData = !this.data || !this.data[hash]; refs = refs || {}; newRequest = !refs[hash]; refs[hash] = refs[hash] || []; refs[hash].push(watcher); if ( newRequest ) { this.activeQueries = this.activeQueries || {}; this.activeQueries[hash] = query; } // + socket watch / sync query record (debounced) //console.info("! watch query : ", hash, query) if ( newRequest ) { if ( noData ) this.syncRemoteQuery(query, hash); else watcher(this.data[hash]) } else !noData && watcher(this.data[hash]) return hash; } unBindQuery( query, watcher ) { let refs = this.watchersByEttyId, hash = mkQueryH(query), etty = "__queries"; refs[hash] = refs[hash] || []; let i = refs[hash].indexOf(watcher); if ( i != -1 ) refs[hash].splice(i, 1); if ( !refs[hash].length ) { delete refs[hash]; delete this.activeQueries[hash]; this.scrapIt(etty, hash); } // - socket watch record if no more watchers //console.info("! unwatch query : ", hash) } } function walk( obj, path ) { if ( is.string(path) ) path = path.split('.'); return path.length ? obj[path[0]] && walk(obj[path[0]], path.slice(1)) : obj; } export function clearWatchers( target, DataProvider, idKeys, isQuery ) { let watchKey = !isQuery ? "__recWatchers" : "__queryWatchers", watchs = target[watchKey] = target[watchKey] || {}; Object.keys( watchs ).map( idKey => !isQuery ? DataProvider.unBindRecord( idKeys[idKey].etty, watchs[idKey].value, watchs[idKey].fn ) : DataProvider.unBindQuery( watchs[idKey].value, watchs[idKey].fn ) ); target.__recWatchers = {}; } export function updateWatchers( target, DataProvider, idKeys, changes, isQuery ) { let watchKey = !isQuery ? "__recWatchers" : "__queryWatchers", watchs = target[watchKey] = target[watchKey] || {}, hasChanges; target.__activeRequests = target.__activeRequests || 0; Object.keys(idKeys) .forEach( idKey => { let newValue = isQuery ? changes[idKey] : idKeys[idKey] && (changes[idKey].id || idKeys[idKey]._id), key = idKeys[idKey] && idKeys[idKey].target || idKey; if ( idKeys[idKey] && (!watchs[idKey] || watchs[idKey].value !== newValue) ) { let initial = newValue && ( isQuery ? !DataProvider.getQuery(newValue) : !DataProvider.getRecord(newValue) ); target.__activeRequests++; hasChanges = true; if ( !isQuery ) watchs[idKey] && DataProvider.unBindRecord( idKeys[idKey].etty, watchs[idKey].value, watchs[idKey].fn ); else watchs[idKey] && DataProvider.unBindQuery( watchs[idKey].value, watchs[idKey].fn ); delete watchs[idKey]; if ( newValue ) { watchs[idKey] = { value: newValue, fn : ( update ) => { initial && target.__activeRequests--; initial = false; !target.dead && target.push( { ...target.data, [key]: update }) } } if ( !isQuery ) watchs[idKey].key = DataProvider.bindRecord( idKeys[idKey].etty, watchs[idKey].value, watchs[idKey].fn ) else watchs[idKey].key = DataProvider.bindQuery( watchs[idKey].value, watchs[idKey].fn ); if ( (!target.data || !target.data[key]) && changes[idKey].default ) target.push( { [key]: { ...changes[idKey].default } }) } else { target.push( { ...target.data, [key]: null }) } } else if ( !newValue ) { target.push( { ...target.data, [key]: null }) } } ) return hasChanges; } export function getRecordsFromIdKeys( DataProvider, idKeys, changes ) { let results = {}; Object.keys(idKeys) .forEach( idKey => { results[idKeys[idKey].target] = DataProvider.getRecord(walk(changes, idKey)) } ) return results; } export function getQueriesFromIdKeys( DataProvider, idKeys, changes ) { let results = {}; Object.keys(idKeys) .forEach( idKey => { results[idKeys[idKey].target || idKey] = DataProvider.getQuery(walk(changes, idKey)) || idKeys[idKey].default } ) return results; }
/* eslint-disable no-console */ /* eslint-disable camelcase */ /* eslint-disable no-undef */ import chai from 'chai'; import chaiHttp from 'chai-http'; import jwt from 'jsonwebtoken'; import moment from 'moment'; import app from '../src/index'; import { User, Meal } from '../src/models'; const { assert } = chai; chai.use(chaiHttp); chai.should(); const userData = { name: 'user name', email: 'user1@email.com', phone_number: '098192393', address: 'address', password: 'password', role_id: 1, }; const catererData = { name: 'user name', email: 'caterer@email.com', phone_number: '098192393', address: 'address', password: 'password', role_id: 2, }; before((done) => { User.create(catererData) .then(() => User.create(userData)) .then(() => { done(); }); }); describe('Welcome', () => { it('should return a welcome message', (done) => { chai.request(app) .get('/') .end((err, res) => { assert.equal(res.body.message, 'Welcome to mBookr API'); done(); }); }); }); describe('Not Found', () => { it('should return error message for non-existent endpoint', (done) => { chai.request(app) .get('/random') .end((err, res) => { res.should.have.status(404); assert.equal(res.body.error.message, 'Not found'); done(); }); }); }); describe('Internal server error', () => { it('should return error message', (done) => { chai.request(app) .get('/api/v1/meals/error') .end((err, res) => { res.should.have.status(500); done(); }); }); }); describe('SignUp', () => { it('User should be able to signup', (done) => { chai.request(app) .post('/api/v1/users/signup') .send({ name: 'user name', email: 'user@email.com', phone_number: '098192393', address: 'address', password: 'password', role_id: 2, }) .end((err, res) => { res.should.have.status(201); assert.equal(res.body.message, 'User created successfully.'); done(); }); }); }); describe('Login', () => { it('User should be able to login', (done) => { chai.request(app) .post('/api/v1/users/login') .send({ email: 'user@email.com', password: 'password', }) .end((err, res) => { res.should.have.status(200); assert.equal(res.body.message, 'Login successful'); done(); }); }); }); describe('Meals', () => { describe('GET /meals', () => { it('should get all meal options', (done) => { User.findOne({ where: { email: catererData.email } }) .then((caterer) => { const { user_id, email, role_id } = caterer; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .get('/api/v1/meals') .set('Authorization', `Bearer ${token}`) .end((err, res) => { res.should.have.status(200); assert.equal(res.body.message, 'Success'); }); done(); }) .catch(err => console.log(err.message)); }); }); describe('POST /meals', () => { it('should add a meal option', (done) => { User.findOne({ where: { email: catererData.email } }) .then((caterer) => { const { user_id, email, role_id } = caterer; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .post('/api/v1/meals') .set('Authorization', `Bearer ${token}`) .field('name', 'Test Meal') .field('price', '500') .attach('image', '../UI/img/food-img.jpg', 'test.png') .end((err, res) => { res.should.have.status(201); assert.equal(res.body.message, 'Meal created successfully.'); }); done(); }) .catch(err => console.log(err.message)); }); }); describe('PUT /meals', () => { it('should edit a meal option', (done) => { Meal.create({ name: 'Fake Meal', price: 1000, image: '../UI/img/food-img.jpg', }) .then((meal) => { User.findOne({ where: { email: catererData.email } }) .then((caterer) => { const { user_id, email, role_id } = caterer; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .put(`/api/v1/meals/${meal.id}`) .set('Authorization', `Bearer ${token}`) .field('name', 'Test Meal') .field('price', '500') .attach('image', '../UI/img/food-img.jpg', 'test.png') .end((err, res) => { res.should.have.status(200); assert.equal(res.body.message, 'Meal successfully updated.'); }); done(); }) .catch(err => console.log(err.message)); }); }); }); describe('PUT /meals', () => { it('should throw error for wrong meal id', (done) => { User.findOne({ where: { email: catererData.email } }) .then((caterer) => { const { user_id, email, role_id } = caterer; const mealId = -1; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .put(`/api/v1/meals/${mealId}`) .set('Authorization', `Bearer ${token}`) .field('name', 'Test Meal') .field('price', '500') .attach('image', '../UI/img/food-img.jpg', 'test.png') .end((err, res) => { res.should.have.status(404); assert.equal(res.body.message, 'Meal Not Found'); }); done(); }) .catch(err => console.log(err.message)); }); }); describe('DELETE /meals', () => { it('should delete a meal option', (done) => { Meal.create({ name: 'Fake Meal', price: 1000, image: '../UI/img/food-img.jpg', }) .then((meal) => { User.findOne({ where: { email: catererData.email } }) .then((caterer) => { const { user_id, email, role_id } = caterer; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .delete(`/api/v1/meals/${meal.id}`) .set('Authorization', `Bearer ${token}`) .end((err, res) => { res.should.have.status(200); assert.equal(res.body.message, 'Meal deleted successfully.'); }); done(); }) .catch(err => console.log(err.message)); }); }); }); // describe('DELETE /meals', () => { // it('should throw error for wrong meal id', (done) => { // User.findOne({ where: { email: catererData.email } }) // .then((caterer) => { // const { user_id, email, role_id } = caterer; // const mealId = -1; // const token = jwt.sign( // { // email, // user_id, // role_id, // }, // 'secret', // { // expiresIn: 86400, // }, // ); // chai.request(app) // .delete(`/api/v1/meals/${mealId}`) // .set('Authorization', `Bearer ${token}`) // .end((err, res) => { // res.should.have.status(404); // assert.equal(res.body.message, 'Meal Not Found'); // }); // done(); // }) // .catch(err => console.log(err.message)); // }); // }); }); describe('Menu', () => { describe('GET /menu', () => { it('should get menu for the day', (done) => { chai.request(app) .get('/api/v1/menu') .end((err, res) => { res.should.have.status(200); assert.equal(res.body.message, 'Success'); done(); }); }); }); describe('POST /menu', () => { it('should add meal to menu for the day', (done) => { Meal.create({ name: 'Fake Meal', price: 1000, image: '../UI/img/food-img.jpg', }) .then((meal) => { User.findOne({ where: { email: catererData.email } }) .then((caterer) => { const { user_id, email, role_id } = caterer; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .post('/api/v1/menu') .set('Authorization', `Bearer ${token}`) .send({ meal_id: meal.id, }) .end((err, res) => { res.should.have.status(201); assert.equal(res.body.message, 'Meal added successfully.'); }); }) .catch(err => console.log(err.message)); }); done(); }); }); describe('DELETE /menu', () => { it('should delete a meal from menu for the day', (done) => { Meal.create({ name: 'Fake Meal', price: 1000, image: '../UI/img/food-img.jpg', }) .then((meal) => { const menu_id = parseInt(moment().format('DDMMYYYY'), Number); User.findOne({ where: { email: catererData.email } }) .then((caterer) => { const { user_id, email, role_id } = caterer; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .delete('/api/v1/menu') .set('Authorization', `Bearer ${token}`) .send({ meal_id: meal.id, menu_id, }) .end((err, res) => { res.should.have.status(200); assert.equal(res.body.message, 'Meal deleted from menu successfully.'); }); }) .catch(err => console.log(err.message)); }); done(); }); }); }); describe('Orders', () => { describe('GET /orders', () => { it('should get all orders', (done) => { User.findOne({ where: { email: catererData.email } }) .then((caterer) => { const { user_id, email, role_id } = caterer; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .get('/api/v1/orders') .set('Authorization', `Bearer ${token}`) .end((err, res) => { res.should.have.status(200); assert.equal(res.body.message, 'Success'); done(); }); }) .catch(err => console.log(err.message)); }); }); describe('POST /orders', () => { it('should get add an order to orders', (done) => { User.findOne({ where: { email: userData.email } }) .then((user) => { const { id, user_id, email, role_id, name, phone_number, address, } = user; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .post('/api/v1/orders') .set('Authorization', `Bearer ${token}`) .send({ user_id: id, user_name: name, user_phone: phone_number, user_address: address, meals: [ { meal_id: 5, meal_name: 'yam', meal_price: 200, meal_image: 'test-img.jpg', quantity: 2, meal_total: 400, }, ], order_total: 600, }) .end((err, res) => { res.should.have.status(201); assert.equal(res.body.message, 'Order created successfully.'); done(); }); }) .catch(err => console.log(err.message)); }); }); describe('PUT /orders', () => { it('should edit an order', (done) => { User.findOne({ where: { email: catererData.email } }) .then((user) => { const { user_id, email, role_id, } = user; const token = jwt.sign( { email, user_id, role_id, }, 'secret', { expiresIn: 86400, }, ); chai.request(app) .put('/api/v1/orders/1') .set('Authorization', `Bearer ${token}`) .send({ user_name: 'name', }) .end((err, res) => { res.should.have.status(200); assert.equal(res.body.message, 'Order updated.'); done(); }); }) .catch(err => console.log(err.message)); }); }); }); after((done) => { User.destroy({ where: { email: ['user@email.com', userData.email, catererData.email] } }) .then(() => { done(); }); });
let players = []; function initPlayers() { let plr1 = { x: 1, y: 2, movement: [38, 39, 40, 37, 32], colour: "darkblue" } let plr2 = { x: 11, y: 11, movement: [87, 68, 83, 65, 13], colour: color(255, 20, 20) } players.push(new Player(plr1.x, plr1.y, plr1.movement,plr1.colour)); players.push(new Player(plr2.x, plr2.y, plr2.movement, plr2.colour)); } class Player { constructor(x, y, movement, colour = color(50, 50, 255)) { this.sx = x; this.sy = y; this.x = x; this.y = y; this.color = colour; this.mov = movement; this.speed = 0.03; this.lastdirection = 1234; } show() { fill(this.color); ellipse(this.sx * placeSize + placeSize * 0.5, this.sy * placeSize + placeSize * 0.5, placeSize * 0.7, placeSize * 0.7) } move() { if (keyIsDown(this.mov[0])) { if(this.sy + 0.1 >= this.y){ this.sy -= this.speed; } else if (moveAllowed(this.x, this.y - 1, -1)) { this.sy -= this.speed; } } else if (keyIsDown(this.mov[2])) { if (this.sy - 0.1 <= this.y) { this.sy += this.speed; } else if (moveAllowed(this.x, this.y + 1,+ 1)){ this.sy += this.speed; } } else if (keyIsDown(this.mov[1])) { if (this.sx - 0.1 <= this.x) { this.sx += this.speed; } else if (moveAllowed(this.x + 1, this.y,1)){ this.sx += this.speed; } } else if (keyIsDown(this.mov[3])) { if (this.sx + 0.1 >= this.x) { this.sx -= this.speed; } else if (moveAllowed(this.x - 1, this.y,3)){ this.sx -= this.speed; } } this.x = round(this.sx); this.y = round(this.sy); if (keyIsDown(this.mov[4])) { if (placeAllowed(this.x, this.y)) placeBomb(this.x, this.y, 200); } } } function showplayers() { for (let i = 0; i < players.length; i++) { let plr = players[i]; plr.move(); plr.show(); let live = true; for (let o = 0; o < explosions.length; o++) { let par = explosions[o].particles; for (let p = 0; p < explosions[o].particles.length; p++) { if (plr.y === par[p].x && plr.x === par[p].y) { players.splice(i, 1); break; } } } } } function PlayerIsntHere(x, y) { let notHere = 0; for (let i = 0; i < players.length; i++) { let plr = players[i] if (plr.x === x && plr.y === y) notHere += 1; } if (notHere < 2) return true; } //I have to create placeAllowed function function moveAllowed(x, y, di) { if (gameboard[y][x] === 0 && BombIsntHere(x, y) && PlayerIsntHere(x, y)) return true; } function placeAllowed(x, y) { let nobomb = true for (let i = 0; i < Bombs.length; i++) { if (Bombs[i].x === x && Bombs[i].y === y) nobomb = false; } if (nobomb && gameboard[y][x] === 0 && BombIsntHere(x, y)) return true; } function checkifcan(){ }
// Title: SPUtilities // Version: 0.1 // Description: jQuery plugin for SharePoint customization. // Compatibility: jQuery 1.10.2 // Author: Christopher H. Lincoln (function($){ //////////////////////////////////////////////////////////////////////////////////////////////////// // SPUtils namespace $.SPUtils = function(options) { // initialize options options = $.extend({}, $.fn.SPUtils.defaultOptions, options); // check SharePoint version // check LCID }; // defaultOptions property $.SPUtils.defaultOptions = { 'Debugging': false, // enables custom debugging console 'LCID': 1033, // locality; English - United States 'SPVersion': 0, // environment major version; [12, 14, 15] 'Strict': false // enables graceful exception handling }; // SPUtils namespace //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Form class $.SPUtils.form = []; // persistent form collection $.SPUtils.Form = function(options){ // initialize options options = $.extend({}, $.SPUtils.Form.defaultOptions, options); // initialize form object if($.SPUtils.form.length === 0){ $.SPUtils.form = _GetListForm(); } // initialize row objects if($.SPUtils.Form.rows.length === 0){ } return $.SPUtils.form; }; $.SPUtils.Form.defaultOptions = { // Name: defaultOptions // Type: property // Description: Specifies default parameter values 'Type': '', // ["Display", "Edit", "New"] 'Dialog': null // [true, false] }; $.SPUtils.Form.Get = function(index){ // Name: Get // Type: method // Description: Retrieves the HTML DOM element of the form // Parameters: index (optional) // Returns: Form element (HTML DOM element) var index = (typeof index === 'undefined') ? 0 : parseInt(index); return $.SPUtils.form[index]; }; $.SPUtils.Form.rows = []; // persistent row collection $.SPUtils.Form.Rows = function(options){ // initialize options options = $.extend({}, $.SPUtils.Form.Rows.defaultOptions, options); // initialize rows (redundant) var rows = $.SPUtils.Form.rows; if(rows.length === 0){ $.SPUtils.Form.rows = _GetRows($.SPUtils.form); rows = $.SPUtils.Form.rows; } // handle null parameter if(options === $.SPUtils.Form.Rows.defaultOptions){ // get all rows } // otherwise else{ // get specified row } return $.SPUtils.Form.rows; }; // defaultOptions property $.SPUtils.Form.Rows.defaultOptions = { 'Index': -1, // [0, n) 'Required': false, // [true, false] 'Selector': 'Display', // ["Display", "Internal", "Index"] 'Name': '' }; // Form class //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Row class $.SPUtils.Row = function(options){ // initialize options options = $.extend({}, $.SPUtils.Row.defaultOptions, options); }; $.SPUtils.Row.defaultOptions = { // Name: defaultOptions // Type: property // Description: Specifies default parameter values 'DisplayName': '', 'Index': -1, // [-1, n) 'InternalName': '', 'Required': null, // [true, false] 'Type': '' // ["Date/Time", "Multiple Lines of Text", "Single Line of Text", etc.] }; $.SPUtils.Row.Get = function(index){ // Name: Get // Type: method // Description: Retrieves the HTML DOM element of the specified row in a form // Parameters: index (optional) // Returns: Console element (HTML DOM element) }; $.SPUtils.Row.Hide = function(){ // Name: Hide // Type: method // Description: Hides the specified row in a form // Parameters: none // Returns: Row object (object) }; $.SPUtils.Row.Show = function(){ // Name: Show // Type: method // Description: Displays the specified row in a form // Parameters: none // Returns: Row object (object) }; // Row class //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Description class $.SPUtils.Description = function(options){ // initialize options options = $.extend({}, $.SPUtils.Description.defaultOptions, options); }; $.SPUtils.Description.defaultOptions = { // Name: defaultOptions // Type: property // Description: Specifies default parameter values 'Text': null, // string 'Position': 'Default', // ["Default", "Label"] 'Visible': null, // [true, false] }; // Description class //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Field class $.SPUtils.Field = function(options){ // initialize options options = $.extend({}, $.SPUtils.Row.defaultOptions, options); }; $.SPUtils.Field.defaultOptions = { // Name: defaultOptions // Type: property // Description: Specifies default parameter values 'DisplayName': '', 'Index': -1, // [-1, n) 'InternalName': '', 'Required': null, // [true, false] 'Type': '' // ["Date/Time", "Multiple Lines of Text", "Single Line of Text", etc.] }; // Field class //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Console class $.SPUtils.console = []; // persistent console collection $.SPUtils.Console = function(options){ // initialize options options = $.extend({}, $.SPUtils.Console.defaultOptions, options); // initialize console if($.SPUtils.console.length === 0){ $('body').append('<DIV ID="SPUtils-Console"><DIV class="sputils-header">SPUtilities Console</DIV><OL class="sputils-messages"></OL></DIV>'); $.SPUtils.console = $('$SPUtils-Console').get(0); } return $.SPUtils.console; }; // Name: Collection // Type: property // Description: Persistent collection of console objects $.SPUtils.Console.collection = []; // Name: Default Options // Type: property // Description: Specifies default parameter values $.SPUtils.Console.defaultOptions = { }; // Name: Add // Type: method // Description: Creates a new entry in the custom debugging console // Parameters: level (_Exception.level object), message (string) // Returns: Console element (HTML DOM element) $.SPUtils.Console.Add = function(level, message){ // add message return consoleCollection; }; $.SPUtils.Console.Get = function(index){ // Name: Get // Type: method // Description: Retrieves the HTML DOM element of the custom debugging console // Parameters: index (optional) // Returns: Console element (HTML DOM element) var index = (typeof index === 'undefined') ? 0 : parseInt(index); return $.SPUtils.console[index]; }; $.SPUtils.Console.Hide = function(){ // Name: Hide // Type: method // Description: Hides the custom debugging console // Parameters: none // Returns: Console collection (array) var consoleCollection = $.SPUtils.console; $(consoleCollection).removeClass('active'); return consoleCollection; }; $.SPUtils.Console.Show = function(){ // Name: Show // Type: method // Description: Displays the custom debugging console // Parameters: none // Returns: Console collection (array) var consoleCollection = $.SPUtils.console; $(consoleCollection).addClass('active'); return consoleCollection; }; // Console class //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // private function _GetListForm(){ // Description: Retrieves the top-level container element of a List Form Web Part // Parameters: none // Returns: Collection of form objects ($.SPUtils.form) try{ var results = []; results.push($('#listFormToolBarTop').parents('div:first')); return results; } catch(ex){ throw{ 'name': _Exception.name, 'level': _Exception.level[0], 'message': 'A List Form Web Part was not retrieved successfully. (1.100)' } } } function _GetListFormRow(rowCollection, target, targetFormat){ // Description: Retrieves the top-level container element of a row in a List Form Web Part // Parameters: Collection of row objects ($.SPUtils.Form.rows) // Returns: Row object ($.SPUtils.Row) try{ } catch(ex){ throw{ 'name': _Exception.name, 'level': _Exception.level[0], 'message': 'A row of a List Form Web Part row collection was not retireved successfully. (1.200)' } } } function _GetListFormRows(formCollection){ // Description: Retrieves top-level container elements of rows in a List Form Web Part // Parameters: Collection of form objects ($.SPUtils.form) try{ } catch(ex){ throw{ 'name': _Exception.name, 'level': _Exception.level[0], 'message': 'A row collection of a List Form Web Part was not retrieved successfully. (1.300)' } } } function _GetListFormRowField(rowElement){ // Description: Retrieves the top-level container element of a field (i.e. control) for a row in a List Form Web Part // Parameters: Row object ($.SPUtils.Row) // Returns: Field object ($.SPUtils.Field) try{ } catch(ex){ throw{ 'name': _Exception.name, 'level': _Exception.level[1], 'message': 'A description of a row in a List Form Web Part was not retrieved successfully. (1.400)' } } } function _GetListFormRowDescription(rowElement){ // Description: Retrieves the top-level container element of a description for a row in a List Form Web Part // Parameters: Row object ($.SPUtils.Row) // Returns: Description object ($.SPUtils.Description) try{ } catch(ex){ throw{ 'name': _Exception.name, 'level': _Exception.level[1], 'message': 'A description of a row in a List Form Web Part was not retrieved successfully. (1.400)' } } } var _Exception = function(){ // Description: Stores properties for custom exceptions this.name = 'SPUtils Plugin Error'; this.level = ['Critical', 'Warning', 'Information']; }; // private //////////////////////////////////////////////////////////////////////////////////////////////////// $.fn.SPUtils = function(options){ return this.each(function(){ (new $.SPutils($(this), options)); }); } })(jQuery)
/* * Copyright (C) 2021 Radix IoT LLC. All rights reserved. */ import pageTemplate from './adminHomePage.html'; import './adminHomePage.css'; import sqlSvg from './svgs/sql-icon.svg' import noSqlSvg from './svgs/nosql-icon.svg' import diskspaceSvg from './svgs/diskspace-icon.svg' import ramSvg from './svgs/ram-icon.svg' import cpuloadSvg from './svgs/cpuload-icon.svg' class PageController { static get $$ngIsClass() { return true; } static get $inject() { return ['$q','$mdMedia','maSystemStatus', 'maUiDateBar', 'maUiPages', '$injector', 'maUiMenu', 'maUser', 'maEvents', 'maUiServerInfo']; } constructor($q, $mdMedia, systemStatus, maUiDateBar, maUiPages, $injector, maUiMenu, maUser, maEvents, maUiServerInfo) { this.systemStatus = systemStatus this.maUiDateBar = maUiDateBar this.maUiPages = maUiPages; this.$injector = $injector; this.maUiMenu = maUiMenu; this.maUser = maUser; this.maEvents = maEvents this.maUiServerInfo = maUiServerInfo this.$q = $q; this.$mdMedia = $mdMedia; this.sqlSvg = sqlSvg this.noSqlSvg = noSqlSvg this.diskspaceSvg = diskspaceSvg this.ramSvg = ramSvg this.cpuloadSvg = cpuloadSvg } $onInit() { this.eventCounts = {} this.maUiPages.getPages().then(store => { this.pageCount = store.jsonData.pages.length; }); this.hasDashboardDesigner = !!this.$injector.modules.maDashboardDesigner; this.maUiMenu.getMenu().then(menu => { this.utilityMenuItems = menu.filter(item => item.showInUtilities); }); this.systemStatus.getInternalMetrics().then((response) => { this.internalMetrics = response.data; }); this.getCounts() } getCounts() { const promises = [ this.getCount('DATA_POINT'), this.getCount('SYSTEM'), this.getCount('ADVANCED_SCHEDULE') ]; this.$q.all(promises).then(([count1, count2, count3]) => { this.eventCounts.dataPoint = count1 this.eventCounts.system = count2 this.eventCounts.advancedSchedule = count3 }); } getCount(eventType) { return this.maEvents.buildQuery() .eq('eventType', eventType) .eq('active', true) .limit(0) .query().then(result => { return result.$total; }); } } export default { controller: PageController, template: pageTemplate };
//app.js var tonk0006_giftr = { loadRequirements: 0, personName: '', occasionName: '', person_name: '', init: function () { document.addEventListener('deviceready', this.onDeviceReady); document.addEventListener('DOMContentLoaded', this.onDomReady); }, onDeviceReady: function () { //alert("Device is ready"); tonk0006_giftr.loadRequirements++; if (tonk0006_giftr.loadRequirements === 2) { tonk0006_giftr.start(); } }, onDomReady: function () { //alert("DOM is ready"); tonk0006_giftr.loadRequirements++; if (tonk0006_giftr.loadRequirements === 2) { tonk0006_giftr.start(); } }, start: function () { //connect to database //build the lists for the main pages based on data //add button and navigation listeners tonk0006_giftr.dbConnect(); tonk0006_giftr.showPeopleList(); var addButtons = document.querySelectorAll('.btnAdd'); addButtons[0].addEventListener('click', tonk0006_giftr.addPerson); addButtons[1].addEventListener('click', tonk0006_giftr.addOccasion); addButtons[2].addEventListener('click', tonk0006_giftr.addGiftForPerson); addButtons[3].addEventListener('click', tonk0006_giftr.addGiftForOccasion); var cancelButtons = document.querySelectorAll('.btnCancel'); cancelButtons[0].addEventListener('click', tonk0006_giftr.cancelModal); cancelButtons[1].addEventListener('click', tonk0006_giftr.cancelModal); cancelButtons[2].addEventListener('click', tonk0006_giftr.cancelModal); cancelButtons[3].addEventListener('click', tonk0006_giftr.cancelModal); var saveButtons = document.querySelectorAll('.btnSave'); saveButtons[0].addEventListener('click', tonk0006_giftr.savePerson); saveButtons[1].addEventListener('click', tonk0006_giftr.saveOccasion); saveButtons[2].addEventListener('click', tonk0006_giftr.saveGiftForPerson); saveButtons[3].addEventListener('click', tonk0006_giftr.saveGiftForOccasion); document.querySelector('header h1').addEventListener('click', tonk0006_giftr.showPeopleList); var list = document.querySelectorAll('[data-role="listview"]'); var hm1 = new Hammer.Manager(list[0]); var hm2 = new Hammer.Manager(list[1]); var hm3 = new Hammer.Manager(list[2]); var hm4 = new Hammer.Manager(list[3]); var singleTap1 = new Hammer.Tap({ event: 'singletap' }); var doubleTap1 = new Hammer.Tap({ event: 'doubletap', taps: 2, threshold: 10, posThreshold: 40 }); var singleTap2 = new Hammer.Tap({ event: 'singletap' }); var doubleTap2 = new Hammer.Tap({ event: 'doubletap', taps: 2, threshold: 10, posThreshold: 40 }); var singleTap3 = new Hammer.Tap({ event: 'singletap' }); var doubleTap3 = new Hammer.Tap({ event: 'doubletap', taps: 2, threshold: 10, posThreshold: 40 }); var singleTap4 = new Hammer.Tap({ event: 'singletap' }); var doubleTap4 = new Hammer.Tap({ event: 'doubletap', taps: 2, threshold: 10, posThreshold: 40 }); hm1.add([doubleTap1, singleTap1]); hm2.add([doubleTap2, singleTap2]); hm3.add([doubleTap3, singleTap3]); hm4.add([doubleTap4, singleTap4]); doubleTap1.recognizeWith(singleTap1); doubleTap2.recognizeWith(singleTap2); doubleTap3.recognizeWith(singleTap3); doubleTap4.recognizeWith(singleTap4); doubleTap1.requireFailure(singleTap1); doubleTap2.requireFailure(singleTap2); doubleTap3.requireFailure(singleTap3); doubleTap4.requireFailure(singleTap4); hm1.on('singletap', tonk0006_giftr.showGiftsForPerson); hm2.on('singletap', tonk0006_giftr.showGiftsForOccasion); hm1.on('doubletap', tonk0006_giftr.deleteListItem); hm2.on('doubletap', tonk0006_giftr.deleteListItem); hm3.on('doubletap', tonk0006_giftr.deleteListItem); hm4.on('doubletap', tonk0006_giftr.deleteListItem); var pages = document.querySelectorAll('[data-role=page]'); var goToPeople = new Hammer(pages[1]); goToPeople.on('swiperight', tonk0006_giftr.showPeopleList); var goToOccassions = new Hammer(pages[0]); goToOccassions.on('swipeleft', tonk0006_giftr.showOccasionList); }, dbConnect: function () { console.log("Connecting to database..."); tonk0006_giftr.db = openDatabase('giftrDB', '', 'Giftr Database', 1024 * 1024); if (tonk0006_giftr.db.version == "") { console.log('First time running database... Creating new tables.'); tonk0006_giftr.db.changeVersion("", "1.0", function (trans) { trans.executeSql("CREATE TABLE IF NOT EXISTS people(person_id INTEGER PRIMARY KEY AUTOINCREMENT, person_name TEXT)", [], function (tx, rs) { console.log("Table people created."); }, function (tx, err) { console.error(err.message); }); trans.executeSql("CREATE TABLE IF NOT EXISTS occasions(occ_id INTEGER PRIMARY KEY AUTOINCREMENT, occ_name TEXT)", [], function (tx, rs) { console.log("Table occasions created."); }, function (tx, err) { console.error(err.message); }); trans.executeSql("CREATE TABLE IF NOT EXISTS gifts(gift_id INTEGER PRIMARY KEY AUTOINCREMENT, person_id INTEGER, occ_id INTEGER, gift_idea TEXT, purchased BOOLEAN)", [], function (tx, rs) { console.log("Table gifts created."); }, function (tx, err) { console.error(err.message); }); }, function (err) { console.error(err.message); }, function () { tonk0006_giftr.showPeopleList(); }); } else { console.log("Successfully connected to database!"); tonk0006_giftr.showPeopleList(); } }, showPeopleList: function () { var pages = document.querySelectorAll('[data-role=page]'); pages[0].style.display = 'block'; pages[1].style.display = 'none'; pages[2].style.display = 'none'; pages[3].style.display = 'none'; }, showOccasionList: function () { var pages = document.querySelectorAll('[data-role=page]'); pages[0].style.display = 'none'; pages[1].style.display = 'block'; pages[2].style.display = 'none'; pages[3].style.display = 'none'; }, showGiftsForPerson: function (ev) { var pages = document.querySelectorAll('[data-role=page]'); pages[0].style.display = 'none'; pages[2].style.display = 'block'; var name = ev.target.innerHTML; console.log('Displayed gift ideas page for ' + name); var paras = document.querySelectorAll('.details'); if (paras[2].innerHTML !== '') paras[2].innerHTML = 'Here are all the gift ideas for <strong>' + name + '</strong> for all occasions.'; personName = name; }, showGiftsForOccasion: function (ev) { var pages = document.querySelectorAll('[data-role=page]'); pages[1].style.display = 'none'; pages[3].style.display = 'block'; var occasion = ev.target.innerHTML; console.log('Displayed gift ideas page for ' + occasion); var paras = document.querySelectorAll('.details'); if (paras[3].innerHTML !== '') paras[3].innerHTML = 'Here are all the gift ideas for <strong>' + occasion + '</strong> for all people.'; occasionName = occasion; }, addPerson: function () { console.log('Person modal window opened'); document.querySelector('[data-role=modal]#add-person').style.display = 'block'; document.querySelector('[data-role=overlay]').style.display = 'block'; var input = document.querySelector('#new-per'); input.value = ''; input.focus(); input.addEventListener('keypress', function (ev) { ev.stopImmediatePropagation(); if (ev.keyCode === 13) { ev.preventDefault(); tonk0006_giftr.savePerson(); input.blur(); } }); }, addOccasion: function () { console.log('Occasion modal window opened'); document.querySelector('[data-role=modal]#add-occasion').style.display = 'block'; document.querySelector('[data-role=overlay]').style.display = 'block'; var input = document.querySelector('#new-occ'); input.value = ''; input.focus(); input.addEventListener('keypress', function (ev) { ev.stopImmediatePropagation(); if (ev.keyCode === 13) { ev.preventDefault(); tonk0006_giftr.saveOccasion(); input.blur(); } }); }, addGiftForPerson: function () { console.log('Gift for person modal window opened'); document.querySelector('[data-role=modal]#add-gift-per').style.display = 'block'; document.querySelector('[data-role=overlay]').style.display = 'block'; var nameArray = document.querySelectorAll('li'); console.log(nameArray); var headings = document.querySelectorAll('h3'); headings[2].innerHTML = 'New gift for <strong>' + personName + '</strong>.'; var inputs = document.querySelectorAll('#new-idea'); var input = inputs[0]; input.value = ''; // input.focus(); input.addEventListener('keypress', function (ev) { ev.stopImmediatePropagation(); if (ev.keyCode === 13) { ev.preventDefault(); tonk0006_giftr.saveGiftForPerson(); input.blur(); } }); }, addGiftForOccasion: function () { console.log('Gift for occasion modal window opened'); document.querySelector('[data-role=modal]#add-gift-occ').style.display = 'block'; document.querySelector('[data-role=overlay]').style.display = 'block'; var headings = document.querySelectorAll('h3'); headings[3].innerHTML = 'New gift for <strong>' + occasionName + '</strong>.'; var inputs = document.querySelectorAll('#new-idea'); var input = inputs[1]; input.value = ''; // input.focus(); input.addEventListener('keypress', function (ev) { ev.stopImmediatePropagation(); if (ev.keyCode === 13) { ev.preventDefault(); tonk0006_giftr.saveGiftForOccasion(); input.blur(); } }); }, savePerson: function () { var ul = document.querySelectorAll('[data-role="listview"]'); var li = document.createElement('li'); var text = document.querySelector('#new-per').value; li.innerHTML = text; // li.setAttribute('data-ref', text); li.setAttribute('id', text); if (text) ul[0].appendChild(li); tonk0006_giftr.db.transaction(function (trans) { trans.executeSql("INSERT INTO people(person_name) VALUES('" + text + "')", [], function (tx, rs) { console.log(text + " " + "has been added to the database."); text = null; tonk0006_giftr.cancelModal(); }, function (tx, err) { console.error(err.message); }); }); }, saveOccasion: function () { var ul = document.querySelectorAll('[data-role="listview"]'); var li = document.createElement('li'); var text = document.querySelector('#new-occ').value; li.innerHTML = text; // li.setAttribute('data-ref', text); li.setAttribute('id', text); if (text) ul[1].appendChild(li); tonk0006_giftr.db.transaction(function (trans) { trans.executeSql("INSERT INTO occasions(occ_name) VALUES('" + text + "')", [], function (tx, rs) { console.log(text + " " + "has been added to the database."); tonk0006_giftr.cancelModal(); }, function (tx, err) { console.error(err.message); }); }); }, // NEEDS MORE WORK saveGiftForPerson: function () { var ul = document.querySelectorAll('[data-role="listview"]'); var li = document.createElement('li'); var ideas = document.querySelectorAll('#new-idea'); var text = ideas[0].value; //var textpair = (text + ' for ' + occasionName); li.innerHTML = text; li.setAttribute('id', text); if (text) ul[2].appendChild(li); var gift_idea = text; var occ_list = document.querySelector("#add-gift-per #list-per"); var occ_id = occ_list.options[occ_list.selectedIndex].value; tonk0006_giftr.db.transaction(function (trans) { trans.executeSql("INSERT INTO gifts(person_id, occ_id, gift_idea, purchased) VALUES('" + person_name + "', '" + occ_id + "', '" + gift_idea + "', 0)", [], function (tx, rs) { console.log("Gift + " + gift_idea + " has been added to the database."); tonk0006_giftr.cancelModal(); }, function (tx, err) { console.error(err.message); }); }); }, // NEEDS MORE WORK - JUST STARTED IT saveGiftForOccasion: function () { var ul = document.querySelectorAll('[data-role="listview"]'); var li = document.createElement('li'); var ideas = document.querySelectorAll('#new-idea'); var text = ideas[1].value; //var textpair = (text + ' for ' + personName); li.innerHTML = text; li.setAttribute('id', text); if (text) ul[3].appendChild(li); tonk0006_giftr.cancelModal(); var gift_idea = text; var occ_list = document.querySelector("#add-gift-per #list-occ"); var occ_id = occ_list.options[occ_list.selectedIndex].value; var person_name = occ_list.options[occ_list.selectedIndex].innerHTML; }, deleteListItem: function (ev) { console.log('Double-tap event occured'); var item = ev.target.innerHTML; var li = document.getElementById(item); li.parentNode.removeChild(li); console.log('Item ' + item + ' was deleted from the screen'); tonk0006_giftr.db.transaction(function (tr) { tr.executeSql("DELETE FROM people WHERE person_name = '" + item + "'", [], function (tx, rs) { console.log('Item ' + item + ' has been deleted from the database.') // tonk0006_giftr.cancelModal(); }, function (tx, err) { console.info(err.message); }); }); }, cancelModal: function () { var modals = document.querySelectorAll('[data-role=modal]'); modals[0].style.display = 'none'; modals[1].style.display = 'none'; modals[2].style.display = 'none'; modals[3].style.display = 'none'; document.querySelector('[data-role=overlay]').style.display = 'none'; } } tonk0006_giftr.init();
import React, { useEffect, useState } from "react"; import { Redirect } from "react-router-dom"; import { Normal } from "../Pages/Dashboard/Dashboard"; import getTokenDetails from "../lib/jwt"; /**const PrivateRoute = () => { const token = localStorage.getItem("UserToken"); const [tokenIsValid, settokenIsValid] = useState(true); const verifyToken = async () => { const result = await getTokenDetails(token); settokenIsValid(result); } if (token && tokenIsValid) { return (<Normal />); } // Redirect to homepage return (<Redirect to={{ pathname: "/" }} />); };*/ const PrivateRoute = () => { const token = localStorage.getItem("UserToken"); if (token) { return (<Normal />); } // Redirect to homepage return (<Redirect to={{ pathname: "/login" }} />); }; export default PrivateRoute;
jQuery(document).ready(function() { var sortRoute = $("#api-routes").attr("data-sort-route"); //--------------------------------------------- // Menu items //--------------------------------------------- // Store the collection tag var collectionSelector = [".menu-items-collection"]; var $collectionHolder; var $collection; collectionSelector.forEach(function(selector){ // Get the tag that holds the collection and the add item button $collectionHolder = $(selector); // count the collection items we have on load $collectionHolder.data('index', $collectionHolder.find('.collection-row').length); // Add new collection item $(document).on('click', selector+' .add-item', function(e) { e.preventDefault(); $collection = $(this).parents(".repeater-container"); // Get the data-prototype var prototype = $collection.data('prototype'); // get the new index var index = $collection.data('index'); // Update the name and id var newForm = prototype; newForm = newForm.replace(/__name__/g, index); // Update the index and add the form $collection.data('index', index + 1); var $newFormLi = $(newForm); $collection.find(".add-item").parents("li").before($newFormLi.hide().fadeIn(300)); $('select:not(.classic)').selectpicker({}); }); // Remove an item from the collection $(document).on('click', selector+' .delete-item', function(e) { e.preventDefault(); $(this).parents(".collection-row").fadeOut(300, function() { $(this).remove(); }); }); }); var el = document.getElementById('menu-items-collection'); var sortable = Sortable.create($(".menu-items-collection")[0], { handle: '.drag-handle', animation: 150, onSort: function (evt) { updateItemsPositions(); } }); function updateItemsPositions(){ $(".menu-item").each(function(index){ $(this).find(".position input").val(index); }); } });
import React from 'react'; import ReactHowler from 'react-howler'; import { useSfx } from 'contexts/sfxContext'; import menuMp3 from 'assets/sounds/menu-toggle.mp3'; const MenuSounds = () => { const { menuSounds } = useSfx(); return ( <> {menuSounds.map(() => ( <ReactHowler src={menuMp3} volume={0.7} key={`menu-sound-${Math.random()}`} /> ))} </> ); }; export default MenuSounds;
"use strict"; function isVehicleDriver(player) { if (!player.vehicle || player.seat != -1) { return false; } return true; } exports.isVehicleDriver = isVehicleDriver;
const solve = (data, n) => { const nums = data.split(",").map(Number); let last = nums.pop(); const used = new Map(nums.map((x, i) => [x, i])); for (let i = nums.length + 1; i < n; i++) { const lastIndex = used.get(last); used.set(last, i - 1); last = lastIndex !== undefined ? i - lastIndex - 1 : 0; } return last; }; module.exports = { part1: (data) => solve(data, 2020), part2: (data) => solve(data, 30000000), };
export default function todos(state = ['How are you?\n'], action) { switch (action.type) { case 'ADD_TODO': return state.concat([action.payload]); default: return state; } }
/* Write a program that deletes a given element e from the array a. Input: e = 2, a = [4, 6, 2, 8, 2, 2] Output array: [4, 6, 8] */ var deleteElement = function (a){ var e = 2; var newArray = []; for(var i = 0; i < a.length; i++){ if(a[i] !== e){ newArray[newArray.length] = a[i]; } } return newArray; } console.log(deleteElement([4, 6, 2, 8, 2, 2]));
import React from 'react'; import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; //importing CSS file import './QuestionsModal.css'; class QuestionsModal extends React.Component { constructor(props) { super(props); console.log(this.props); } render() { console.log(this.props); return ( <div> <Button color="danger" onClick={this.props.toggle}>{this.props.buttonLabel}</Button> <Modal isOpen={this.props.modal} toggle={this.props.toggle}> <ModalHeader toggle={this.props.toggle}>Modal title</ModalHeader> <ModalBody> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </ModalBody> <ModalFooter> <Button color="primary" onClick={this.props.toggle}>Do Something</Button>{' '} <Button color="secondary" onClick={this.props.toggle}>Cancel</Button> </ModalFooter> </Modal> </div> ); } } export default QuestionsModal; // class QuestionsContainer extends Component { // constructor(props) { // super(props); // const quizWords = []; // this.toggle = this.toggle.bind(this); // this.state = { // activeTab: '1', // quizWords // }; // } // toggle(tab) { // if (this.state.activeTab !== tab) { // this.setState({ // activeTab: tab // }); // } // } // // displayQuestions() { // // const data = this.props.data; // // if (data.loading) { // // return ( <div>Loading Questions...</div> ); // // } else { // // return dataQuizzes.map(quiz => { // // return ( // // ) // // }); // // } // // } // // client.query({ // // query: gql` // // getSingleQuizQuery($id: String!) { // // quiz (id: $id) { // // id // // quizName // // words { // // word // // definition // // } // // } // // }` // // }).then(response => console.log(response.data)) // render() { // // console.log(this.props); // const data = this.props.data; // const quizWordsArr = this.state.quizWords; // const pathnameId = this.props.urlPath.split('/')[2]; // // console.log(pathnameId); // // console.log(data.words.quiz.quizId); // // const query = gql` // // query GetQuizQuery($Id: String!) { // // quiz (id: $Id) { // // id // // quizName // // words { // // word // // definition // // } // // } // // } // // `; // // const params = { Id: this.props.quizId }; // // const result = graphql(query, null, null, params); // // console.log(result); // if (data.loading) { // return ( <p>Loading...</p> ); // } else { // // for (let word of data.words) { // // if (data.words.quizId === pathnameId) { // // quizWordsArr.push(word); // // } // // } // // console.log(quizWordsArr); // } // return ( // <div> // <Row> // <Nav tabs> // <NavItem> // <NavLink // className={classnames({ active: this.state.activeTab === '1' })} // onClick={() => { this.toggle('1'); }} // > // Tab1 // </NavLink> // </NavItem> // </Nav> // </Row> // <Row> // {/* { this.displayQuestions() } */} // <TabContent activeTab={this.state.activeTab}> // <TabPane tabId="1"> // <Row> // <Col sm="12"> // <h4>Tab 1 Contents</h4> // </Col> // </Row> // </TabPane> // </TabContent> // </Row> // </div> // ) // } // } // export default graphql // // (getSingleQuizQuery, { // // options: (props) => { // // return { // // variables: { // // id: props.quizId // // } // // } // // } // // }) // (getWordsQuery)(QuestionsContainer);
/** * Module dependencies. */ var mongoose = require('mongoose'), Match = mongoose.model('Match'), Bot = mongoose.model('Bot'), User = mongoose.model('User'); exports.retrieveLatest = function(skip, callback) { Match.find({}).sort('-completedOn').skip(skip).limit(20).populate('blackBot', 'name').populate('whiteBot', 'name').populate('winnerBot', 'name').exec(callback); } function findNextMatchPage(filter, skip, callback) { Match.find(filter) .sort('-completedOn') .skip(skip) .populate('blackBot', 'name') .populate('whiteBot', 'name') .populate('winnerBot', 'name') .limit(20) .exec(callback); } exports.retrieveLatestFiltered = function(skip, username, callback) { if (username) { User.findOne({username: username}).exec(function(err, user){ console.log(user); if (err) { return callback(err); } else if (!user) { callback(null, []); } else { Bot.find({ user: user._id }, '_id').exec(function(err, userBots){ if (err) { return callback(err); } else if (!userBots) { callback(null, []); } else { var botIds = []; for(i = 0; i < userBots.length; i++) { botIds.push(userBots[i]._id); } findNextMatchPage({ $or: [ {whiteBot: {$in: botIds}}, {blackBot: {$in: botIds}} ] }, skip, callback); } }) } }) } else { findNextMatchPage({}, skip, callback); } } exports.retrieveById = function(id, callback) { Match.findOne({_id:id}).populate('blackBot', 'name').populate('whiteBot', 'name').populate('winnerBot', 'name').exec(callback); }
const { importUserClient, mainFeedsCacheClient } = require('./redis'); const { LANGUAGES, TREND_NEWS_CACHE_PREFIX, HOT_NEWS_CACHE_PREFIX } = require('../constants'); /** * Add user name to namespace of currently importing users * @param userName {String} * @returns {Promise<void>} */ exports.addImportedUser = async (userName) => importUserClient.setAsync(`import_user:${userName}`, new Date().toISOString()); /** * Add user name to namespace of currently importing users * @param userName {String} * @param errorMessage {String} * @returns {Promise<void>} */ exports.setImportedUserError = async (userName, errorMessage) => importUserClient.setAsync(`import_user_error:${userName}`, errorMessage); /** * Delete user name from list currently imported users * @param userName {String} */ exports.deleteImportedUser = (userName) => importUserClient.del(`import_user:${userName}`); /** * Update list of TRENDING feed cache for specified locale * @param ids {[String]} list of posts "_id" * @param locale {String} locale of feed * @returns {Promise<void>} */ exports.updateTrendLocaleFeedCache = async ({ ids, locale }) => { if (!validateUpdateNewsCache(ids, locale)) return; await clearFeedLocaleCache(TREND_NEWS_CACHE_PREFIX); return mainFeedsCacheClient.rpushAsync([`${TREND_NEWS_CACHE_PREFIX}:${locale}`, ...ids]); }; /** * Update list of HOT news cache for specified locale * @param ids {[String]} list of posts "_id" * @param locale {String} locale of feed * @returns {Promise<void>} */ exports.updateHotLocaleFeedCache = async ({ ids, locale }) => { if (!validateUpdateNewsCache(ids, locale)) return; await clearFeedLocaleCache(HOT_NEWS_CACHE_PREFIX); return mainFeedsCacheClient.rpushAsync([`${HOT_NEWS_CACHE_PREFIX}:${locale}`, ...ids]); }; /** * Delete caches for feed by prefix for all locales * @param prefix {String} Namespace of feed cache * @returns {Promise<*>} */ async function clearFeedLocaleCache(prefix) { const keys = LANGUAGES.map((lang) => `${prefix}:${lang}`); return mainFeedsCacheClient.del(...keys); } function validateUpdateNewsCache(ids, locale) { if (!ids || !locale) { console.error('List of ids and locale must be specified'); return false; } if (!Array.isArray(ids)) { console.error('Ids must be an array'); return false; } if (!LANGUAGES.includes(locale)) { console.error('Locale must be from allowed list of languages'); return false; } return true; }
const tag = () => import('../pages/tag.vue') export default [{ path: '/tag/:tag', component: tag }, { path: '/tag/:tag/page/:page', component: tag }]
import {useRef} from 'react'; import Card from '../ui/Card'; import classes from './NewMeetupForm.module.css'; function NewMeetupForm(props){ const titleRef = useRef(); const urlRef = useRef(); const addressRef= useRef(); const descriptionRef = useRef(); function handleSubmit(event){ event.preventDefault(); let title = titleRef.current.value; let url = urlRef.current.value; let address = addressRef.current.value; let description = descriptionRef.current.value; const meetup_record = Object.assign({},{ title:title, image:url, address:address, description: description }); props.onAddMeetup(meetup_record); console.log(meetup_record); } return( <Card> <form className={classes.form} onSubmit={handleSubmit}> <div className={classes.control}> <label htmlFor="title">Title</label> <input type="text" required id={"title"} ref={titleRef}/> </div> <div className={classes.control}> <label htmlFor="title">Image Url</label> <input type="url" required id={"url"} ref={urlRef}/> </div> <div className={classes.control}> <label htmlFor="address">Address</label> <input type="text" required id={"address"} ref={addressRef}/> </div> <div className={classes.control}> <label htmlFor="description">Description</label> <textarea required id={"description"} rows={5} ref={descriptionRef}/> </div> <div className={classes.actions}> <button>Add Meetup</button> </div> </form> </Card> ) } export default NewMeetupForm;
function deleteDate( id ) { if ( confirm('Você tem certeza dessa ação?') ) { $('#delete-blacklist-form').attr('action', '/blacklist/'+id); $('#delete-blacklist-form').submit(); } }
 require(["ex1/Home", "ex1/Business"], function (Home, Business) { "use strict"; var hjemme = new Home("Hjemme", 59.922315, 10.49115, "A+M+M+M+H"); var hotellet = new Business("Hotellet", 61.229968, 7.098702); console.log(hjemme.toString()); console.log(hotellet.toString()); });
// 1 : Khai bao bien // var a = 5 // const b = 6 // a = 10 // b = 12 // console.log(a) // console.log(b) // 2 : Kieu du lieu // null // undenfined // Th1 : Khai bao 1 bien khong gan gia tri // var a // console.log(a) // TH2 : Truy van toi key khong ton tai cua object // const teo = { // name : "Nguyen Van Teo", // age : 10 // } // console.log(teo.address) // Th3 : Function khong return // function showName(name){ // console.log(name) // return // } // console.log(showName("Phat")) // 3 : Object // const teo = { // name : "Nguyen Van Teo", // age : 10 // } // console.log(teo.address) // 4 : Array // const arrayNames = ["Teo","Ti","Tun"] // arrayNames[0] = "Tuan" // console.log(arrayNames[0]) // mutable vs immutable // 5 : Toan tu // + - * / % , ++ , -- // Do uu tien cua toan tu // 1 : ++ -- // 2 : * , / // 3 : + , - // var a = 5 // var b = 6 // var ketqua = a++ - --b + --a + b-- + ++a - b++ + b-- - b++ // 5 - --b + --a + b-- + ++a - b++ + b-- - b++ a = 6 , b = 6 // 5 - 5 + --a + b-- + ++a - b++ + b-- - b++ a = 6 , b = 5 // 5 - 5 + 5 + b-- + ++a - b++ + b-- - b++ a = 5 , b = 5 // 5 - 5 + 5 + 5 + ++a - b++ + b-- - b++ a = 5 , b = 4 // 5 - 5 + 5 + 5 + 6 - b++ + b-- - b++ a = 6 , b = 4 // 5 - 5 + 5 + 5 + 6 - 4 + b-- - b++ a = 6 , b = 5 // 5 - 5 + 5 + 5 + 6 - 4 + 5 - b++ a = 6 , b = 4 // 5 - 5 + 5 + 5 + 6 - 4 + 5 - 4 a = 6 , b = 5 // 13 // console.log(ketqua) // ? (10 , 13 , 12) // 6 : Function // function showName(name){ // console.log(name) // return // } // console.log(showName("Phat")) // 7 : Object method // const teo = { // name : "Nguyen Van Teo", // age : 10, // info : function(){ // console.log("Name " + this.name) // console.log("Age " + this.age) // } // } // teo.info() // 8 : Phep so sanh // var a = {name : 'Teo'} // var b = a // b.name = "ti" // console.log(a.name) // console.log(null + 1) // 9 : Vong lap for // for (var i = 0 ; i < 10 ; i++){ // console.log(i) // } //10 : for in // Array // var arrayNames = ["Teo","Ti","Tun","Hoa","Tuan"] // Object // const teo = { // name : "Nguyen Van Teo", // age : 10, // info : function(){ // console.log("Name " + this.name) // console.log("Age " + this.age) // } // } // for (const key in teo) { // console.log(key) // } // Ví dụ var apartment = { bedroom: { area: 20, bed: { type: 'twin-bed', price: 100 } } }; function getkey(object){ for (const key in object) { console.log(key) if (typeof object[key] == "object"){ getkey(object[key]) } } // console.log(Object.keys(object)) } getkey(apartment) /** * Kết quả mong muốn: * bedroom * area * bed * type * price * Chú ý: không cần hiển thị ra đúng thứ tự như trên */
export const MORNING_MINUTES_LIMIT = 180 export const EVENING_MINUTES_LIMIT = 240 export const MAX_MINUTES_PER_TRAIL = 420 export const EVENT_TYPES = Object.freeze({ MEET: 'meet', BREAK: 'break' }) export const CATEGORIES = Object.freeze([ { name: 'Advanced Topics', color: '#1A55AF' }, { name: 'Beginner', color: '#FE9D2C' }, { name: 'Frontend', color: '#F7DF1E' }, { name: 'Backend', color: '#427A0A' }, { name: 'Test', color: '#FA5F1C' }, ])
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = process.env.PORT || 3005; const { createRouteRegistry } = require('../src/index.js'); app.use(bodyParser.json()); const openAPIRoot = { swagger: '2.0', info: { description: 'Example OpenAPI Document', version: '1.0.0', title: 'Express OpenAPI Document', contact: { email: 'me@example.com'} }, host: 'localhost:' + port, basePath: '/', tags:[], schemes: [ 'http', 'https'], paths: {} }; const postSchema = { type: 'object', properties: { title: { type: 'string' }, body: { type: 'string' }, author: { type: 'string' }, date: { type: 'string', format: 'date-time' }, tags: { type: 'array', items: { type: 'string' }}, }, required: ['title', 'body', 'author', 'date'] }; const { specRouter, serveSpec } = createRouteRegistry({router: app, openAPI: openAPIRoot}); const posts = []; const registerRoutes = (app) => { app.post('/posts', (req, res) => { const { body, title, author, tags, date } = req.body; const post = {body, title, date, author, tags}; posts.push(post); res.json(post); }, { description: 'save a post', operationId: 'savePost', parameters: [ { name: 'post', in: 'body', description: '', required: true, schema: postSchema } ], responses: { 200: { description: 'saved post', schema: postSchema } } }); app.get('/posts', (req, res) => { res.json(posts); }, { description: 'get list of posts', responses: { 200: { description: 'list of all posts', schema: { type: 'array', items: postSchema } } } }); }; registerRoutes(specRouter); serveSpec({app, express}); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
var Player = function(playerID){ this.playerID = playerID; this.isMainPlayer= false; this.mesh; console.log("ID asignado a este player: " + playerID); var scope = this; this.init = function(){ // Load a glTF resource // loader.load('/client/js/mono.glb', loader.load('/client/assets/mono.glb', function ( gltf ) { model=gltf.scene; scene.add(model); gltf.animations; // Array<THREE.AnimationClip> gltf.scene; // THREE.Group gltf.scenes; // Array<THREE.Group> gltf.cameras; // Array<THREE.Camera> gltf.asset; // Object scope.mesh=model; if(scope.isMainPlayer){ //dar controles de esta instancia controls = new THREE.PlayerControls(camera, scope.mesh); controls.init(); }; }, // called while loading is progressing function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } ); // }; this.setOrientation = function(position, rotation){ if(scope.mesh){ scope.mesh.position.copy(position); scope.mesh.rotation.x=rotation.x; scope.mesh.rotation.y=rotation.y; scope.mesh.rotation.z=rotation.z } }; };
const stringTimes = (word, num) => { let apple = ''; Array(num).fill().forEach(() => { apple += word }) return apple } console.log(stringTimes('Hi', 3)) console.log(stringTimes('Hi', 2)) console.log(stringTimes('Hi', 1))
import { SET_NAME_PRACTICE, SET_LOCATION_PRACTICE, SET_EMAIL_PRACTICE, GET_IMAGES_BY_EMAIL, SAVE_IMAGES_ON_DEVICE, SET_VALIDATE_EMAIL, } from '../constants/ActionTypes' export function setValidateEmail(bool) { return { type: SET_VALIDATE_EMAIL, payload: { bool } } } export function setGetImagesByEmail(bool) { return { type: GET_IMAGES_BY_EMAIL, payload: { bool } } } export function setSaveImagesOnDevice(bool) { return { type: SAVE_IMAGES_ON_DEVICE, payload: { bool } } } export function setPracticeName(name) { return { type: SET_NAME_PRACTICE, payload: { name } } } export function setPracticeLocation(location) { return { type: SET_LOCATION_PRACTICE, payload: { location } } } export function setPracticeEmail(email) { return { type: SET_EMAIL_PRACTICE, payload: { email } } }
module.exports = { mongoDb_Atlas_URL: "YWRtaW46YWRtaW4xMjNAY2x1c3RlcjAuc2dtbGsubW9uZ29kYi5uZXQvbXlEQg==" }
/************** * @package WordPress * @subpackage Cuckoothemes * @since Cuckoothemes 1.0 * URL http://cuckoothemes.com **************/ jQuery(document).ready(function($){ $("#cuckoo-contact-form").submit(function() { var contactSubmit = $(this); if(typeof contactSubmit != "undefined"){ var name = $(this).find(":input[type=text]#contact_name").val(), email = $(this).find(":input[type=email]#email_contact").val(), content = $(this).find("textarea#contact_message").val(), numbers = $(this).find(":input.amount-checker").val(); preloderColor = $(this).find(":input[type=hidden][name=style-theme]").val(); amount = $(this).find(":input[type=hidden][name=amount-cuckoo]").val(); if( name == '') { $(this).find(":input[type=text]#contact_name").css("border", "1px solid red"); } if( content == '' ) { $(this).find("textarea#contact_message").css("border", "1px solid red"); } if( email == '' ) { $(this).find(":input[type=email]#email_contact").css("border", "1px solid red"); } if( name == '' || content == '' || email == '' ) { return false; }else{ if(contactSubmit.find('#number_checked').css('display') == 'none'){ var heightNumbers = $('.map-baqckground').height()-$('#contact').find('.item-header-wrap').height(), widthNumbers = $('.contact-content').width(); contactSubmit.find('#number_checked').css({'width': widthNumbers, 'height': heightNumbers}).fadeIn('slow'); $('.show-map').css('z-index', 4); return false; }else{ if( numbers == '' ) { $(this).find(":input.amount-checker").css("border", "1px solid red"); return false; }else{ if( numbers == amount ){ contactSubmit.find('#number_checked').fadeOut(800); var str = $(this).serialize(), heightPreload = $('.map-baqckground').height(), marginTop = $('#contact').find('.item-header-wrap').height(); contactSubmit.parent().parent().append('<div class="form-preload"><div class="img-loader"></div><div class="circle_preload"></div></div>').find(".form-preload").css({'height': heightPreload, 'margin-top': marginTop }).fadeIn(); $.ajax({ type: 'POST', url: contactajaxcuckoo.ajaxurl, data: 'action=contact_form&'+str, success: function(msg) { $("#result").ajaxComplete(function(event, request, settings){ $('.form-preload').find('.img-loader').fadeOut('slow'); $('.form-preload').find('.circle_preload').fadeOut('slow'); if( msg == 0 ){ $(this).append('<p class="error">An error has occurred while sending your email!</p>'); }else{ $(this).html(msg); } if($(this).css('display') == 'none'){ $(this).fadeIn(800,function(){ contactSubmit.find(":input[type=text]#contact_name").attr('value',''); contactSubmit.find(":input[type=email]#email_contact").attr('value',''); contactSubmit.find("textarea#contact_message").attr('value',''); contactSubmit.find(":input[type=text].amount-checker").attr('value',''); contactSubmit.find(".form_label_logs_name").css('top', 6); contactSubmit.find(".form_label_logs_email").css('top', 6); contactSubmit.find(".form_label_textarea").css('top', 6); }).delay(2000).fadeOut(800, function(){ $('.form-preload').fadeOut('slow', function(){ $('.show-map').css('z-index', 5); $(this).remove(); $('#result').find('p').remove(); }); }); } }); } }); }else{ $(this).find(":input.amount-checker").css("border", "1px solid red"); return false; } } } } } return false; }); });
$(document).ready(function () { $('#chkViewAll').change(function () { ViewAllTickets(); }); }); var ViewAllTickets = function () { if ($('#chkViewAll').is(':checked')) { url = $('#lnkShowAll').val(); window.location.href = url; } else { url = $('#lnkShowClosed').val(); window.location.href = url; } }
const albumModel = require('../model/albumModel'); //We need to require path & multer dependencies const path = require('path'); //Get multipart & asigns different keys. Parse files from forms to object const multer = require('multer')({ //Specifying final destination for uploads dest: 'public/uploads' }); const fs = require('fs'); const util = require('util'); const controller = {}; //fileUploader using path, util & fs controller.storeWithOriginalName = (file) => { //Establishing unique ID (using new date) + filename var idDate = new Date(); var prefixFilename = idDate.getTime() + '_' + idDate.getMilliseconds(); let filename = prefixFilename + '_' + file.originalname; //Establishing path destination+filename const fullnewPath = path.join(file.destination, filename); //util is a package with utilities, in this case, we use it for promisify const rename = util.promisify(fs.rename); //promisify converts async blocker into a sync //file.path is a temporary route return rename(file.path, fullnewPath) .then(() => { //We return the filename when all actions are done return filename; }) .catch((err) => { console.error('err'); }) } controller.add = (req, res, _next) => { const myAlbum = new albumModel({ name: req.body.name, releaseYear: req.body.releaseYear }); myAlbum.save((err, obj) => { if (err) { console.error('UGHH! Error', err) } else { res.redirect('/albums/list/?addedId=' + obj._id) } }); } //for rendering FRONTEND) controller.addForm = (_req, res, _next) => { res.render('albums/form', { mode: 'add', data: {}, title: 'Add record', coverEmpty: true }) } controller.editForm = (req, res, _next) => { //We 're finding by id. All functions of mongo are promises by default albumModel.find({ _id: req.params.id }) .then((obj) => { res.render('albums/form', { mode: 'edit', //find always returns an array (as mysql consults) data: obj[0], coverEmpty: false, title: 'Edit record: ' + obj[0]._id }) }) .catch((err) => { res.send('ERROR: ' + err); }) } //functional methods //We need to use async, because file need to be uploaded before the consult controller.edit = async (req, res, next) => { //establishing default types of file (we need to restrict to user) const fileTypes = ['image/png', 'image/jpeg'] //We're receiveng an object directly, so we dont need to use new albumModel let newObj = { name: req.body.name, releaseYear: req.body.releaseYear }; if (req.file) { if (fileTypes.includes(req.file.mimetype) && req.file.size < 6291456) { //Using function to store the file. Using await for await the file upload const storeFileOperation = await controller.storeWithOriginalName(req.file) //For encode a string as URL component .then(encodeURIComponent) .then(encoded => { newObj.coverFilename = encoded; }) .catch(next); } } albumModel.updateOne({ _id: req.params.id }, newObj, (err, raw) => { if (err) { console.error('DAMMMMN! There was an error', err); } else { console.log('Guardado y redirigir: ', raw); res.redirect('/albums/list/?editedId=' + req.params.id); } }); } controller.del = (req, res, next) => { albumModel.findOne({ _id: req.params.id }) .then((obj) => { //We save filename from database, and then we delete it if exists const fileName = obj.coverFilename; const wasFileDeleted = fs.unlinkSync(`/uploads/${fileName}`); if (wasFileDeleted) { albumModel.deleteOne({ _id: req.params.id }, (err, result) => { if (err) { console.error('DAMMMMN! There was an error', err); } else { console.log('Guardado y redirigir: ', result); res.redirect('/albums/list/?deletedId=' + req.params.id); } }) } }) .catch((err2) => { console.error('Cannot get database info', err2); }) } controller.list = (req, res, _next) => { //req.query returns params specified in url starting with ?. Example: ?addedId=X const recordWasAdded = ('addedId' in req.query); albumModel.find({}) //We dont need to await another consults, so we dont use async in this case .then((objs) => { let theMessage = null; //Checking if we have a query in URL (add model adds a QUERY to the URL) if (recordWasAdded) theMessage = 'Artist added! ID =' + req.query.addedId; res.render('albums/list', { data: objs, message: theMessage }) }) .catch((err) => { res.send('ERROR: ' + err) }) } module.exports = controller;
import { domain } from './domain' export const incrementLoading = domain.event('incrementLoading') export const decrementLoading = domain.event('decrementLoading') export const loading = domain.store(0, {name: 'loading'}) .on(incrementLoading, val => val + 1) .on(decrementLoading, val => val - 1)
window.onload = function() { document.getElementById("js-search-input").focus(); } function post(path, params, method) { method = method || "post"; var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit(); } function interpretSearch() { var search = document.getElementById("js-search-input").value.split(" "); var searchTerms = ""; console.log(search[0]) switch(search[0]) { case '?': alert("c: 4chan\nr: reddit\ng: github\nt: twitch\njp: 日本語 dictionary\nyt: youtube\nwa: wolfram alpha\n"); break; case 'c:': window.location.href = "https://4chan.org/" + search[1]; return false; case 'r:': window.location.href = "https://reddit.com/r/" + search[1]; return false; case 'g:': window.location.href = "https://github.com/" + search[1]; return false; case 't:': window.location.href = "https://twitch.tv/" + search[1]; return false; case 'jp:': window.location.href = "https://www.japandict.com/" + search[1]; return false; case 'yt:': for(var i = 1; i < search.length; i++) { searchTerms += search[i]+'+'; } window.location.href = "https://youtube.com/results?search_query=" + searchTerms; return false; case 'wa:': for(var i = 1; i < search.length; i++) { searchTerms += search[i]+'+'; } window.location.href = "https://www.wolframalpha.com/input/?i=" + searchTerms; return false; default: searchTerms += search[0] for(var i = 1; i < search.length; i++) { searchTerms += ' '+search[i]; }; if(searchTerms.indexOf('.') !== -1) { window.location.href = "https://" + searchTerms; } else { post("https://startpage.com/do/search", {query: searchTerms, t: "night"}); } return false; } };
$('#event-pdf').click(function () { var pdf = new jsPDF('l', 'pt', 'legal'); source = $('#event-table')[0]; specialElementHandlers = { '#bypassme': function (element, renderer) { return true } }; margins = { top: 20, bottom: 20, left: 20, width: 522 }; pdf.fromHTML( source, margins.left, margins.top, { 'width': margins.width, 'elementHandlers': specialElementHandlers }, function (dispose) { pdf.save('Test.pdf'); }, margins); });
import React, { Component } from 'react'; import Input from './input' import Form from './form' import Joi from "joi" class LoginForm extends Form { state = { data :{ username: "", password: "" }, errors:{} } schema = { username: Joi.string().required().label('Username'), password: Joi.string().required().label('Password') } makeSubmit = ()=>{ } render() { return ( <div class="offset-md-2 col-6"> <form onSubmit={this.handleSubmit}> {this.createInput("username","username")} {this.createInput("password","password","passWord")} {this.createButton("Submit")} </form> </div> ); } } export default LoginForm;
const angles = document.querySelectorAll('.angle-input'); const btn = document.querySelector('#btn'); const outputBlock = document.querySelector('#block__output'); const sumOfAngles = (angle1, angle2, angle3) => angle1 + angle2 + angle3; const isTriangle = () => { if ( angles[0].value === '' || angles[1].value === '' || angles[2].value === '' ) { outputBlock.innerText = 'Please enter the input values'; } else { const sum = sumOfAngles( Number(angle1.value), Number(angle2.value), Number(angle3.value) ); if (sum === 180) { outputBlock.innerText = 'Yay! Its a Triangle'; } else { outputBlock.innerText = 'Not a Triangle!'; } } }; btn.addEventListener('click', isTriangle);
const Navigation = { init: function (){ this.addListeners(); }, addListeners: function(){ let nav = $('.nav-top') let menu = $('.side-menu') let closeMenu = $('.close-menu') nav.on('click', event => { menu.removeClass('hidden') }) closeMenu.on('click', event => { menu.addClass('hidden') }) } } const Float = { init: function(){ this.addSlick(); }, addSlick: function(){ $('.section-float').slick({ infinite: false, autoplay: true, autoplaySpeed: 2500, }); } } const News = { init: function(){ this.addListeners(); }, addListeners: function(){ let news = $('.float-news') let open = $('.news-open') let closeNews = $('.close-news') let layer = $('.layer') news.on('click', event => { open.removeClass('news-hidden') layer.addClass('layer-active') }) closeNews.on('click', event => { open.addClass('news-hidden') layer.removeClass('layer-active') }) } } const Paterns = { init: function(){ this.addSlick(); }, addSlick: function(){ $('.partners').slick({ infinite: true, slidesToShow: 3, slidesToScroll: 1, autoplay: true, autoplaySpeed: 2500, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 1, infinite: true, } }, { breakpoint: 600, settings: { slidesToShow: 2, slidesToScroll: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] }); } } const MaskForm = { init: function () { this.includeMask(); }, includeMask: function () { $('#tel1').mask('(00)'); $('#tel2').mask('00000-0000'); $('#cep').mask('00000-000'); }, }; const AdressForm = { init: function () { this.addListeners(); }, addListeners: function () { let cepInput = document.querySelector('#cep'); let para = document.querySelector('.para'); cepInput.addEventListener('keyup', (event) => { const { value } = event.target; if (value.length === 9) { $.ajax(`https://brasilapi.com.br/api/cep/v1/${value}`) .then((response) => { document.getElementById('street').value = response.street; document.getElementById('neighborhood').value = response.neighborhood; document.getElementById('city').value = response.city; document.getElementById('state').value = response.state; para.textContent = ''; }) .catch(() => { para.textContent = 'Digite um CEP válido!'; para.classList.add('paraError'); }); } }); }, }; Navigation.init(); Float.init(); News.init(); Paterns.init(); MaskForm.init(); AdressForm.init();
import React, { Component } from 'react'; import Carousel from 'nuka-carousel'; import Slide from './Slide' import './PizzaSlider.css'; class PizzaSlider extends Component { render() { var Decorators = []; return ( <div className="container"> <div className="row"> <Carousel className="hidden-xs" decorators={Decorators} wrapAround={true} slidesToShow={3} cellSpacing={0} > {this.props.items.map((item) => <Slide key={item.id} id={item.id} name={item.name} image={item.image} smallprice={item.smallprice} smallsize={item.smallsize} bigprice={item.bigprice} bigsize={item.bigsize} desc={item.desc} consist={item.consist} addOrder={this.props.onAdd} /> )} </Carousel> <div className="col-sm-12 hidden-lg hidden-md hidden-sm"> <div className="menu"> {this.props.items.map((item) => <Slide key={item.id} id={item.id} name={item.name} image={item.image} smallprice={item.smallprice} smallsize={item.smallsize} bigprice={item.bigprice} bigsize={item.bigsize} consist={item.consist} addOrder={this.props.onAdd} /> )} </div> </div> </div> </div> ); } } export default PizzaSlider;
const fs = require('fs-extra'); const path = require('path'); const chokidar = require('chokidar'); const enfsensure = require('enfsensure'); const ffmpeg = require('fluent-ffmpeg'); if (/^win/.test(process.platform)) { ffmpeg.setFfmpegPath(path.resolve(__dirname + '/../../../bin/ffmpeg')); ffmpeg.setFfprobePath(path.resolve(__dirname + '/../../../bin/ffprobe')); } let data_path = process.env.data_path || path.join(__dirname + '../../../data'); const Video = require('../db/models/video'); module.exports = { init: function (app, conf) { if (!app.watchers) app.watchers = []; let pathCh = path.resolve(data_path, 'videos', conf.id, 'temp'); enfsensure.ensureDir(pathCh, (err) => { if (err) console.log(err); app.watchers[conf.id] = chokidar.watch(pathCh, { ignoreInitial: true }).on('add', function (_path, stats) { if (this.previousVideoFile) { if (conf.motionDetection.enable && (!this.detectionDate || this.detectionDate < this.previousVideoFile.stats.birthtime)) { fs.unlink(this.previousVideoFile.path, (err) => { if (err) console.error(err); console.log('removed videofile:', this.previousVideoFile.path); this.previousVideoFile = { path: _path, stats: stats } }); } else { let dstpath = path.resolve(data_path, 'videos', conf.id, path.basename(this.previousVideoFile.path)); fs.move(this.previousVideoFile.path, dstpath, { overwrite: true }, (err) => { if (err) console.error(err); console.log('added videofile:', dstpath); ffmpeg.ffprobe(dstpath, (err, metadata) => { let start = new Date(this.previousVideoFile.stats.birthtime); let end = new Date(new Date(this.previousVideoFile.stats.birthtime).getTime() + metadata.format.duration * 1000); let newVideo = new Video({ sourceId: conf.id, filename: path.basename(dstpath), start: start.getTime(), end: end.getTime(), duration: metadata.format.duration * 1000 }); newVideo.save(err => { if (err) console.error(err); }) this.previousVideoFile = { path: _path, stats: stats } }); }); } } else { this.previousVideoFile = { path: _path, stats: stats } } }); }); function cleanTemp() { fs.readdir(pathCh, (err, files) => { if (files && files.length > 0) files.forEach(file => { let p = path.resolve(pathCh, file); fs.stat(p, (err, stats) => { if (err) console.log(err); let start = new Date(stats.birthtime).getTime(); let now = new Date().getTime(); if ((now - start) > 1000 * 60 * 60) { fs.unlink(p, (err) => { if (err) console.error(err); }); } }); }); }); } cleanTemp(); setInterval(cleanTemp, 1000 * 60 * 60); }, startVideoRecorder: function (nodeConf, processes) { let name = 'video_' + nodeConf.id; if (!processes[name]) processes[name] = {}; let cwd = path.resolve(data_path, 'videos', nodeConf.id, 'temp'); function createFFMpegProc(url) { return ffmpeg(url) .videoCodec('copy') .audioCodec('aac') .outputOptions( '-f', 'segment', '-segment_time', nodeConf.motionDetection.enable ? '60' : '600', '-segment_format', 'mp4', '-strict', '-2', '-reset_timestamps', '1', '-strftime', '1' ) .on('start', (cmd) => { console.log(name, 'started:', cmd); }) .on('error', (err) => { if (err) console.error(err.message); processes[name].retry ? processes[name].retry++ : processes[name].retry = 1; if (processes[name] && processes[name].proc && !processes[name].end && processes[name].retry <= 5) module.exports.startVideoRecorder(nodeConf, processes); if (processes[name] && processes[name].retry > 5) { setTimeout(function () { processes[name].retry = 1; module.exports.startVideoRecorder(nodeConf, processes); }, 1000 * 60 * 10) } }) .on('end', (a) => { if (processes[name] && processes[name].proc && !processes[name].end) module.exports.startVideoRecorder(nodeConf, processes); }) .save(path.resolve(cwd, '%Y%m%d-%H%M%S.mp4')); } enfsensure.ensureDir(cwd, (err, pth) => { if (err) return console.error(err); if (nodeConf.device.type == 'TRASSIR_Cloud') { const TRASSIR_Cloud = require('../rtsp2/trassir_cloud'); TRASSIR_Cloud.get_video(nodeConf.videoRecording.uri, (err, new_url) => { if (err) return console.error(err); if (!new_url && !processes[name].proc) { return setTimeout(function() { module.exports.startVideoRecorder(nodeConf); }, 5000); } else { processes[name].proc = createFFMpegProc(new_url); } }); } else { processes[name].proc = createFFMpegProc(nodeConf.videoRecording.uri); } }); }, deleteVideoRecorder: function (id, processes, cb) { let name = 'video_' + id; console.log(name, 'stopped'); processes[name].end = true; setTimeout(() => { processes[name].proc.ffmpegProc.stdin.write('q'); delete processes[name]; if (cb) cb(); }, 2500); } }
(function () { 'use strict' window.GOVUK = window.GOVUK || {} function WordsToAvoidAlerter (wordsToAvoidRegexps, options) { var $el = $(options.el) var $wordsToAvoidAlert = $(options.wordsToAvoidAlert) var $alertCount = $('<strong />').attr('id', 'js-words-to-avoid-count') var wordsToAvoidMatcher = new RegExp('(' + wordsToAvoidRegexps.join('|') + ')', 'gi') var wordsToAvoidUsedSpan = $('<span />').attr('id', 'js-words-to-avoid-used') var initAlertMessageTemplate = function () { $wordsToAvoidAlert.append($alertCount) if (options.highlightingEnabled) { $wordsToAvoidAlert.append(' highlighted word(s) appear on the words to avoid list:') } else { $wordsToAvoidAlert.append(' word(s) appear on the words to avoid list:') } $wordsToAvoidAlert.append(wordsToAvoidUsedSpan) } initAlertMessageTemplate() var wordsToAvoidUsed = function () { if (options.highlightingEnabled) { // use optimised way and look for highlighted words return $.distinct($.map($('.highlighter span.highlight'), function (highlightedEl) { return $(highlightedEl).text() })) } else { var textToSearchIn = [] $el.each(function () { textToSearchIn.push($(this).val()) }) return $.distinct(textToSearchIn.join(' ').match(wordsToAvoidMatcher) || []) } } var numberOfWordsToAvoidUsed = function () { if (options.highlightingEnabled) { return $('.highlighter span.highlight').length } else { return wordsToAvoidUsed().length } } var listOfWordsToAvoidUsed = function () { var _wordsToAvoidUsed = wordsToAvoidUsed() var list = $.map(_wordsToAvoidUsed, function (word) { return $('<li />').html(word) }) return $('<ul />').append(list) } var $updateAlert = function () { var _numberOfWordsToAvoidUsed = numberOfWordsToAvoidUsed() if (_numberOfWordsToAvoidUsed) { $wordsToAvoidAlert.removeClass('hide').show() $(options.wordsToAvoidCounter).html(_numberOfWordsToAvoidUsed) $(wordsToAvoidUsedSpan).html(listOfWordsToAvoidUsed()) } else { $wordsToAvoidAlert.hide() } } $el.debounce('keyup', $updateAlert, 500) $updateAlert() var disable = function () { $wordsToAvoidAlert.hide() } $(document).bind('govuk.WordsToAvoidGuide.disable', disable) var enable = function () { $updateAlert() } $(document).bind('govuk.WordsToAvoidGuide.enable', enable) } GOVUK.WordsToAvoidAlerter = WordsToAvoidAlerter }())
var $window = $(window), $body = $('body'), $document = $(document); (function($){ dl.create = function(s){ s = objectval(s); var d = document.createElement(s.name || 'x'), e = $(d); if(is_string(s.src))d.src = s.src; if(is_object(s.attr))e.attr(s.attr); if(is_object(s.css))e.css(s.css); if(is_string(s.html))e.html(s.html); if(is_string(s.text))e.text(s.text); if(is_string(s['class']))e.addClass(s['class']); return e; }; $.fn.less = function(){ if(!is_object(less))return; less.render($(this).text(),function(e,s){ $body.append(dl.create({name:'style',text:s.css})); }); }; $("script[type='text/less']").less(); })(jQuery); var app = angular.module('app', [ ]); app.config([function(){}]); app.controller('ScopeCtrl',function($scope){}); app.run(['$rootScope',function($rootScope){ $rootScope['if'] = function(v,thenV,elseV){return v ? thenV : (elseV === undefined ? '' : elseV);}; $rootScope['int'] = intval; var apply = function(){ $rootScope.$apply(); }, loader = $rootScope.loader = function(options){ options = objectval(options); var s = { src: objectval(options.src), loading: 0 }, c, dst = s.dst = {percent:0,offset:0,total:0,k:0}; cancel = s.cancel = function(){ if(is_func(c))c(); s.loading = 0; dst.percent = dst.offset = 0; dst.total = 0; }, runOptions = {}, args = [], callback = function(success,filename,url){ args = arguments; if(s.loading)delayt.run(runOptions.delay); return success; }, progress = function(e){ if(!s.loading)return; console.log( 'Получено с сервера ' + e.loaded + ' байт' + (e.lengthComputable ? (' из ' + e.total) : '. Общий объем неизвестен' ) ); var lengthComputable = dst.lengthComputable = e.lengthComputable, offset = dst.offset = e.loaded, total = dst.total = lengthComputable ? e.total : ( 10000 + offset ), k = dst.k = offset / total; dst.percent = (100 * k).toFixed(2); apply(); var cb = options.progress; if(is_func(cb))cb(e); }, callb = function(success,filename,url){ console.log('Файл "' + filename + '" ' + (success ? 'успешно' : 'не') + ' скачен!'); var cb = options.callback; if(is_func(cb))cb.apply(null,arguments); s.loading = 0; apply(); }, delayt = new dl.Timeout({ callback: function(){callb.apply(null,args);} }), waitt = new dl.Timeout({ callback: function(){ s.loading = 1;} }); s.run = function(options){ runOptions = objectval(options); cancel(); dst.total = 10000; var src = objectval(s.src); waitt.run(runOptions.wait); c = dl.download(src.url, callback, progress, src.name); }; return s; }; }]);
$(document).ready(function(){ //If guest is true, hide the profile icon var guest = window.localStorage.getItem('guest'); console.log(guest); if (guest == 'true'){ console.log("Guest is true"); //hide the profile icon $('#profileBtn').hide(); } else { console.log("Guest is false"); } var place = window.localStorage.getItem('place'); console.log(place); if (place == 'bathroom1'){ console.log('Bathroom1 selected'); $('#myMap').attr('src', "https://maps.mapwize.io/#/f/p/ucsd/entrance/t/p/ucsd/bathroom_1?k=5917a04807958398&z=21.176"); } else if (place == 'bathroom2'){ console.log('Bathroom2 selected'); $('#myMap').attr('src', "https://maps.mapwize.io/#/f/p/ucsd/entrance/t/p/ucsd/bathroom_east_2?k=5917a04807958398&z=21.165"); } else if (place == 'bathroom8'){ console.log('Bathroom8 selected'); $('#myMap').attr('src', "https://maps.mapwize.io/#/f/p/ucsd/entrance/t/p/ucsd/gn_bathroom?k=5917a04807958398"); } else if (place == 'Classroom'){ console.log('Classroom selected'); $('#myMap').attr('src', "https://maps.mapwize.io/#/f/p/ucsd/entrance/t/p/ucsd/classroom_1?k=5917a04807958398&z=21.025"); } else if (place == 'audreys'){ $('#myMap').attr('src', "https://maps.mapwize.io/#/f/p/ucsd/entrance/t/p/ucsd/audrey_s?k=5917a04807958398&z=20.34"); } else if (place == 'geisel_study'){ $('#myMap').attr('src', "https://maps.mapwize.io/#/f/p/ucsd/entrance/t/p/ucsd/group_study_room?k=5917a04807958398"); }else if (place == 'nursing'){ $('#myMap').attr('src', "https://maps.mapwize.io/#/f/p/ucsd/entrance/t/p/ucsd/bathroom_east_2_2?k=5917a04807958398&z=20.711"); } else if (place == 'csb'){ $('#myMap').attr('src', "https://maps.mapwize.io/#/f/p/cognitive_science_building/csb_180/t/p/cognitive_science_building/bathroom_m?k=32c095f4e615a71b&z=19.895"); } else { $('#myMap').attr('src', "https://maps.mapwize.io/#/v/ucsd/0?k=5917a04807958398&z=18"); } });
var showCollection = angular.module("showCollection",['ngRoute']); showCollection.config(function($routeProvider){ $routeProvider.when("/",{ templateUrl:"views/collection.html", controller:"TodoCTRL" }); $routeProvider.when("/swag",{ template:"<h1>SWAG!</h1>" }); $routeProvider.otherwise({ template:"<b>Sorry, nothing found, only a 404 :(</b>" }); }); showCollection.controller("TodoCTRL",function($scope,$http){ //$scope.sections = [{text:"SWAG"},{text:"SWAG2"} //] function getSections(){ $http({method: 'GET', url: '/getsections'}). success(function(data) { $scope.sections = data; $(".collection").css("width",$scope.sections.length*275+275); $(".collection").css("height",$(window).height()-90); $.jInvertScroll(['.collection']); }); } function getTodos(){ $http({method: 'GET', url: '/gettodos'}). success(function(data) { $scope.todos = data; }); }; getSections(); getTodos(); //Actions for sections $scope.SectionADD = function(value){ if(value!=null){ $http({method: 'GET', url: '/getsections?query=insert&text='+value}). success(function(data) { getSections(); }); $(".EditSection").val(""); }else{ $(".EditSection").attr("placeholder","Enter something :)"); } } $scope.updateSection = function(id,text,statusold){ if(text!=null){ $http({method: 'GET', url: '/getsections?query=update&id='+id+'&text='+text}). success(function(data) { getSections(); }) $http({method: 'GET', url: '/gettodos?query=updateSection&statusold='+statusold+'&status='+text}). success(function(data) { getTodos(); }); $(".EditSection").val(""); }else{ $(".EditSection").attr("placeholder","Enter something :)"); } } $scope.removeSection = function(id,status){ $http({method: 'GET', url: '/getsections?query=remove&id='+id}). success(function(data) { getSections(); }); $http({method: 'GET', url: '/gettodos?query=removeAllFromSection&status='+status}). success(function(data) { getTodos(); }); }//Actions for todos $scope.TodoADD = function(status,value){ if(value!=null){ $http({method: 'GET', url: '/gettodos?query=insert&text='+value+'&status='+status}). success(function(data) { getTodos(); }); $(".text-input").val(""); }else{ $(".text-input").attr("placeholder","Enter something :)"); } } $scope.update = function(id,status){ $http({method: 'GET', url: '/gettodos?query=update&id='+id+'&status='+status}). success(function(data) { getTodos(); }) } $scope.remove = function(id){ $http({method: 'GET', url: '/gettodos?query=remove&id='+id}). success(function(data) { getTodos(); }); } });